flutter_firebase_auth_repository 1.0.0 copy "flutter_firebase_auth_repository: ^1.0.0" to clipboard
flutter_firebase_auth_repository: ^1.0.0 copied to clipboard

A comprehensive Flutter/Dart package that provides a simple, clean repository for handling Firebase Authentication with multiple providers.

πŸ” Firebase Auth Repository #

pub package License: MIT platforms

A simple, clean, and comprehensive repository for handling Firebase Authentication in Flutter. It supports multiple providers out-of-the-box and integrates seamlessly with Firestore.


✨ Features #

  • βœ… Multiple Auth Providers:
    • Email & Password (Sign Up / Sign In / Password Reset)
    • Google Sign-In
    • Facebook Sign-In
    • GitHub Sign-In
    • Microsoft Sign-In
  • βœ… Real-time Auth State: Exposes a Stream<User?> to listen for authentication state changes across your app.
  • βœ… Firestore Integration: Automatically creates a user document in Firestore on the first sign-up.
  • βœ… Platform-Independent Core: Pure Dart logic makes it perfect for any Flutter application.
  • βœ… Clean Architecture Ready: Built with a repository pattern that is easy to integrate into state management solutions like BLoC/Cubit, Riverpod, etc.

πŸ“œ Table of Contents #


πŸš€ Getting Started #

Follow these steps to integrate the Firebase Auth Repository into your Flutter project.

1. Add Dependency #

Add the package to your pubspec.yaml file:

dependencies:
  firebase_auth_repository: ^1.0.0 # Check for the latest version on pub.flutter-io.cn

Then, run flutter pub get in your terminal.

2. Configure Firebase #

Make sure your Flutter app is connected to a Firebase project.

  • Android: Place your google-services.json file in the android/app/ directory.
  • Add Gradle Plugins (Android):
    1. In android/build.gradle, add the google-services classpath:
      // android/build.gradle
      buildscript {
          dependencies {
              // ... other dependencies
              classpath 'com.google.gms:google-services:4.4.1' // Use the latest version
          }
      }
      
    2. In android/app/build.gradle, apply the plugin at the bottom of the file:
      // android/app/build.gradle
      apply plugin: 'com.google.gms.google-services'
      

3. Configure Social Providers #

Google Sign-In (Android)

For standard Google Sign-In, the initial Firebase setup is often sufficient. However, you will need to provide your serverClientId.

πŸ”‘ How to get the serverClientId

  1. Open your google-services.json file.
  2. Find the client_id where "client_type": 3. This is typically the Web client ID.
  3. Copy this value and pass it as the serverClientId parameter to the signInWithGoogle() method.

You can also find this ID in the Google Cloud Console under APIs & Services β†’ Credentials β†’ OAuth 2.0 Client IDs.

Facebook Sign-In (Android)

⚠️ Important: Facebook SDK v15.0.0 and newer require a minimum Android SDK version of 21.

// android/app/build.gradle
defaultConfig {
    // ...
    minSdkVersion 21
    // ...
}
  1. Add Facebook App Credentials In android/app/src/main/res/values/strings.xml, add your Facebook App ID and Client Token:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="facebook_app_id">YOUR_FACEBOOK_APP_ID</string>
        <string name="facebook_client_token">YOUR_FACEBOOK_CLIENT_TOKEN</string>
    </resources>
    
  2. Retrieve Your Credentials

    • Go to the Facebook for Developers portal.
    • Navigate to your app's dashboard.
    • App Settings β†’ Basic: Copy the App ID.
    • App Settings β†’ Advanced: Copy the Client Token.

4. Enable Providers in Firebase #

In your Firebase Console:

  1. Navigate to the Authentication section.
  2. Select the Sign-in method tab.
  3. Enable all the providers you intend to use (Google, Facebook, etc.).
  4. For Facebook, you must also add the App ID and App Secret from the Facebook Developer portal.

πŸ’» Usage Example #

Here is a basic example of how to initialize the repository and trigger a sign-in flow.

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth_repository/firebase_auth_repository.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(); // Initialize Firebase
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final _authRepository = FirebaseAuthRepository();

  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Auth Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // Listen to auth state changes
              StreamBuilder<User?>(
                stream: _authRepository.authStateChanges,
                builder: (context, snapshot) {
                  final user = snapshot.data;
                  if (user != null) {
                    return Text('Welcome ${user.email ?? user.displayName}!');
                  }
                  return const Text('You are not signed in.');
                },
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  try {
                    // Pass your serverClientId here
                    const serverClientId = 'YOUR_GOOGLE_SERVER_CLIENT_ID';
                    await _authRepository.signInWithGoogle(serverClientId: serverClientId);
                    print('Google sign-in successful!');
                  } catch (e) {
                    print('Error signing in with Google: $e');
                  }
                },
                child: const Text('Sign in with Google'),
              ),
              ElevatedButton(
                onPressed: () async {
                  try {
                    await _authRepository.signOut();
                    print('Signed out successfully!');
                  } catch (e) {
                    print('Error signing out: $e');
                  }
                },
                child: const Text('Sign Out'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

πŸ“– API Reference #

Method Description
signUp(...) Creates a new user with email and password.
signIn(...) Signs in an existing user with email and password.
signInWithGoogle(...) Initiates the Google Sign-In flow.
signInWithFacebook() Initiates the Facebook Sign-In flow.
signInWithGitHub() Initiates the GitHub Sign-In flow.
signInWithMicrosoft() Initiates the Microsoft Sign-In flow.
signOut() Signs out the currently authenticated user.
resetPassword(...) Sends a password reset link to the specified email.
authStateChanges A Stream<User?> that emits the current user or null.

πŸ”’ Firestore Security Rules #

If you are using the Firestore integration, it is critical to secure your database. Use these rules as a starting point to ensure users can only access their own data.

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    // Only authenticated users can read or write their own user document
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

πŸ› οΈ For Maintainers & Contributors #

This plugin was created with the flutter create --template=plugin command.

Plugin Structure #

The core Dart logic is located in lib/, while native Android configurations are managed in the android/ directory.

firebase_auth_repository/
β”œβ”€β”€ android/
β”‚   └── src/main/AndroidManifest.xml  <-- Native Android manifest
β”œβ”€β”€ lib/
β”‚   └── firebase_auth_repository.dart   <-- Core Dart logic
└── pubspec.yaml

Internal Android Configuration #

The plugin includes its own android/src/main/AndroidManifest.xml to handle native dependencies like Facebook Login. The Android build tools automatically merge this with your app's main manifest.

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application>
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
        <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>

        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
    </application>
</manifest>

This setup relies on the end-user to define @string/facebook_app_id and @string/facebook_client_token in their app's strings.xml file, as explained in the setup guide.


πŸ“„ License #

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™Œ Maintained By #

Made with ❀️ by Dattaram Kolte

3
likes
0
points
58
downloads

Publisher

verified publishershehzaanmansuri.com

Weekly Downloads

A comprehensive Flutter/Dart package that provides a simple, clean repository for handling Firebase Authentication with multiple providers.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

cloud_firestore, firebase_auth, firebase_core, flutter, flutter_facebook_auth, google_sign_in, http, plugin_platform_interface

More

Packages that depend on flutter_firebase_auth_repository

Packages that implement flutter_firebase_auth_repository