signIn method
Initiates an OAuth sign-in flow.
This method opens the OAuth provider's authentication page in a browser or web view, then waits for the callback with the authentication result.
provider The OAuth provider identifier (e.g., 'google', 'github', 'apple').
callbackUrlScheme The URL scheme for the OAuth callback URL.
Returns an AuthResponse containing the Session on successful authentication.
Example:
final response = await authClient.oauth.signIn(
provider: 'google',
callbackUrlScheme: 'myapp',
);
if (response.isSuccess) {
print('OAuth sign-in successful: ${response.data!.user.email}');
}
Note: The server must be configured with the OAuth provider and have the callback URL registered in its trusted origins.
Implementation
Future<AuthResponse<Session>> signIn({
required String provider,
required String callbackUrlScheme,
}) async {
try {
// Get the OAuth URL from the server
final response = await _dio.get(
'${ApiEndpoints.oauthSignIn}/$provider',
queryParameters: {
'callbackUrl': '$callbackUrlScheme://oauth-callback',
},
);
final authUrl = response.data['url'] as String;
// Open the browser for authentication
final result = await FlutterWebAuth2.authenticate(
url: authUrl,
callbackUrlScheme: callbackUrlScheme,
);
// Extract the token from the callback URL
final token = Uri.parse(result).queryParameters['token'];
if (token == null) {
return AuthResponse.error(
AuthError(
code: 'OAUTH_ERROR',
message: 'No token received from OAuth callback',
),
);
}
// Complete the sign-in by exchanging the token
final sessionResponse = await _dio.post(
ApiEndpoints.oauthCallback,
data: {'token': token},
);
final session = Session.fromJson(sessionResponse.data['session'] ?? sessionResponse.data);
await _tokenManager.setAccessToken(session.token);
return AuthResponse.success(session);
} on DioException catch (e) {
return AuthResponse.error(AuthError.fromDio(e));
}
}