createTokenByRefreshToken method
Create a new token by given refresh token.
The given token must be a valid refresh token.
The expiresIn
parameter is the duration after which the token will
expire. If not provided, the token will expire after 1 hour.
The customToken
parameter determines if the token should be stored in
the database or not. If customToken
is true, the token is not stored
in the database.
Returns a map containing the following keys:
access_token
: the JWT tokenrefresh_token
: the refresh tokenexpires_in
: the duration after which the token will expire in seconds
Implementation
//
/// The given token must be a valid refresh token.
//
/// The `expiresIn` parameter is the duration after which the token will
/// expire. If not provided, the token will expire after 1 hour.
//
/// The `customToken` parameter determines if the token should be stored in
/// the database or not. If `customToken` is true, the token is not stored
/// in the database.
//
/// Returns a map containing the following keys:
//
/// * `access_token`: the JWT token
/// * `refresh_token`: the refresh token
/// * `expires_in`: the duration after which the token will expire in seconds
Future<Map<String, dynamic>> createTokenByRefreshToken(
String token, {
Duration? expiresIn,
bool customToken = false,
}) async {
final newToken = HasApiTokens().refreshToken(
token.replaceFirst('Bearer ', ''),
_userGuard,
expiresIn,
);
if (!customToken) {
Map<String, dynamic> payload = HasApiTokens().verify(
token.replaceFirst('Bearer ', ''), _userGuard, 'refresh_token');
Model? authenticatable =
Config().get('auth')['guards'][_userGuard]['provider'];
if (authenticatable == null) {
throw InvalidArgumentException('Authenticatable class not found');
}
Map? user =
await authenticatable.query.where('id', '=', payload['id']).first();
if (user == null) {
throw Unauthenticated(message: 'Invalid token');
}
_user[_userGuard] = user;
await PersonalAccessToken().query.insert({
'name': _userGuard,
'tokenable_id': user['id'],
'token': md5.convert(utf8.encode(newToken['access_token'])),
'created_at': DateTime.now(),
});
}
return newToken;
}