@ngdoc function
@name login
@methodOf auth.service:Auth
@description
Authenticate user and save token

@param {Object} user login info
@param {Function} [callback] A callback
@return {Promise} A promise
516588
function login(user, callback) {
      /* jshint validthis:true */
      var cb = callback || angular.noop;
      var deferred = $q.defer();
      $cookies.customerId = user.customerId;

      $http.post('/auth/local', {
        customerId: user.customerId,
        name: user.name,
        password: user.password
      }).success(function (data) {
        $cookieStore.put('token', data.token);
        $cookieStore.remove('customerID');
        currentUser = User.get();
        deferred.resolve(data);
        return cb();
      }).error(function (err) {
        this.logout();
        deferred.reject(err);
        return cb(err);
      }.bind(this));

      return deferred.promise;
    }
636607
function authorize(passport, name, options, callback) {
  options = options || {}
  options.assignProperty = 'account'

  return authenticate(passport, name, options, callback)
}
601008
function(credentials){
      var socialLogin = false;
      if (credentials == undefined){
        credentials = {
          userid: $('#login_email').val(),
          password: $('#login_password').val()
        };
      } else if (typeof credentials === 'string'){
        socialLogin = true;
      }

      // Alter the UI to indicate that the login request is pending
      $('#login_button').attr('value', 'Logging in...');
      $('#register_button, #or').hide();

      var login = socialLogin ? cm.loginSocial.bind(cm) : cm.login.bind(cm);

      function loginError(msg){
        $('#login_button').attr('value', 'Login');
        $('#register_button, #or').show();
        todo.error('login', msg);
      }

      // Run CloudMine login request.
      login(credentials)
        .on('success', function(data){
          var services = data.profile.__services__;
          if(services){
            console.log("linked services:", services);
            data.profile.__services__.forEach(function(service){
              $('a.auth.' + service).hide();
            });
          }
          todo.process_login(data);
        })
        .on('unauthorized', function(data){
          loginError(data.errors[0]);
        })
        .on('error', function(data){
          loginError(data.errors ? data.errors[0] : "Error Logging in");
        })
    }
174408
def authenticate(&callback)
      user("me") do |user|
        self.token = user.token
        callback.call(user)
      end
    end
1028652
function initLogin(callback) {
	debug('Getting login');
	request.get({ 
			url: psnURL.SignIN
			, headers : {
				'User-Agent': userAgent
				,'X-Requested-With': requestedWith
			}
		}
		, function (error, response, body) {
			//console.log(error);
			if (body) {
				var $ = cheerio.load(body);
				var new_paramString = $('#brandingParams').attr("value");
				getLogin(callback, psnURL.SignIN)
			}
			else {
				debug('ERROR: ' + error)
			}
	})
}
369398
function login(user = {
    username: settings.username,
    password: settings.password
}) {
    return __awaiter(this, void 0, void 0, function* () {
        log_1.logger.info(`[API] Logging in ${user.username}`);
        if (exports.currentLogin !== null) {
            log_1.logger.debug(`[API] Already logged in`);
            if (exports.currentLogin.username === user.username) {
                return exports.currentLogin.result;
            }
            else {
                yield logout();
            }
        }
        const result = yield post('login', user, false);
        if (result && result.data && result.data.authToken) {
            exports.currentLogin = {
                result: result,
                username: user.username,
                authToken: result.data.authToken,
                userId: result.data.userId
            };
            setAuth(exports.currentLogin);
            log_1.logger.info(`[API] Logged in ID ${exports.currentLogin.userId}`);
            return result;
        }
        else {
            throw new Error(`[API] Login failed for ${user.username}`);
        }
    });
}
172666
function parseClientAuth(data, callback) {
  authParser.parseAuth(data, function(err, data) {
    if (err) callback(err, null);
    callback(null, data);
  });
}
1254041
function (error, result) {
    // If the login method returns its result but the connection is lost
    // before the data is in the local cache, it'll set an onReconnect (see
    // above). The onReconnect will try to log in using the token, and *it*
    // will call userCallback via its own version of this
    // loggedInAndDataReadyCallback. So we don't have to do anything here.
    if (reconnected)
      return;

    // Note that we need to call this even if _suppressLoggingIn is true,
    // because it could be matching a _setLoggingIn(true) from a
    // half-completed pre-reconnect login method.
    Accounts._setLoggingIn(false);
    if (error || !result) {
      error = error || new Error(
        "No result from call to " + options.methodName);
      onceUserCallback(error);
      return;
    }
    try {
      options.validateResult(result);
    } catch (e) {
      onceUserCallback(e);
      return;
    }

    // Make the client logged in. (The user data should already be loaded!)
    makeClientLoggedIn(result.id, result.token, result.tokenExpires);
    onceUserCallback();
  }
