loginUser method

Future<Agent> loginUser(
  1. Agent fromAgent,
  2. String username,
  3. String password,
  4. {List<String>? scopes}
)

Authenticates a user for username and password.

This method attempts to authenticates username for password, and issues an access token if successful. The returned Agent provides that access token in the authorization header of its requests.

fromAgent must be a client authenticated agent, typically created by addClient. If scopes is non-null, the access token will have the included scope if valid.

Implementation

Future<Agent> loginUser(Agent fromAgent, String username, String password,
    {List<String>? scopes}) async {
  final authorizationHeader = fromAgent.headers["authorization"];
  if (authorizationHeader is! String) {
    throw ArgumentError("expected header 'Authorization' to have String type");
  }
  const parser = AuthorizationBasicParser();
  final credentials = parser.parse(authorizationHeader);

  try {
    final token = await authServer!.authenticate(
        username, password, credentials.username, credentials.password,
        requestedScopes: scopes?.map((s) => AuthScope(s)).toList());
    return Agent.from(fromAgent)
      ..headers["authorization"] = "Bearer ${token.accessToken}";
  } on AuthServerException catch (e) {
    if (e.reason == AuthRequestError.invalidGrant) {
      throw ArgumentError("Invalid username/password.");
    } else if (e.reason == AuthRequestError.invalidScope) {
      throw ArgumentError(
          "Scope not permitted for client identifier and/or user.");
    }

    rethrow;
  }
}