linkProviderAccount function
Links a provider account to a user.
This is typically called after an OAuth flow completes and the user wants to link the provider to their existing account.
Implementation
Future<AuthAccountLinked> linkProviderAccount({
required AuthStore store,
required String userId,
required String providerId,
required String providerAccountId,
String? accessToken,
String? refreshToken,
DateTime? expiresAt,
Map<String, dynamic>? metadata,
DateTime? now,
}) async {
final normalizedUserId = userId.trim();
final normalizedProviderId = providerId.trim();
final normalizedProviderAccountId = providerAccountId.trim();
if (normalizedUserId.isEmpty) {
throw AuthFlowException('invalid_request');
}
if (normalizedProviderId.isEmpty) {
throw AuthFlowException('invalid_provider');
}
if (normalizedProviderAccountId.isEmpty) {
throw AuthFlowException('invalid_provider_account');
}
// Verify user exists
final user = await Future.sync(() => store.users.findById(normalizedUserId));
if (user == null) {
throw AuthFlowException('user_not_found');
}
// Check if this provider account is already linked to another user
final existingAccount = await Future.sync(
() =>
store.accounts.find(normalizedProviderId, normalizedProviderAccountId),
);
if (existingAccount != null) {
if (existingAccount.userId == normalizedUserId) {
// Already linked to this user
return AuthAccountLinked(
providerId: normalizedProviderId,
providerAccountId: normalizedProviderAccountId,
linkedAt: _parseLinkedAt(existingAccount.metadata),
isNewLink: false,
);
} else {
// Linked to a different user
throw AuthFlowException('provider_account_already_linked');
}
}
// Create the account link
final linkedAt = (now ?? DateTime.now()).toUtc();
final account = AuthAccount(
providerId: normalizedProviderId,
providerAccountId: normalizedProviderAccountId,
userId: normalizedUserId,
accessToken: accessToken,
refreshToken: refreshToken,
expiresAt: expiresAt,
metadata: {...?metadata, 'linkedAt': linkedAt.toIso8601String()},
);
final canonical = await Future.sync(() => store.accounts.link(account));
if (canonical.providerId != normalizedProviderId ||
canonical.providerAccountId != normalizedProviderAccountId ||
canonical.userId != normalizedUserId) {
throw AuthFlowException('provider_account_already_linked');
}
return AuthAccountLinked(
providerId: normalizedProviderId,
providerAccountId: normalizedProviderAccountId,
linkedAt: linkedAt,
isNewLink: true,
);
}