595916
function (data) {
			//console.log("login_data");
			//console.log(data);
			if (data === null) {
				var err = new Error("ACCOUNT_NOT_FOUND " + account);
				err.name = "login Error";
				err.code = 1;
				return UTIL.safeCall(onDone, err);
			}

			// by default we assume authentication fails and return token does not exist
			var result = false;
			var token = undefined;		
			
			// determine to check password or check token
			if (by_account)
				result = (l_encryptPass(password) === data.password);
			else
				// NOTE: check if the requester of the token was the same as the one logined previously
				result = (data.pass_tokens.hasOwnProperty(password));
				
			// check login is success or fail
			if (result === true) {
				l_addLogin(account, data, conn);
				
				// generate unique token and store it if requested
				if (requester) {
					var l_createTokenDone = function (l_createToken_err, token) {
						if (l_createToken_err) {
							var err = new Error("ACCOUNT_LOGIN_TOKENSTORE_FAIL: " + account);
							err.name = "login Error";
							err.code = 1;
							UTIL.safeCall(onDone, err);
						}
						else {
							UTIL.safeCall(onDone, null, {code: 0, msg: 'ACCOUNT_LOGIN_SUCCESS: ' + account, uid: data.uid, token: token, data: data});
						}
					};
					l_createToken(data.uid, requester, l_createTokenDone);
				}
				else {
					return UTIL.safeCall(onDone, null, {code: 0, msg: 'ACCOUNT_LOGIN_SUCCESS: ' + account, data: data});
				}
			}
			else {
				var err = new Error("ACCOUNT_LOGIN_PASSFAIL: " + account);
				err.name = "login Error";
				err.code = 1;
				return UTIL.safeCall(onDone, err);
			}
		}
816904
function getLogin(callback, referer, params) {
	debug('Logging in, sending POST');
	request.post(psnURL.SignINPOST
		,{
			headers: {
				'User-Agent': userAgent
				,'X-Requested-With': requestedWith
				,'Origin':'https://auth.api.sonyentertainmentnetwork.com'
				,'Referer': referer
			}
			,form:{
				'params' 		: (params !== psnVars.paramString ? params : psnVars.paramString) // Now it's base64'd for some reason.
				,'j_username'	: options.email
				,'j_password'	: options.password
			}
		}, function (error, response, body) {
			if (!error) {
				followRedirect(null, response.headers.location, referer);
			}
			else {
				debug('ERROR: ' + error)
			}
		}
	)
}
74618
function authenticateAccount() {

  var authcRequest = {
    username: accountEmail, //we could've entered the username instead
    password: 'Changeme1!'
  };

  return application.authenticateAccount(authcRequest, function(err, result) {
    if (err) throw err;

    return result.getAccount(function(err2, theAccount) { //this is cached and will execute immediately (no server request):
      if(err2) throw err2;

      account = theAccount;

      console.log('Authenticated account:');
      console.log(account);

      //authentication was successful, so we ordinarily have no need to send a
      //password reset email right now, but hey - this is a quickstart and we're
      //trying to show stuff!  So kick off the password reset workflow just for fun:
      return sendPasswordResetEmail(); //next quickstart step
    });
  });
}
377253
function login(options) {

    // Return promise and resolve once user info is retrieved.
    return new Promise(function (resolve, reject) {

      FB.login(function (response) {

        /*response = authResponse + status*/
        _getUser(response).then(function (userResponse) {

          if(userResponse.user) {

            /*userResponse = authResponse + status + user*/
            resolve(userResponse);

          } else {

            // Reject login promise if the user canceled the FB login.
            reject(userResponse);

          }

        });

      }, options);

    });
  }
