authenticate method

Future<AuthenticationAttemptResult> authenticate(
  1. Channel channel,
  2. String token
)

Authenticates channel with token and reserves its user connection.

Implementation

Future<AuthenticationAttemptResult> authenticate(
  Channel channel,
  String token,
) async {
  if (_authenticatedUsers.containsKey(channel)) {
    return AuthenticationAttemptResult.authenticated;
  }
  if (!_authenticating.add(channel)) {
    return AuthenticationAttemptResult.inProgress;
  }

  try {
    final request = _authenticationRequests[channel];
    if (request == null) return AuthenticationAttemptResult.rejected;

    final user = await authentication.authenticate(
      AuthenticationRequest(
        uri: request.uri,
        token: token,
        remoteAddress: request.remoteAddress,
      ),
    );
    if (user == null ||
        !identical(_authenticationRequests[channel], request) ||
        !_reserveConnection(user)) {
      return AuthenticationAttemptResult.rejected;
    }

    _authenticatedUsers[channel] = user;
    _authenticationTimeouts.remove(channel)?.cancel();
    return AuthenticationAttemptResult.authenticated;
  } finally {
    _authenticating.remove(channel);
  }
}