authenticate static method

Future<Map<String, dynamic>> authenticate({
  1. required String code,
  2. String? callbackPath,
  3. required String? clientId,
  4. required String? clientSecret,
  5. required String redirectBase,
})

Implementation

static Future<Map<String, dynamic>> authenticate({
  required String code,
  String? callbackPath,
  required String? clientId,
  required String? clientSecret,
  required String redirectBase,
}) async {
  if (clientId == null || clientSecret == null) {
    throw AuthException('GitHub OAuth is not configured');
  }

  final redirectUri = callbackPath != null
      ? '$redirectBase$callbackPath'
      : '$redirectBase/api/auth/github/callback';

  // 1. Exchange code for access token
  final accessToken = await _exchangeCodeForToken(
    code,
    clientId,
    clientSecret,
    redirectUri,
  );

  // 2. Fetch user profile
  final profile = await _fetchUserProfile(accessToken);

  // 3. Get user email
  String? email = profile['email'];
  if (email == null || email.isEmpty) {
    final emails = await _fetchUserEmails(accessToken);
    final primaryEmail = emails.firstWhere(
      (e) => e['primary'] == true,
      orElse: () => emails.firstWhere((e) => e['verified'] == true),
    );
    email = primaryEmail['email'];
  }

  return AuthProvider.formatUserData(
    provider: 'github',
    providerId: profile['id'].toString(),
    email: email,
    name: profile['name'] ?? profile['login'],
    picture: profile['avatar_url'],
    rawProfile: profile,
  );
}