checkAuthentication method

Future<Authentication> checkAuthentication(
  1. HttpRequest request,
  2. Map<String, String> parameters
)

Implementation

Future<Authentication> checkAuthentication(
    HttpRequest request, Map<String, String> parameters) async {
  var authorization = request.headers['Authorization']?.first.trim();

  String? username;
  String? password;

  if (isNotEmptyString(authorization)) {
    var parts = authorization!.split(RegExp(r'\s+'));
    var type = parts[0].toLowerCase();

    if (type == 'basic') {
      var base64 = parts[1];
      var userAndPass = Base64.decode(base64).split(':');
      username = userAndPass[0];
      password = userAndPass[1];
    } else if (type == 'bearer') {
      var token = parts[1];
      var ok = validateToken(token);

      if (ok) {
        setResponseHeader(request, 'X-Access-Token', token);
        return Authentication(token: token, grant: true);
      }
    }
  }

  username ??= _getParameter(parameters, json, 'username');
  password ??= _getParameter(parameters, json, 'password');

  var ok = await checkPassword(username, password);
  if (!ok) {
    request.response.statusCode = HttpStatus.unauthorized;
    return Authentication(username: username, grant: false);
  }

  _checkTokens();
  var accessToken = _usersTokens.putIfAbsent(
      username!, () => AccessToken(_generateToken()));

  var token = accessToken.token;

  setResponseHeader(request, 'X-Access-Token', token);
  return Authentication(username: username, token: token, grant: true);
}