authenticate method

Future<GitHubAuthSuccess> authenticate(
  1. Session session, {
  2. required String accessToken,
  3. required Transaction? transaction,
})

Authenticates a user using an access token.

If the external user ID is not yet known in the system, a new AuthUser is created for it.

The transaction parameter can be used to perform the database operations within an existing transaction.

Implementation

Future<GitHubAuthSuccess> authenticate(
  final Session session, {
  required final String accessToken,
  required final Transaction? transaction,
}) async {
  final accountDetails = await fetchAccountDetails(
    session,
    accessToken: accessToken,
  );

  var githubAccount = await GitHubAccount.db.findFirstRow(
    session,
    where: (final t) => t.userIdentifier.equals(
      accountDetails.userIdentifier,
    ),
    transaction: transaction,
  );

  final createNewUser = githubAccount == null;

  final AuthUserModel authUser = switch (createNewUser) {
    true => await _authUsers.create(
      session,
      transaction: transaction,
    ),
    false => await _authUsers.get(
      session,
      authUserId: githubAccount!.authUserId,
      transaction: transaction,
    ),
  };

  if (createNewUser) {
    githubAccount = await linkGitHubAuthentication(
      session,
      authUserId: authUser.id,
      accountDetails: accountDetails,
      transaction: transaction,
    );
  }

  return (
    githubAccountId: githubAccount.id!,
    authUserId: githubAccount.authUserId,
    details: accountDetails,
    newAccount: createNewUser,
    scopes: authUser.scopes,
  );
}