351229
function _loadUserFromToken(){
    return BB
        .bind(this)
        .then(function() {
            return grasshopper.request(this.token).users.current();
        })
        .then(function(user){
            this.user = user;
        });
}
582210
def _login(login_func, *args):
    
    response = login_func(*args)
    _fail_if_contains_errors(response)
    user_json = response.json()
    return User(user_json)
933107
function authenticate(req, res, next) {
  var username = req.body.username,
      password = req.body.password;

  if (req.session && req.session.user.username === username) {
    // This user is already logged in
    next();
    return;
  }

  // Get the employee REST resource - /employees/{username}
  var dataStore = req.app.dataStore;
  var resource = new swagger.Resource('/employees', username, null);
  dataStore.get(resource, function(err, resource) {
    // Check the login credentials
    if (resource && resource.data.password === password) {
      // Login is valid, so create a new session object
      var sessionId = Math.random().toString(36).substr(2);
      req.session = {
        id: sessionId,
        created: new Date(),
        user: resource.data
      };

      // Save the session REST resource
      resource = new swagger.Resource('/sessions', req.session.id, req.session);
      dataStore.save(resource, next);
    }
    else {
      // Login failed
      res.sendStatus(401);
    }
  });
}
157406
async function authenticate(scopes) {
  return new Promise((resolve, reject) => {
    // grab the url that will be used for authorization
    const authorizeUrl = oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: scopes.join(' '),
    });
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            res.end('Authentication successful! Please return to the console.');
            server.destroy();
            const {tokens} = await oauth2Client.getToken(qs.get('code'));
            oauth2Client.credentials = tokens;
            resolve(oauth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
      });
    destroyer(server);
  });
}
520830
function handleLogout(req, res, next) {
		var p = new Promise(function (resolve, reject) {
			// Return success even if not currently logged in.
			if (!req.locals.user) {
				debug(`Request is not authenticated, nobody to logout.`);
				return resolve({
					success: true,
					message: 'not logged in'
				});
			}

			// Lookup current user and do the logout.
			debug(`Logging out the current authenticated session for User ${req.locals.user}`);
			AclUser.findOne({
				_id: req.locals.user._id,
				local_auth_type: 'password',
				active: true
			}, function (err, user) {
				if (err) {
					debug(`Error finding User during logout request.`, err);
					return reject(new restifyErrors.InternalError(err));
				}
				if (!user) {
					debug(`User not found during logout request.`);
					return resolve({
						success: true,
						message: 'not found'
					});
				}
				user.modifiedBy = 'logout';
				user.last_logout_date = new Date();

				// Destroy the current Bearer token 
				for (var i = user.bearer.length - 1; i > -1; i--) {
					if (req.headers.authorization == `Bearer ${user.bearer[i].token}`) {
						user.bearer.splice(i, 1);
						break;
					}
				}

				// Save the User back to the database
				user.save(function (err, result) {
					if (err) {
						debug(`Error updating user during logout request.`, err);
						return reject(new restifyErrors.InternalError(err));
					}
					resolve({
						success: true,
						message: 'success'
					});
				});
			});
		}).then(function (data) {
			req.logout(); // Provided by Passport
			res.json(data);
			next();
		}).catch(function (err) {
			debug(`Error handling logout request.`, err);
			next(err);
		});
	}