Simple function to generate a JWT based off a user
@param user
@param existingToken Optional, pass in if there is an existing token we are adding to
@returns {*}
512812
function generateForUser(user, existingToken) {
        existingToken = existingToken || {};

        var privateKey = config.security.token.privateKey;
        var decryptedToken = _.extend(existingToken, { _id: user._id, authToken: user.authToken });

        return jsonwebtoken.sign(decryptedToken, privateKey);
    }
779060
function (authentication, callback) {
            /***
             * Let's save the authentication and so the user is logged in
             *
             */
            var token = generateId();
            var authenticationInstance = this.$.dataSource.createEntity(Authentication, token);

            authenticationInstance.set(authentication.$);
            authenticationInstance.save(null, callback);
        }
824851
def generate_user_token(self, user, salt=None):
        
        return self.token_serializer.dumps(str(user.id), salt=salt)
605689
public ChaiUser newChaiUser( final String userDN )
            throws ChaiUnavailableException
    {
        final VendorFactory entryFactory = getChaiProvider().getDirectoryVendor().getVendorFactory();
        return entryFactory.newChaiUser( userDN, getChaiProvider() );
    }
504489
private static Token<EsTokenIdentifier> getAuthToken(ClusterName clusterName, User user) {
        EsToken esToken = getEsAuthToken(clusterName, user);
        if (esToken == null) {
            return null;
        } else {
            return EsTokenIdentifier.createTokenFrom(esToken);
        }
    }
266723
@Restricted(NoExternalUse.class)
    public @Nullable ApiTokenStore.HashedToken getLegacyTokenOf(@Nonnull User user) {
        ApiTokenProperty apiTokenProperty = user.getProperty(ApiTokenProperty.class);
        return apiTokenProperty.getTokenStore().getLegacyToken();
    }
325687
async def generate_access_token(self, user):
        
        payload = await self._get_payload(user)
        secret = self._get_secret(True)
        algorithm = self._get_algorithm()

        return jwt.encode(payload, secret, algorithm=algorithm).decode("utf-8")
1039253
@Remoted
    public IPromise<Object[]> login(String user, String pw, String jwt) {
        Promise res = new Promise();
        ConnectionRegistry remoteConnection = connection.get();
        getCredentials(user,pw,jwt).then( (authres, err) -> {
            if ( err != null ) {
                res.reject(err);
            } else {
                String sessionId = remoteConnection != null ? remoteConnection.getSocketRef().getConnectionIdentifier() : null;
                getSession(user,sessionId, authres ).then( (sess,serr) -> {
                    if ( sess != null ) {
                        if ( sessionId != null && sessionStorage != null ) {
                            sessionStorage.putUserAtSessionId(sessionId,user);
                        }
                        res.resolve(new Object[]{sess,authres});
                    } else
                        res.complete(sess,serr);
                });
            }
        });
        return res;
    }
528510
def claim_token(self, **params):
        
        self._json_params.update(params)
        success, self.user = self.Model.authenticate_by_password(
            self._json_params)

        if success:
            headers = remember(self.request, self.user.username)
            return JHTTPOk('Token claimed', headers=headers)
        if self.user:
            raise JHTTPUnauthorized('Wrong login or password')
        else:
            raise JHTTPNotFound('User not found')
189450
function tokenNotExpired(tokenName, jwt) {
    if (tokenName === void 0) { tokenName = AuthConfigConsts.DEFAULT_TOKEN_NAME; }
    var token = jwt || localStorage.getItem(tokenName) || sessionStorage.getItem(tokenName);
    var jwtHelper = new JwtHelper();
    return token != null && !jwtHelper.isTokenExpired(token);
}
229906
function findUserFromAccessToken(accessToken, UserModel) {

    if (!accessToken) return null;

    return UserModel.findById(accessToken.userId).then((user) => {
        if (!user) return Promise.reject('No user with this access token was found.');
        return Promise.resolve(user);
    });
}
802470
function init(config) {
    var tokenConfig = config.security.token || {};
    var privateKey = tokenConfig.privateKey;
    var decryptedToken = {
        _id: tokenConfig.webserverId,
        authToken: tokenConfig.webserverToken
    };
    var jwt = jsonwebtoken.sign(decryptedToken, privateKey);

    headers = { 'Authorization': 'Bearer ' + jwt };

    admin._id =  mongo.newObjectId('000000000000000000000000');
    admin.name = 'systemAdmin';
    admin.type = 'user';
    admin.role = 'admin';

    var apiConfig = config.api || {};
    var host = apiConfig.internalHost || apiConfig.host;  // from web server to api use internalHost name
    var useSSL = apiConfig.serverUseSSL !== undefined ?
        apiConfig.serverUseSSL : config.useSSL;
    baseUrl = (useSSL ? 'https://' : 'http://') + host;

    var port = config.api.port;
    if (port !== 80 && port !== 443) {
        baseUrl += ':' + port;
    }

    baseUrl += '/' + config.api.version;

    return config;
}
3338
function(user) {
        var promise;
        if (AV.User._currentUser !== user) {
          promise = AV.User.logOut();
        } else {
          promise = Promise.resolve();
        }
        return promise.then(function() {
          user._isCurrentUser = true;
          AV.User._currentUser = user;

          var json = user._toFullJSON();
          json._id = user.id;
          json._sessionToken = user._sessionToken;
          return AV.localStorage
            .setItemAsync(
              AV._getAVPath(AV.User._CURRENT_USER_KEY),
              JSON.stringify(json)
            )
            .then(function() {
              AV.User._currentUserMatchesDisk = true;
              return AV._refreshSubscriptionId();
            });
        });
      }
279081
function getTokenHashes(username, done) {
  return getUser(username, function(getUserErr, user) {
    if (getUserErr) {
      return done(getUserErr);
    }

    if (!user) {
      return done(new Error(`user '${username}' not found`));
    }

    return done(null, user.tokens);
  });
}
1021861
public User existsByInviteToken(String token) {
		Criteria criteria = this.dao.newCriteria(User.class).add(Restrictions.eq("inviteToken", token));
		return (User) criteria.uniqueResult();
	}
1305261
def create_token_for_user(user: get_user_model()) -> bytes:
        
        token = urandom(48)
        AuthToken.objects.create(
            hashed_token=AuthToken._hash_token(token),
            user=user)
        return token
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
}