Authorize an existing user - resolve using token - token:    login token Provides: - success: {ok:true,user:,login:} - failure: {ok:false,why:,token:}
480930
function cmd_auth(args, done) {
    var seneca = this
    var userent = seneca.make(user_canon)
    var loginent = seneca.make(login_canon)

    var q = { id: args.token }

    loginent.load$(q, function(err, login) {
      if (err) return done(err)

      if (!login) {
        return done(null, {
          ok: false,
          token: args.token,
          why: 'login-not-found'
        })
      }

      if (!login.active) {
        return done(null, {
          ok: false,
          token: args.token,
          why: 'login-inactive'
        })
      }

      userent.load$({ id: login.user }, function(err, user) {
        if (err) return done(err)

        if (!user) {
          return done(null, {
            ok: false,
            token: args.token,
            user: login.user,
            why: 'user-not-found'
          })
        }

        done(null, { user: user, login: login, ok: true })
      })
    })
  }
1004551
def login(user, &block)
      authenticate_session.login user, &block

      if logged_in? && Authenticate.configuration.rotate_csrf_on_sign_in?
        session.delete(:_csrf_token)
        form_authenticity_token
      end
    end
1158747
function doLogin (opts, csrf, email, password) {
  return fetch(`${opts.host}/_/auth/login`, json({
    ...opts,
    method: 'post',
    body: { csrf, email, password }
  })).then((response) => props({
    session: getSessionCookie(response.headers.get('set-cookie')),
    body: getJSON(response)
  }))
}
1374436
def validate_token
      token = params[:token]
      return false if token.nil?
      
      user = User.validate_token(token)
      return false if user.nil?
     
      login_user(user)
      return true
    end
1138547
def get_token(username, password, server):
    
    method = 'PUT'
    uri = 'https://' + server + '/authenticate'
    token = ''

    authinfo = {
        "username": username,
        "password": password,
        "local_user": username}

    token = tonicdns_client(uri, method, token, data=authinfo)

    return token
467912
def login(user, password)
      @user = user
      @password = password

      response = call_remote(:login, [:username, user, :password, password])

      raise "Incorrect user name / password [#{response.fault}]" unless response.loginResponse

      result = response[:loginResponse][:result]
      @session_id = result[:sessionId]

      init_server(result[:serverUrl])

      response
    end
946398
async function authenticate({ options, keys, log })
{
	// A little helper which can be called from routes
	// as `ctx.role('administrator')`
	// which will throw if the user isn't administrator.
	// The `roles` are taken from JWT payload.
	this.role = (...roles) =>
	{
		if (!this.user)
		{
			throw new errors.Unauthenticated()
		}

		for (const role of roles)
		{
			for (const user_role of this.user.roles)
			{
				if (user_role === role)
				{
					return true
				}
			}
		}

		throw new errors.Unauthorized(`One of the following roles is required: ${roles}`)
	}

	// Get JWT token from incoming HTTP request
	let token = get_jwt_token(this)

	// If no JWT token was found, then done
	if (!token)
	{
		return
	}

	// JWT token (is now accessible from Koa's `ctx`)
	this.accessToken = token

	// Verify JWT token integrity
	// by checking its signature using the supplied `keys`

	let payload

	for (const secret of keys)
	{
		try
		{
			payload = jwt.verify(token, secret)
			break
		}
		catch (error)
		{
			// If authentication token expired
			if (error.name === 'TokenExpiredError')
			{
				if (options.refreshAccessToken)
				{
					// If refreshing an access token fails
					// then don't prevent the user from at least seeing a page
					// therefore catching an error here.
					try
					{
						token = await options.refreshAccessToken(this)
					}
					catch (error)
					{
						log.error(error)
					}

					if (token)
					{
						for (const secret of keys)
						{
							try
							{
								payload = jwt.verify(token, secret)
								break
							}
							catch (error)
							{
								// Try another `secret`
								if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature')
								{
									continue
								}

								// Some other non-JWT-related error
								log.error(error)
								break
							}
						}
					}
				}

				if (payload)
				{
					break
				}

				throw new errors.Access_token_expired()
			}

			// Try another `secret`
			if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature')
			{
				continue
			}

			// Some other non-JWT-related error.
			// Shouldn't prevent the user from at least seeing a page
			// therefore not rethrowing this error.
			log.error(error)
			break
		}
	}

	// If JWT token signature was unable to be verified, then exit
	if (!payload)
	{
		return
	}

	// If the access token isn't valid for access to this server
	// (e.g. it's a "refresh token") then exit.
	if (options.validateAccessToken)
	{
		if (!options.validateAccessToken(payload, this))
		{
			return
		}
	}

	// Token payload can be accessed through `ctx`
	this.accessTokenPayload = payload

	// Fire "on user request" hook
	if (options.onUserRequest)
	{
		options.onUserRequest(token, this)
	}

	// JWT token ID
	const jwt_id = payload.jti

	// `subject`
	// (which is a user id)
	const user_id = payload.sub

	// // Optional JWT token validation (by id)
	// // (for example, that it has not been revoked)
	// if (validateToken)
	// {
	// 	// Can validate the token via a request to a database, for example.
	// 	// Checks for `valid` property value inside the result object.
	// 	// (There can possibly be other properties such as `reason`)
	// 	const is_valid = (await validateToken(token, this)).valid
	//
	// 	// If the JWT token happens to be invalid
	// 	// (expired or revoked, for example), then exit.
	// 	if (!is_valid)
	// 	{
	// 		// this.authenticationError = new errors.Unauthenticated('AccessTokenRevoked')
	// 		return
	// 	}
	// }

	// JWT token ID is now accessible via Koa's `ctx`
	this.accessTokenId = jwt_id

	// Extracts user data (description) from JWT token payload
	// (`user` is now accessible via Koa's `ctx`)
	this.user = options.userInfo ? options.userInfo(payload) : {}

	// Sets user id
	this.user.id = user_id
	
	// Extra payload fields:
	//
	// 'iss' // Issuer
	// 'sub' // Subject
	// 'aud' // Audience
	// 'exp' // Expiration time
	// 'nbf' // Not before
	// 'iat' // Issued at 
	// 'jti' // JWT ID

	// JWT token payload is accessible via Koa's `ctx`
	this.accessTokenPayload = payload
}
582210
def _login(login_func, *args):
    
    response = login_func(*args)
    _fail_if_contains_errors(response)
    user_json = response.json()
    return User(user_json)
