Returns a stateless user object which is backed by the given validated
        token.
191282
def get_user(self, validated_token):
        
        if api_settings.USER_ID_CLAIM not in validated_token:
            # The TokenUser class assumes tokens will have a recognizable user
            # identifier claim.
            raise InvalidToken(_('Token contained no recognizable user identification'))

        return TokenUser(validated_token)
1017754
def verify_token(token)
        logger.debug("Verifying token: #{token}")

        # First get the payload of the token. This will also verify whether
        # or not the token is welformed.
        payload = get_token_payload(token)

        # Next, the payload should define user UUID and session UUID.
        user_uuid = payload["user_uuid"]
        session_uuid = payload["session_uuid"]
        if user_uuid.nil? || session_uuid.nil?
          logger.error("User or session is not specified")
          raise UNAUTHORIZED_ERROR, "Invalid token"
        end
        logger.debug("Token well defined: #{token}")

        # But, the user UUID and session UUID better be valid too. That is,
        # they must be real user and session, and the session must belong to
        # the user.
        auth_user = User.find_by_uuid(user_uuid)
        if auth_user.nil?
          # :nocov:
          logger.error("Specified user doesn't exist #{user_uuid}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
          # :nocov:
        end
        auth_session = Session.find_by_uuid(session_uuid)
        if auth_session.nil? || auth_session.user != auth_user
          logger.error("Specified session doesn't exist #{session_uuid}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
        end

        # Finally, decode the token using the secret. Also check expiration
        # here too.
        JWT.decode token, auth_session.secret, true
        logger.debug("Token well formatted and verified. Set cache.")

        # Return the corresponding session
        return auth_session

      rescue JWT::DecodeError => e
        logger.error(e.message)
        raise UNAUTHORIZED_ERROR, "Invalid token"
      end
644050
def token(self) -> str:
        

        return self.value[0] if self in (Role.USER, Role.ROLE_REMOVE) else self.name
566561
def get_auth_token(self, user_payload):
        
        now = datetime.utcnow()
        payload = {
            'user': user_payload
        }
        if 'iat' in self.verify_claims:
            payload['iat'] = now

        if 'nbf' in self.verify_claims:
            payload['nbf'] = now + self.leeway

        if 'exp' in self.verify_claims:
            payload['exp'] = now + self.expiration_delta

        if self.audience is not None:
            payload['aud'] = self.audience

        if self.issuer is not None:
            payload['iss'] = self.issuer

        return jwt.encode(
            payload,
            self.secret_key,
            algorithm=self.algorithm,
            json_encoder=ExtendedJSONEncoder).decode('utf-8')
988809
def verify_token(self, token):
        '''
        
        '''
        try:
            result = self.resolver.get_token(token)
        except Exception as ex:
            raise EauthAuthenticationError(
                "Token validation failed with {0}.".format(repr(ex)))

        return result
144705
def get_user_by_action_token(action, token):
    
    data = utils.unsign_url_safe(token,
                                 secret_key=get_jwt_secret(),
                                 salt=action)
    if data is None:
        raise exceptions.AuthError("Invalid Token")
    return get_user_by_id(int(data))
424666
def get_auth_token(self):
        """"""
        data = [str(self.id), hash_data(self.password)]
        return _security.remember_token_serializer.dumps(data)
1305783
def _getUserAuthObject(self, user, connection):
        
        credentials = self._getCredentials(user)
        userAuthObject = AutomaticUserAuthClient(user, connection, **credentials)
        return userAuthObject
639091
function(tokenStr) {
            if (typeof tokenStr !== 'string') {
                return null;
            }
            var token = tokenCache[tokenStr];
            if (token !== undefined) {
                return token;
            } else {
                try {
                    token = tokens.validate(tokenStr, trustedPubKey);
                    tokenCache[tokenStr] = token;
                    return token;
                } catch (err) {
                    // did not validate, cache negative result.
                    tokenCache[tokenStr] = null;
                    return null;
                }
            }
        }
35349
def get_user_by_auth_token(token=None):
    
    if not token:
        token = request.get_auth_token()
    secret_key = get_jwt_secret()
    s = utils.unsign_jwt(token=token,
                         secret_key=secret_key,
                         salt=get_jwt_salt())
    if "id" not in s:
        raise exceptions.AuthError("Invalid Authorization Bearer Token")
    return get_user_by_id(int(s["id"]))
912344
def user_to_uid(user):
    '''
    
    '''
    if user is None:
        user = salt.utils.user.get_user()

    return salt.utils.win_dacl.get_sid_string(user)
775483
function getUserForToken(decodedToken) {
        var userId = decodedToken._id;
        var authToken = decodedToken.authToken;
        var cacheKey = userId + authToken;
        var conditions = {
            caller: userService.admin,
            where: { _id: userId, authToken: authToken, status: 'created' },
            findOne: true
        };
        var cachedUser;

        // if no user id or authToken, then no user
        if (!userId || !authToken) { return null; }

        // try to get user from cache, then DB
        return userCacheService.get({ key: cacheKey })
            .then(function (user) {
                cachedUser = user;
                return user ? user : userService.find(conditions);
            })
            .then(function (user) {

                // if user found in database, but not in cache, save in cache
                if (user && !cachedUser) {
                    userCacheService.set({ key: cacheKey, value: user });
                }

                // return the user
                return user;
            });
    }
1334495
@Restricted(NoExternalUse.class)
    public @Nullable ApiTokenProperty.TokenInfoAndStats getLegacyStatsOf(@Nonnull User user, @Nullable ApiTokenStore.HashedToken legacyToken) {
        ApiTokenProperty apiTokenProperty = user.getProperty(ApiTokenProperty.class);
        if (legacyToken != null) {
            ApiTokenStats.SingleTokenStats legacyStats = apiTokenProperty.getTokenStats().findTokenStatsById(legacyToken.getUuid());
            return new ApiTokenProperty.TokenInfoAndStats(legacyToken, legacyStats);
        }
        
        // in case the legacy token was revoked during the request
        return null;
    }
600152
public Authentication getAuthentication(String token) {
		if (null != token) {
			TokenContainer container = tokens.get(token);
			if (null != container) {
				if (container.isValid()) {
					return container.getAuthentication();
				} else {
					logout(token);
				}
			}
		}
		return null;
	}
394506
def requires_user(fn):
        
        @functools.wraps(fn)
        def wrap(*args, **kwargs):

            subject = WebYosai.get_current_subject()

            if subject.identifiers is None:
                msg = ("Attempting to perform a user-only operation.  The "
                       "current Subject is NOT a user (they haven't been "
                       "authenticated or remembered from a previous login). "
                       "ACCESS DENIED.")
                raise WebYosai.get_current_webregistry().raise_unauthorized(msg)
            return fn(*args, **kwargs)
        return wrap
1181628
def login_oauth2_user(valid, oauth):
    """"""
    if valid:
        oauth.user.login_via_oauth2 = True
        _request_ctx_stack.top.user = oauth.user
        identity_changed.send(current_app._get_current_object(),
                              identity=Identity(oauth.user.id))
    return valid, oauth
366965
public Token<DelegationTokenIdentifier> selectTokenFromFsOwner() throws IOException {
    return lookupToken(user.getCredentials(), service, tokenBinding.getKind());
  }