authenticate method

Future<Session> authenticate({
  1. Context? ctx,
  2. bool forceRefresh = false,
})

Implementation

Future<Session> authenticate(
    {Context? ctx, bool forceRefresh = false}) async {
  await ready();
  if (!forceRefresh && _state.session != null && authorized()) {
    return _state.session!;
  }
  final token = this.token;
  if (token.isEmpty) {
    throw Status.unauthorized.err();
  }
  final expiresAt = _state.expiresAt;
  if (expiresAt != null && !expiresAt.isAfter(DateTime.now())) {
    await destroy(localOnly: true);
    throw Status.expireAuthentication.err();
  }
  _setState(_state.copyWith(authenticating: true));
  try {
    final session =
        await _tokenizer.authenticate(token, ctx: _withToken(ctx, token));
    if (session == null) {
      throw Status.unauthorized.err();
    }
    await _persist(
      token: token,
      session: session,
      expiresAt: _state.expiresAt,
    );
    _setState(
      _state.copyWith(
        ready: true,
        session: session,
        authenticating: false,
      ),
    );
    return session;
  } catch (_) {
    _setState(_state.copyWith(authenticating: false));
    rethrow;
  }
}