createToken method

Future<Map<String, dynamic>> createToken({
  1. Duration? expiresIn,
  2. bool withRefreshToken = false,
  3. bool customToken = false,
})

Create new token for the given user.

The token created is a JWT token that contains the user's ID and the guard's name. The token is then signed with the secret key from the environment variable JWT_SECRET_KEY.

If withRefreshToken is true, a refresh token is also created and returned in the refresh_token key of the map.

If customToken is true, the token is not stored in the database and is returned as is.

The expiresIn parameter is the duration after which the token will expire. If not provided, the token will expire after 1 hour.

Returns a map containing the following keys:

  • access_token: the JWT token
  • refresh_token: the refresh token if withRefreshToken is true
  • expires_in: the duration after which the token will expire in seconds

Implementation

Future<Map<String, dynamic>> createToken({
  Duration? expiresIn,
  bool withRefreshToken = false,
  bool customToken = false,
}) async {
  Map<String, dynamic> token = HasApiTokens()
      .setPayload(_user[_userGuard])
      .createToken(_userGuard, expiresIn, withRefreshToken);

  if (!customToken) {
    await PersonalAccessToken().query.insert({
      'name': _userGuard,
      'tokenable_id': _user[_userGuard]['id'],
      'token': md5.convert(utf8.encode(token['access_token'])).toString(),
      'created_at': DateTime.now(),
    });
  }

  return token;
}