createOAuth2Session method

Future createOAuth2Session({
  1. required String provider,
  2. String? success,
  3. String? failure,
  4. List<String>? scopes,
})

Create OAuth2 Session

Allow the user to login to their account using the OAuth2 provider of their choice. Each OAuth2 provider should be enabled from the Appwrite console first. Use the success and failure arguments to provide a redirect URL's back to your app when login is completed.

If there is already an active session, the new session will be attached to the logged-in account. If there are no active sessions, the server will attempt to look for a user with the same email address as the email received from the OAuth2 provider and attach the new session to the existing user. If no matching user is found - the server will create a new user.

A user is limited to 10 active sessions at a time by default. Learn more about session limits.

Implementation

Future createOAuth2Session(
    {required String provider,
    String? success,
    String? failure,
    List<String>? scopes}) async {
  final String path = '/account/sessions/oauth2/{provider}'
      .replaceAll('{provider}', provider);

  final Map<String, dynamic> params = {
    'success': success,
    'failure': failure,
    'scopes': scopes,
    'project': client.config['project'],
  };

  final List query = [];

  params.forEach((key, value) {
    if (value is List) {
      for (var item in value) {
        query.add(Uri.encodeComponent(key + '[]') +
            '=' +
            Uri.encodeComponent(item));
      }
    } else if (value != null) {
      query.add(Uri.encodeComponent(key) + '=' + Uri.encodeComponent(value));
    }
  });

  Uri endpoint = Uri.parse(client.endPoint);
  Uri url = Uri(
      scheme: endpoint.scheme,
      host: endpoint.host,
      port: endpoint.port,
      path: endpoint.path + path,
      query: query.join('&'));

  return client.webAuth(url, callbackUrlScheme: success);
}