563376
def login(self, identity, credentials):
        '''
        '''
        result = self.dispatcher.session.post(self._url('v0/auth/login'),
                                              json={
                                                  'email': identity,
                                                  'password': credentials
                                              })
        status = result.status_code
        if status == 400:
            raise APIException('invalid parameters, login process has changed')
        elif status == 401:
            # do our best to get something out to the user
            msg = result.text
            try:
                msg = json.loads(result.text)['message']
            finally:
                raise InvalidIdentity(msg)
        elif status != 200:
            raise APIException('%s: %s' % (status, result.text))
        jwt = result.text
        payload = jwt.split('.')[1]
        rem = len(payload) % 4
        if rem > 0:
            payload += '=' * (4 - rem)
        payload = base64.urlsafe_b64decode(payload.encode('utf-8'))
        return json.loads(payload.decode('utf-8'))
723513
public boolean resetPassword(String password, String token) {
		UserRecoverRequest req = this.retrieveRecoverRequest(token);
		if (req == null)
			return false;
		User user = req.getUser();
		user.setPassword(CryptManager.passwordHash(password));
		this.dao.persist(user);
		req.setRecover(new Date());
		req.setRecoverIp(this.request.getRemoteAddr());
		req.setUsed(true);
		this.dao.persist(req);
		return true;
	}
564173
function signIn (defOptions, credentials, callback) {
  var promise = normalizeRequestParameters(defaults, 'SignIn', credentials).then(function (credentials) {

    var options = {
      method : 'POST',
      uri : 'v1/SignIn',
      json : credentials
    };
    
    extend(true, options, defOptions);
    
    return options;
    
  }).then(request).nodeify(callback);
  
  return promise;
}
796239
def _login(self, username, password):
        '''
        '''
        logger.debug('login in as user "%s"' % username)
        url = self._build_url('/auth')
        payload = {'username': username, 'password': password}
        res = self._session.post(url, json=payload)
        res.raise_for_status()
        self._access_token = res.json()['access_token']
        self._session.headers.update(
            {'Authorization': 'JWT %s' % self._access_token}
        )
65115
def login(self):
        
        uri = 'API/Auth/Login'
        if self._token:
            json_data = {'token': self._token, 'domain': self._domain}
        else:
            json_data = {'username': self._username, 'password': self._password, 'domain': self._domain}
        result = self.__rest_client.request_put(uri, json_data)
        self.__rest_client.session.headers.update(authorization="Basic {0}".format(result.replace('"', '')))
195581
def login(request, user):
    
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        session_key = request.session[SESSION_KEY]
        if session_key != user.pk or (
                session_auth_hash and
                request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = user.pk
    request.session[BACKEND_SESSION_KEY] = user.backend
    request.session[USER_DATA_SESSION_KEY] = user.user_data
    request.session[HASH_SESSION_KEY] = session_auth_hash

    update_token_in_session(request.session, user.token)

    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
468096
def token_login(token):
    """"""

    expired, invalid, user = login_token_status(token)

    if invalid:
        do_flash(*get_message('INVALID_LOGIN_TOKEN'))
    if expired:
        send_login_instructions(user)
        do_flash(*get_message('LOGIN_EXPIRED', email=user.email,
                              within=_security.login_within))
    if invalid or expired:
        return redirect(url_for('login'))

    login_user(user)
    after_this_request(_commit)
    do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))

    return redirect(get_post_login_redirect())
648108
def auth_token(cls, token):
        

        store = goldman.sess.store
        login = store.find(cls.RTYPE, 'token', token)

        if not login:
            msg = 'No login found with that token. It may have been revoked.'
            raise AuthRejected(**{'detail': msg})
        elif login.locked:
            msg = 'The login account is currently locked out.'
            raise AuthRejected(**{'detail': msg})
        else:
            login.post_authenticate()
779797
def authenticate_token(self, load):
        '''
        
        '''
        token = self.get_tok(load['token'])

        # Bail if the token is empty or if the eauth type specified is not allowed
        if not token or token['eauth'] not in self.opts['external_auth']:
            log.warning('Authentication failure of type "token" occurred.')
            return False

        return token