check method

Future<bool> check(
  1. String token, {
  2. Map<String, dynamic>? user,
  3. bool isCustomToken = false,
})

Validates and checks the provided token for authentication.

This function verifies the provided JWT access token and checks its validity against stored personal access tokens. If the token is valid, it updates the token's last used timestamp and sets the current user context, marking them as authorized.

The function handles both custom and stored tokens. For custom tokens, it sets the user payload directly. For stored tokens, it ensures the token exists and is not marked as deleted, then retrieves the associated user.

Throws:

Returns a Future that resolves to true if the token is valid and the user is successfully authenticated.

Implementation

Future<bool> check(
  String token, {
  Map<String, dynamic>? user,
  bool isCustomToken = false,
}) async {
  Map<String, dynamic> payload = HasApiTokens()
      .verify(token.replaceFirst('Bearer ', ''), _userGuard, 'access_token');

  if (isCustomToken) {
    _user[_userGuard] = payload;
    _loggedIn = true;
    return true;
  } else {
    Map<String, dynamic>? exists = await PersonalAccessToken()
        .query
        .where('token', '=', md5.convert(utf8.encode(token)))
        .whereNull('deleted_at')
        .first(['id']);
    // Throw 401 Error if token not found
    if (exists == null) {
      throw Unauthenticated(message: 'Invalid token');
    }

    await PersonalAccessToken()
        .query
        .where('token', '=', md5.convert(utf8.encode(token)))
        .update({'last_used_at': DateTime.now()});

    if (user == null) {
      Model? authenticatable =
          Config().get('auth')['guards'][_userGuard]['provider'];

      if (authenticatable == null) {
        throw InvalidArgumentException('Authenticatable class not found');
      }
      user =
          await authenticatable.query.where('id', '=', payload['id']).first();
    }

    if (user != null) {
      _user[_userGuard] = user;
      _loggedIn = true;
      return true;
    } else {
      throw Unauthenticated(message: 'Invalid token');
    }
  }
}