Coder Social home page Coder Social logo

robingenz / capacitor-firebase-authentication Goto Github PK

View Code? Open in Web Editor NEW
67.0 5.0 18.0 3.02 MB

⚡️ Capacitor plugin for Firebase Authentication.

License: MIT License

Ruby 1.95% Java 50.42% Objective-C 1.95% Swift 29.51% JavaScript 0.62% TypeScript 15.55%
capacitor capacitor-plugin android ios firebase firebase-auth firebase-authentication authentication auth web pwa

capacitor-firebase-authentication's Introduction

⚠️ Deprecated repository

This project has been moved to the following monorepo: robingenz/capacitor-firebase.



Firebase Authentication

@robingenz/capacitor-firebase-authentication

Capacitor plugin for Firebase Authentication.


Maintainers

Maintainer GitHub Social
Robin Genz robingenz @robin_genz

Installation

npm install @robingenz/capacitor-firebase-authentication firebase
npx cap sync

Add Firebase to your project if you haven't already (Android / iOS / Web).

On iOS, verify that this function is included in your app's AppDelegate.swift:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}

The further installation steps depend on the selected authentication method:

Attention: Please note that this plugin uses third-party SDKs to offer native sign-in. These SDKs can initialize on their own and collect various data. Here you can find more information.

Configuration

These configuration values are available:

Prop Type Description Default
skipNativeAuth boolean Configure whether the plugin should skip the native authentication. Only needed if you want to use the Firebase JavaScript SDK. Only available for Android and iOS. false
providers string[] Configure which providers you want to use so that only the providers you need are fully initialized. If you do not configure any providers, they will be all initialized. Please note that this does not prevent the automatic initialization of third-party SDKs. Only available for Android and iOS. ["apple.com", "facebook.com", "github.com", "google.com", "microsoft.com", "playgames.google.com", "twitter.com", "yahoo.com", "phone"]

Examples

In capacitor.config.json:

{
  "plugins": {
    "FirebaseAuthentication": {
      "skipNativeAuth": false,
      "providers": ["apple.com", "google.com"]
    }
  }
}

In capacitor.config.ts:

/// <reference types="@capacitor/firebase-authentication" />

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  plugins: {
    FirebaseAuthentication: {
      skipNativeAuth: false,
      providers: ["apple.com", "google.com"],
    },
  },
};

export default config;

Demo

A working example can be found here: robingenz/capacitor-firebase-authentication-demo

Usage

import { FirebaseAuthentication } from '@robingenz/capacitor-firebase-authentication';

const getCurrentUser = async () => {
  const result = await FirebaseAuthentication.getCurrentUser();
  return result.user;
};

const getIdToken = async () => {
  const result = await FirebaseAuthentication.getIdToken();
  return result.token;
};

const setLanguageCode = async () => {
  await FirebaseAuthentication.setLanguageCode({ languageCode: 'en-US' });
};

const signInWithApple = async () => {
  await FirebaseAuthentication.signInWithApple();
};

const signInWithFacebook = async () => {
  await FirebaseAuthentication.signInWithFacebook();
};

const signInWithGithub = async () => {
  await FirebaseAuthentication.signInWithGithub();
};

const signInWithGoogle = async () => {
  await FirebaseAuthentication.signInWithGoogle();
};

const signInWithMicrosoft = async () => {
  await FirebaseAuthentication.signInWithMicrosoft();
};

const signInWithPlayGames = async () => {
  await FirebaseAuthentication.signInWithPlayGames();
};

const signInWithPhoneNumber = async () => {
  const { verificationId } = await FirebaseAuthentication.signInWithPhoneNumber(
    {
      phoneNumber: '123456789',
    },
  );
  const verificationCode = window.prompt(
    'Please enter the verification code that was sent to your mobile device.',
  );
  await FirebaseAuthentication.signInWithPhoneNumber({
    verificationId,
    verificationCode,
  });
};

const signInWithTwitter = async () => {
  await FirebaseAuthentication.signInWithTwitter();
};

const signInWithYahoo = async () => {
  await FirebaseAuthentication.signInWithYahoo();
};

const signOut = async () => {
  await FirebaseAuthentication.signOut();
};

const useAppLanguage = async () => {
  await FirebaseAuthentication.useAppLanguage();
};

API

getCurrentUser()

getCurrentUser() => Promise<GetCurrentUserResult>

Fetches the currently signed-in user.

Returns: Promise<GetCurrentUserResult>


getIdToken(...)

getIdToken(options?: GetIdTokenOptions | undefined) => Promise<GetIdTokenResult>

Fetches the Firebase Auth ID Token for the currently signed-in user.

Param Type
options GetIdTokenOptions

Returns: Promise<GetIdTokenResult>


setLanguageCode(...)

setLanguageCode(options: SetLanguageCodeOptions) => Promise<void>

Sets the user-facing language code for auth operations.

Param Type
options SetLanguageCodeOptions

signInWithApple(...)

signInWithApple(options?: SignInOptions | undefined) => Promise<SignInResult>

Starts the Apple sign-in flow.

Param Type
options SignInOptions

Returns: Promise<SignInResult>


signInWithFacebook(...)

signInWithFacebook(options?: SignInOptions | undefined) => Promise<SignInResult>

Starts the Facebook sign-in flow.

Param Type
options SignInOptions

Returns: Promise<SignInResult>


signInWithGithub(...)

signInWithGithub(options?: SignInOptions | undefined) => Promise<SignInResult>

Starts the GitHub sign-in flow.

Param Type
options SignInOptions

Returns: Promise<SignInResult>


signInWithGoogle(...)

signInWithGoogle(options?: SignInOptions | undefined) => Promise<SignInResult>

Starts the Google sign-in flow.

Param Type
options SignInOptions

Returns: Promise<SignInResult>


signInWithMicrosoft(...)

signInWithMicrosoft(options?: SignInOptions | undefined) => Promise<SignInResult>

Starts the Microsoft sign-in flow.

Param Type
options SignInOptions

Returns: Promise<SignInResult>


signInWithPlayGames(...)

signInWithPlayGames(options?: SignInOptions | undefined) => Promise<SignInResult>

Starts the Play Games sign-in flow.

Param Type
options SignInOptions

Returns: Promise<SignInResult>


signInWithTwitter(...)

signInWithTwitter(options?: SignInOptions | undefined) => Promise<SignInResult>

Starts the Twitter sign-in flow.

Param Type
options SignInOptions

Returns: Promise<SignInResult>


signInWithYahoo(...)

signInWithYahoo(options?: SignInOptions | undefined) => Promise<SignInResult>

Starts the Yahoo sign-in flow.

Param Type
options SignInOptions

Returns: Promise<SignInResult>


signInWithPhoneNumber(...)

signInWithPhoneNumber(options: SignInWithPhoneNumberOptions) => Promise<SignInWithPhoneNumberResult>

Starts the sign-in flow using a phone number.

Either the phone number or the verification code and verification ID must be provided.

Only available for Android and iOS.

Param Type
options SignInWithPhoneNumberOptions

Returns: Promise<SignInWithPhoneNumberResult>


signInWithCustomToken(...)

signInWithCustomToken(options: SignInWithCustomTokenOptions) => Promise<SignInResult>

Starts the Custom Token sign-in flow.

This method cannot be used in combination with skipNativeAuth on Android and iOS. In this case you have to use the signInWithCustomToken interface of the Firebase JS SDK directly.

Param Type
options SignInWithCustomTokenOptions

Returns: Promise<SignInResult>


signOut()

signOut() => Promise<void>

Starts the sign-out flow.


useAppLanguage()

useAppLanguage() => Promise<void>

Sets the user-facing language code to be the default app language.


addListener('authStateChange', ...)

addListener(eventName: 'authStateChange', listenerFunc: AuthStateChangeListener) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for the user's sign-in state changes.

Param Type
eventName 'authStateChange'
listenerFunc AuthStateChangeListener

Returns: Promise<PluginListenerHandle> & PluginListenerHandle


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.


Interfaces

GetCurrentUserResult

Prop Type Description
user User | null The currently signed-in user, or null if there isn't any.

User

Prop Type
displayName string | null
email string | null
emailVerified boolean
isAnonymous boolean
phoneNumber string | null
photoUrl string | null
providerId string
tenantId string | null
uid string

GetIdTokenResult

Prop Type Description
token string The Firebase Auth ID token JWT string.

GetIdTokenOptions

Prop Type Description
forceRefresh boolean Force refresh regardless of token expiration.

SetLanguageCodeOptions

Prop Type Description
languageCode string BCP 47 language code. Example: en-US.

SignInResult

Prop Type Description
user User | null The currently signed-in user, or null if there isn't any.
credential AuthCredential | null Credentials returned by an auth provider.

AuthCredential

Prop Type Description
providerId string The authentication provider ID for the credential. Example: google.com.
accessToken string The OAuth access token associated with the credential if it belongs to an OAuth provider.
idToken string The OAuth ID token associated with the credential if it belongs to an OIDC provider.
secret string The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0 provider.
nonce string The random string used to make sure that the ID token you get was granted specifically in response to your app's authentication request.

SignInOptions

Prop Type Description
customParameters SignInCustomParameter[] Configures custom parameters to be passed to the identity provider during the OAuth sign-in flow.

SignInCustomParameter

Prop Type Description
key string The custom parameter key (e.g. login_hint).
value string The custom parameter value (e.g. [email protected]).

SignInWithPhoneNumberResult

Prop Type Description
verificationId string The verification ID, which is needed to identify the verification code.

SignInWithPhoneNumberOptions

Prop Type Description
phoneNumber string The phone number to be verified.
verificationId string The verification ID which will be returned when signInWithPhoneNumber is called for the first time. The verificationCode must also be provided.
verificationCode string The verification code from the SMS message. The verificationId must also be provided.

SignInWithCustomTokenOptions

Prop Type Description
token string The custom token to sign in with.

PluginListenerHandle

Prop Type
remove () => Promise<void>

AuthStateChange

Prop Type Description
user User | null The currently signed-in user, or null if there isn't any.

Type Aliases

AuthStateChangeListener

Callback to receive the user's sign-in state change notifications.

(change: AuthStateChange): void

FAQ

  1. What does this plugin do?
    This plugin enables the use of Firebase Authentication in a Capacitor app. It uses the Firebase SDK for Java (Android), Swift (iOS) and JavaScript.
  2. What is the difference between the web implementation of this plugin and the Firebase JS SDK?
    The web implementation of this plugin encapsulates the Firebase JS SDK and enables a consistent interface across all platforms. You can decide if you prefer to use the web implementation or the Firebase JS SDK.
  3. What is the difference between the native and web authentication?
    For web authentication, the Firebase JS SDK is used. This only works to a limited extent on Android and iOS in the WebViews (see here). For native authentication, the native SDKs from Firebase, Google, etc. are used. These offer all the functionalities that the Firebase JS SDK also offers on the web. However, after a login with the native SDK, the user is only logged in on the native layer of the app. If the user should also be logged in on the web layer, additional steps are required (see here).
  4. How can I use this plugin with the Firebase JavaScript SDK?
    See here.

Changelog

See CHANGELOG.md.

License

See LICENSE.

capacitor-firebase-authentication's People

Contributors

f7fabian avatar merganon avatar mesqueeb avatar nkalupahana avatar robingenz avatar vojto avatar yaron1m avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

capacitor-firebase-authentication's Issues

bug: unable to signInWithCredential using plugin with angular fire

Plugin version: ^0.3.11

Platform(s): iOS

Current behavior: At a loss as to what's going on. Google sign in is successful and giving a result with an idToken, but calling this.afAuth.signInWithCredential never resolves. I'm not sure if I'm passing a bad object or what. I'm using this plugin with firebase and angular fire:

"@angular/fire": "^7.1.1",
"@robingenz/capacitor-firebase-authentication": "^0.3.11",
"firebase": "^9.5.0",

Expected behavior: signInWithCredential resolves

Steps to reproduce:

    const result = await FirebaseAuthentication.signInWithGoogle();
    console.log('[login] signed in', result);
    const credential = GoogleAuthProvider.credential(result.credential?.idToken);

    this.afAuth.signInWithCredential(credential).then(uc => {
      console.log('[login] success: ', uc);
    }, err => {
      console.log('[login] error: ', err);
    }).catch(err => console.log('[login] cred caught error', err));

Other information:
Possibly not a bug with this plugin, but really not sure what's going on here. Found some similar issues googling around to no resolve and hoping someone else has ideas.

Capacitor doctor:

💊   Capacitor Doctor  💊 

Latest Dependencies:

  @capacitor/cli: 3.3.2
  @capacitor/core: 3.3.2
  @capacitor/android: 3.3.2
  @capacitor/ios: 3.3.2

Installed Dependencies:

  @capacitor/cli: 3.2.5
  @capacitor/core: 3.2.5
  @capacitor/android: 3.2.5
  @capacitor/ios: 3.2.5

[success] iOS looking great! 👌
[success] Android looking great! 👌

request: Add twitter auth example (ios with skipNativeAuth)

Based on these docs:

https://github.com/robingenz/capacitor-firebase-authentication/blob/main/docs/firebase-js-sdk.md

I tried to implement Twitter:

  async function signinWithTwitter(): Promise<void> {
    // 1. Create credentials on the native layer
    const result: SignInResult = await FirebaseAuthentication.signInWithTwitter()
    if (!result.credential?.idToken || !result.credential?.secret) {
      throw new Error('Twitter error')
    }
    // 2. Create credentials on the web layer
    const credential = TwitterAuthProvider.credential(
      result.credential?.idToken,
      result.credential?.secret
    )
    // 3. Sign in on the web layer using the id token
    await signInWithCredential(firebaseAuth, credential)
  }

However, that doesn't work. The result looks like:

image

I don't get the idToken and secret.

It seems like Twitter works with redirect detection....?
I do see the redirection URL: do we need to parse something from here?

Screenshot 2021-10-07 at 0 23 20

All help much appreciated!

my config:

"FirebaseAuthentication": {
      "skipNativeAuth": true,
      "providers": [
        "apple.com",
        "google.com",
        "twitter.com"
      ]
    },

bug: FirebaseError: Firebase: Nonce is missing in the request. (auth/missing-or-invalid-nonce)

This is on iOS + Apple authentication with skipNativeAuth error

image

my function:

async function signinWithApple() {
    // 1. Create credentials on the native layer
    const result: SignInResult = await FirebaseAuthentication.signInWithApple()
    // 2. Create credentials on the web layer
    const provider = new OAuthProvider('apple.com')
    const credential = provider.credential({
      idToken: result.credential?.idToken,
      rawNonce: result.credential?.nonce,
    })
    // 3. Sign in on the web layer using the id token and nonce
    await signInWithCredential(firebaseAuth, credential)
  }

my config:

"FirebaseAuthentication": {
      "skipNativeAuth": true,
      "providers": [
        "apple.com",
        "google.com",
        "twitter.com"
      ]
    },

feat(android): return `nonce` on sign in

Is your feature request related to a problem? Please describe:

Currently, signing in to Apple using the Firebase JS SDK is not possible on Android, among other reasons (see #48), because the nonce is not returned.

Describe the solution you'd like:

Return the nonce on sign in.

OAuthCredential (see #44):

export interface OAuthCredential extends AuthCredential {
  accessToken?: string;
  idToken?: string;
  secret?: string;
  nonce?: string;
}

Describe alternatives you've considered:

No alternative options.

Additional context:

AuthProvider still throws "undefined is not an object"

Hey Robin , this is regarding the issue I posted yesterday. (thx for your work btw)

I updated the package to 0.3.7, deleted the node_modules, ran npm install and then copied the new function for Google sign-in from the documentation to my code.

You said Google sign-in works fine on your end, however this line still throws the same error for me:
const credential = app.auth.GoogleAuthProvider.credential(
throws:
Exception with thrown value: TypeError: undefined is not an object (evaluating 'Je.auth.GoogleAuthProvider.credential')

I get the same error for Apple sign-in.

Is there maybe something wrong with my setup?

import { FirebaseAuthentication } from '@robingenz/capacitor-firebase-authentication'
import firebase from "firebase/app"
import 'firebase/auth';

const app = firebase.initializeApp({
    apiKey: ...,
    authDomain: ...,
    projectId: ...,
    storageBucket: ...,
    messagingSenderId: ...,
    appId: ...
})

...

const signInWithGoogle = async () => {
  // 1. Sign in on the native layer
  const result = await FirebaseAuthentication.signInWithGoogle();
  // 2. Sign in on the web layer using the id token
  const credential = app.auth.GoogleAuthProvider.credential(
    result.credential?.idToken,
  );
  await app.auth().signInWithCredential(credential);
};

...

signInWithGoogle()

bug: cannot call value of non-function type 'GIDSignIn'

Current behavior:

The following occurs in Azure pipelines during xcodebuild:

❌  /Users/runner/work/1/s/node_modules/@robingenz/capacitor-firebase-authentication/ios/Plugin/Handlers/GoogleAuthProviderHandler.swift:26:19: cannot call value of non-function type 'GIDSignIn'

        GIDSignIn.sharedInstance().signOut()
                      ^             ~~



❌  /Users/runner/work/1/s/node_modules/@robingenz/capacitor-firebase-authentication/ios/Plugin/Handlers/GoogleAuthProviderHandler.swift:34:15: initializer for conditional binding must have Optional type, not 'GIDAuthentication'

        guard let authentication = user.authentication else {
                  ^             ~~



❌  /Users/runner/work/1/s/node_modules/@robingenz/capacitor-firebase-authentication/ios/Plugin/Handlers/GoogleAuthProviderHandler.swift:37:84: value of optional type 'String?' must be unwrapped to a value of type 'String'

        let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
              ^                    ~~~~~~~~~~~~~~~~~~~

Expected behavior:

There should be no build errors.

Steps to reproduce:

Install this plugin and build the app in a fresh environment (e.g. CI env so that no caches are used).

Other information:

### Stack

| Key                         | Value                                            |
| --------------------------- | ------------------------------------------------ |
| OS                          | 10.15.7                                          |
| Ruby                        | 2.7.4                                            |
| Bundler?                    | true                                             |
| Git                         | git version 2.32.0                               |
| Installation Source         | ~/hostedtoolcache/Ruby/2.7.4/x64/bin/fastlane    |
| Host                        | Mac OS X 10.15.7 (19H1217)                       |
| Ruby Lib Dir                | ~/hostedtoolcache/Ruby/2.7.4/x64/lib             |
| OpenSSL Version             | OpenSSL 1.1.1k  25 Mar 2021                      |
| Is contained                | false                                            |
| Is homebrew                 | false                                            |
| Is installed via Fabric.app | false                                            |
| Xcode Path                  | /Applications/Xcode_12.4.app/Contents/Developer/ |
| Xcode Version               | 12.4                                             |

Capacitor doctor:

$ npx capacitor doctor
   Capacitor Doctor   

Latest Dependencies:

  @capacitor/cli: 3.1.1
  @capacitor/core: 3.1.1
  @capacitor/android: 3.1.1
  @capacitor/ios: 3.1.1

Installed Dependencies:

  @capacitor/core: 3.0.2
  @capacitor/cli: 3.0.1
  @capacitor/ios: 3.0.2
  @capacitor/android: 3.0.2

[error] Xcode is not installed

bug: Callbacks are not triggered

Plugin version:
@robingenz/[email protected]
[email protected]

Platform(s):
Android
iOS

Current behavior:
When successfully signing in with FirebaseAuthentication.signInWithGoogle() the promise resolves but none of the event listeners fire. I tested firebase onAuthStateChanged and onIdTokenChanged callbacks and also FirebaseAuthentication.addListener("authStateChange", ...). When I skipped native auth and tried to sign in through firebase js sdk with the id token then firebase signInWithCredential function just froze and did not resolve.
Everything works correctly in web implementation.

Expected behavior:
All the callbacks should trigger after successful sign in.

Steps to reproduce:

  • Listen to firebase.auth().onAuthStateChanged callback
  • Sign in to google with FirebaseAuthentication.signInWithGoogle()

Related code:
When I tried to sign in with firebase js sdk, signInWithCredential function just hangs and I did not reach "signInWithCredential finished" console log.

FirebaseAuthentication.signInWithGoogle()
      .then(async (response: SignInResult) => {
        const credential = firebase.auth.GoogleAuthProvider.credential(
          response.credential?.idToken
        );

        const authResult = await firebase
          .auth()
          .signInWithCredential(credential)
          .catch((err) => {
            console.debug("AUTH ERROR", err);
          });

        console.debug("signInWithCredential finished", authResult);
      })
      .catch((error) => {
        dispatchToast(t("start.methods.error_generic"));
        console.debug("FirebaseAuthentication.catch", error);
      })
      .finally(() => {
        console.debug("FirebaseAuthentication.finally");
        setLoading(false);
      });

Callback that did not trigger:

FirebaseAuthentication.addListener("authStateChange", (stateChange) => {
      console.debug("FirebaseAuthentication authStateChange", stateChange);
});

Capacitor doctor:

💊   Capacitor Doctor  💊 

Latest Dependencies:

  @capacitor/cli: 3.2.2
  @capacitor/core: 3.2.2
  @capacitor/android: 3.2.2
  @capacitor/ios: 3.2.2

Installed Dependencies:

  @capacitor/cli: 3.2.0
  @capacitor/ios: 3.2.0
  @capacitor/core: 3.2.0
  @capacitor/android: 3.2.0

[success] iOS looking great! 👌
[success] Android looking great! 👌

feat: add Sign-In with Yahoo

Is your feature request related to a problem? Please describe:

Yahoo Sign-In is currently not supported.

Describe the solution you'd like:

Support Sign-In with Yahoo.

bug: Error: 10

Plugin version: 0.3.11

Platform(s): Android

Current behavior: When signing in with Google, after choosing the right Google account I get the following error:

Error: 10: 
    at Object.cap.fromNative ((index):426)
    at <anonymous>:1:18

Expected behavior: Sign in successfully.

Steps to reproduce:

  1. Install plugin.
  2. Call FirebaseAuthentication.signInWithGoogle()
  3. Choose account

This happens both when skipNativeAuth is true and false, running on Android Simulator

Capacitor doctor:

Latest Dependencies:

  @capacitor/cli: 3.3.0
  @capacitor/core: 3.3.0
  @capacitor/android: 3.3.0
  @capacitor/ios: 3.3.0

Installed Dependencies:

  @capacitor/cli: 3.2.4
  @capacitor/android: 3.2.4
  @capacitor/core: 3.2.2
  @capacitor/ios: 3.2.4

The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.

Current behavior:
I just installed @robingenz/[email protected] . I did not use it in the code and after sync with capacitor I get "The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first. "

Expected behavior:
Above behaviour should not happen . This is happening when I haven't even imported anything from the package yet.

Capacitor doctor:

   Capacitor Doctor   

Latest Dependencies:

  @capacitor/cli: 3.2.0
  @capacitor/core: 3.2.0
  @capacitor/android: 3.2.0
  @capacitor/ios: 3.2.0

Installed Dependencies:

  @capacitor/ios: not installed
  @capacitor/core: 3.2.0
  @capacitor/cli: 3.2.0
  @capacitor/android: 3.2.0

[success] Android looking great! 👌

Error "FirebaseAuthentication" plugin is not implemented on android

I already added all the necessary libraries in my project gradle, and module gradle in android. But I am still getting this error. Is there something I missed?


Plugin version:

^0.3.12

Platform(s):

Android

Current behavior:
Everything is setup properly and there are no console error, no build errors either. But when I clicked the button that invokes the main signing method:

const result = await FirebaseAuthentication.signInWithGoogle();

I am getting the toast message that says: "FirebaseAuthentication" plugin is not implemented on android

Expected behavior:
When I click the signin button, a prompt will appear or something?

Steps to reproduce:

Related code:

Vue component:

import { FirebaseAuthentication } from '@robingenz/capacitor-firebase-authentication';
...
const result = await FirebaseAuthentication.signInWithGoogle();

capacitor.config.json

{
  "appId": "org.my.app",
  "appName": "My App",
  "bundledWebRuntime": false,
  "npmClient": "yarn",
  "webDir": "www",
  "plugins": {
    "FirebaseAuthentication": {
      "skipNativeAuth": false,
      "providers": [
        "google.com"
      ]
    }
  }
}

Capacitor doctor:

Latest Dependencies:

  @capacitor/cli: 3.3.2
  @capacitor/core: 3.3.2
  @capacitor/android: 3.3.2
  @capacitor/ios: 3.3.2

Installed Dependencies:

  @capacitor/android: not installed
  @capacitor/cli: 3.3.2
  @capacitor/core: 3.3.2
  @capacitor/ios: 3.3.2

feat: support `onAuthStateChanged`

Is your feature request related to a problem? Please describe:

Currently there is no option to be notified about a SignIn or SignOut.

Describe the solution you'd like:

Support onAuthStateChanged.

addListener('authStateChange', ...)

feat: add Sign-In with Twitter

Is your feature request related to a problem? Please describe:

Twitter Sign-In is currently not supported.

Describe the solution you'd like:

Support Sign-In with Twitter.

feat: return `AuthCredential` on sign in

Is your feature request related to a problem? Please describe:

Currently it is not possible to query the accessToken of an OAuth provider after sign in.

Describe the solution you'd like:

Return AuthCredential/OAuthCredential on sign in.

SignInResult:

export interface SignInResult {
  /**
   * The currently signed-in user, or null if there isn't any.
   */
  user: User | null;
  /**
   * Credentials returned by an auth provider.
   */
  credential: AuthCredential | null;
}

export interface AuthCredential {
  providerId: string;
  signInMethod: string;
}

export interface OAuthCredential extends AuthCredential {
  accessToken?: string;
  idToken?: string;
  secret?: string;
}

Describe alternatives you've considered:

Additional context:

feat: Google Play Services support

Not sure how Google Play Services rates in popularity to the other methods of authentication this plugin could integrate, but I can confidently say that supporting it would reopen the door to developing Android games in Javascript. Direct plugins to GPS have fallen by the wayside in recent years:

https://github.com/artberri/cordova-plugin-play-games-services
https://github.com/openforge/capacitor-game-services

And yet, you'd be hard pressed to find an Android game that doesn't use it. My story is of developing a Javascript game over many years, hoping for platform ubiquity, and missing out due to this hole in Google integration.

suggestion: convert single class to standalone functions

Hey @robingenz
I was reading your source code and I see that you're using a single class with methods for the web code:

export class FirebaseAuthenticationWeb

However, the issue with a big class with methods is that when we don't use some of the providers on there, all those functions are still bundled with our code via webpack/rollup. Because a class can't be tree-shooken I think?

Will you consider rewriting these as just stand-alone functions and exporting each function separately instead?

feat: add Sign-In with Facebook

Is your feature request related to a problem? Please describe:

Facebook Sign-In is currently not supported.

Describe the solution you'd like:

Support Sign-In with Facebook.

feat: implement `skipNativeAuth` config option

Is your feature request related to a problem? Please describe:

It is currently not possible to use the Firebase JS SDK to sign in to Apple. (see #41 (comment)).
One the one hand, for apple.com, the rawNonce (see here) must also be passed when signing in.
On the other hand, this rawNonce can only be used once.
A parallel login on native level and web level is therefore not possible.

Describe the solution you'd like:

Add a configuration option to skip authentication at the native layer (See #47 for more information).

{
  "plugins": {
    "FirebaseAuthentication": {
      "skipNativeAuth": false
    }
  }
}

Default value: false

Describe alternatives you've considered:

Currently, I am not aware of any alternative options. Any ideas are welcome.

Additional context:

bug: Missing Nonce - Sign In with Apple on iOS with Javascript SDK

It seems that the nonce returned by FirebaseAuthentication.signInWithApple() is invalid, or provider.credential is not building the credential correctly.

Code:

export async function appleLogin() {
  // 1. Create credentials on the native layer
  const result = await FirebaseAuthentication.signInWithApple()
  // 2. Sign in on the web layer using the id token and nonce
  const provider = new OAuthProvider('apple.com')
  const credential = provider.credential({
    idToken: result.credential?.idToken,
    rawNonce: result.credential?.nonce
  })
  await signInWithCredential(auth, credential)
}

Error:
Unhandled Promise Rejection: FirebaseError: Firebase: Nonce is missing in the request. (auth/missing-or-invalid-nonce).

feat: Firebase 8.1 compatible version

Is your feature request related to a problem? Please describe:

Is there a Firebase 8.1 compatible version you can provide? Or is it too much work?

Describe alternatives you've considered:

feat: support custom provider parameters

Is your feature request related to a problem? Please describe.
Firebase Authentication allows to specify custom provider parameters.

Example:

provider.addCustomParameter("locale", "fr");

This is currently not possible with this plugin.

Describe the solution you'd like
Add support for custom provider parameters.

feat: Find a way to prevent Facebook SDK to be included into app source code

Is your feature request related to a problem? Please describe:
<-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -

We don't use Facebook authentication in our app. But I believe the FBSDK is still included in the built app.

Describe the solution you'd like:
<-- A clear and concise description of what you want to happen. -→

I'd love to find a way to prevent any FBSDK code from being included in my app.

Describe alternatives you've considered:
<-- A clear and concise description of any alternative solutions or features you've considered. -

Fork this repo.

Additional context:
<-- Add any other context or screenshots about the feature request here. -

Much much lower priority than #93 !!

bug: Google Play Services error reporting is undescriptive

Plugin version:
v0.3.11

Platform(s):
Android

Current behavior:
FirebaseAuthentication.signInWithPlayGames() generates undescriptive error messages of the form: "Error: 4: " (Where the number can be 4 or 8 from what I've seen so far). Anecdotally, "Error: 4: " seems to be thrown when login is attempted without network connectivity.
Checking logs in Android studio, there is no additional reporting that helps narrow down the problem.

Expected behavior:
Error messages that describe the problem.

Steps to reproduce:
Set phone to airplane mode and call "FirebaseAuthentication.signInWithPlayGames()", observe error logs.

bug: FirebaseAuth not found after installing other Capacitor Plugin

Plugin version:

Latest

Platform(s):

Android

Current behavior:

Login not working after adding this plugin https://github.com/capacitor-community/camera-preview

Expected behavior:

Login should work as it did before installing https://github.com/capacitor-community/camera-preview

Steps to reproduce:

Setup new project
install capacitor-firebase-authentication
add android implementation
add web implementtation
check if the login works
npm / yarn install capacitor-firebase-authentication
add this code to mainactivity.java

public class MainActivity extends BridgeActivity {
@OverRide
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
        // Additional plugins you've installed go here
        // Ex: add(TotallyAwesomePlugin.class);
        add(CameraPreview.class);
    }});
}

}

After a successful gradel build the login isn't working anymore. Web still works no testing on iOS so far.

Error message in Android Studio:
E/Capacitor/Console: File: http://localhost/js/chunk-vendors.08187ed4.js - Line 26 - Msg: Error: "FirebaseAuthentication" plugin is not implemented on android

Other information:

Capacitor doctor:

insert the output from `npx cap doctor` here

Capacitor Doctor

Latest Dependencies:

@capacitor/cli: 3.2.0
@capacitor/core: 3.2.0
@capacitor/android: 3.2.0
@capacitor/ios: 3.2.0

Installed Dependencies:

@capacitor/cli: 3.2.0
@capacitor/ios: 3.2.0
@capacitor/android: 3.2.0
@capacitor/core: 3.2.0

[success] Android looking great! �
[error] Xcode is not installed

feat: add method `getIdToken`

Is your feature request related to a problem? Please describe:

Currently the Firebase Auth ID token is only received after login. There is no possibility to request it again.

Describe the solution you'd like:

Add a new method getIdToken that returns the Firebase Auth ID Token.

feat: add Sign-In with GitHub

Is your feature request related to a problem? Please describe:

GitHub Sign-In is currently not supported.

Describe the solution you'd like:

Support Sign-In with GitHub.

bug: Undefined is not a constructor | OAuthProvider("apple.com")

I followed this documentation here on how to sign into the web layer with this plugin.

I copied the exact const signInWithApple = async () => { function into my project,
however const provider = new firebase.auth.OAuthProvider('apple.com'); is throwing this error:

Exception with thrown value: TypeError: undefined is not a constructor (evaluating 'new qe.auth.OAuthProvider("apple.com")')

Device
iPhone running on iOS 14.7.1

Plugin version:
capacitor-firebase-authentication: 0.3.6
firebase: 8.10.0
capacitor: 3.2.0

bug: Auth instance doesn't get authenticated

On Capacitor 3.0, using Firebase v9 with modular syntax I have the issue that my auth instance doesn't get authenticated.

This is the way I'm instantiating my firebaseApp and auth:

/**
 * @param {import('firebase/app').FirebaseApp} _firebaseApp
 * @returns {import('firebase/auth').Auth}
 */
function createFirebaseAuth(_firebaseApp) {
  const auth =
    platform === 'web'
      ? getAuth(_firebaseApp)
      : initializeAuth(_firebaseApp, { persistence: indexedDBLocalPersistence })
  useDeviceLanguage(auth)
  return auth
}

const firebaseApp =  initializeApp(config)
const auth = createFirebaseAuth(firebaseApp)

I need to use initializeAuth on capacitor iOS/android, because otherwise the app doesn't launch properly. (see the reason for that here).

The entire app we have uses these firebaseApp and auth instances. We need to use capacitor-firebase-authentication just to authenticate and nothing else.

I get the feeling looking at the source code that capacitor-firebase-authentication uses their own instantiated auth instance that's completely separate from ours.

I feel that especially because I can't see any way to pass our auth instance to get authenticated.

How can I best solve my issue?

Currently all the authentication methods of this library work, but just nothing happens after that and our auth instance never gets authenticated.

Best regards.

feat: add method `signInWithApple`

Is your feature request related to a problem? Please describe:

Apple Sign-In is currently not supported on Android.

Describe the solution you'd like:

Support Apple Sign-In on Android.

feat(ios): return `nonce` on sign in

Is your feature request related to a problem? Please describe:

Currently, signing in to Apple using the Firebase JS SDK is not possible, among other reasons (see #48), because the nonce is not returned.

Describe the solution you'd like:

Return the nonce on sign in.

OAuthCredential (see #44):

export interface OAuthCredential extends AuthCredential {
  accessToken?: string;
  idToken?: string;
  secret?: string;
  nonce?: string;
}

Describe alternatives you've considered:

No alternative options.

Additional context:

feat: Phone verification

Thank you for creating this package!!

Is your feature request related to a problem? Please describe:
I hope you would add firebase's phone verification added.

feat: add method `useAppLanguage`

Is your feature request related to a problem? Please describe:

Currently there is no option to set the user-facing language code to be the default app language.

Describe the solution you'd like:

Add method useAppLanguage.

Could not resolve dependency

Is there a way to use this package without upgrading Capacitor to 3.2.0 or is it mandatory?

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: @capacitor/[email protected]
npm ERR! node_modules/@capacitor/core
npm ERR!   peer @capacitor/core@"~3.0.0" from @capacitor/[email protected]
npm ERR!   node_modules/@capacitor/android
npm ERR!     @capacitor/android@"^3.0.0" from the root project
npm ERR!   peer @capacitor/core@"^3.0.0" from @capacitor/[email protected]
npm ERR!   node_modules/@capacitor/app
npm ERR!     @capacitor/app@"^1.0.2" from the root project
npm ERR!   6 more (@capacitor/device, @capacitor/ios, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! @robingenz/capacitor-firebase-authentication@"*" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @capacitor/[email protected]
npm ERR! node_modules/@capacitor/core
npm ERR!   peer @capacitor/core@"^3.2.0" from @robingenz/[email protected]
npm ERR!   node_modules/@robingenz/capacitor-firebase-authentication
npm ERR!     @robingenz/capacitor-firebase-authentication@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\...\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\...\AppData\Local\npm-cache\_logs\2021-08-25T19_01_07_115Z-debug.log

Capacitor doctor:

   Capacitor Doctor   

Latest Dependencies:

  @capacitor/cli: 3.2.0
  @capacitor/core: 3.2.0
  @capacitor/android: 3.2.0
  @capacitor/ios: 3.2.0

Installed Dependencies:

  @capacitor/cli: 3.0.0
  @capacitor/core: 3.0.0
  @capacitor/ios: 3.0.0
  @capacitor/android: 3.0.0

feat: add web support

Is your feature request related to a problem? Please describe:

Web platform is currently not supported.

Describe the solution you'd like:

Add support for the web platform.

feat: add method `getCurrentUser`

Is your feature request related to a problem? Please describe:

It's not possible to get the currently signed-in user.

Describe the solution you'd like:

Add a new method getCurrentUser that returns the currently signed-in user.

request.auth is null in security rules so Firebase API calls fail due to permissions.

Plugin version:

0.3.11

Platform(s):

Android

Current behavior:

On a physical Android device, any calls made to the Firebase Firestore or Storage API would fail if the Security Rules are set to only accept authenticated users.
Example of Security Rules below where write calls would only be accepted for authenticated users:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

The error returned:

2021-11-17 12:01:55.373 9229-9229/myapp E/Capacitor/Console: File: http://localhost/tabs/add - Line 0 - Msg: Uncaught (in promise) FirebaseError: Firebase Storage: User does not have permission to access 'ugc_images/1637179300409.jpeg'. (storage/unauthorized)
    {
      "error": {
        "code": 403,
        "message": "Permission denied."
      }
    }

If we remove the if request.auth != null; bit from the rules, then everything would work correctly as expected.

So for some reason the authentication payload is not being sent to Firebase. Even though I'm pretty sure that the user has signed in successfully, and getCurrentUser() returns the user object.

I was only able to make this work on the web layer (PC browser) when we use JavaScript JS SDK with "skipNativeAuth": true, but that defeats the purpose because we want the app to function on the physical device.

Expected behavior:

Authentication payload to be sent to respect Security Rules with request.auth conditions.

Steps to reproduce:

Related code:

// capacitor.config.json
{
  "appId": "myapp",
  "appName": "myapp",
  "webDir": "dist",
  "bundledWebRuntime": false,
  "plugins": {
    "FirebaseAuthentication": {
      "skipNativeAuth": false,
      "providers": [
        "twitter.com",
        "google.com",
        "facebook.com"
      ]
    }
  }
}
// Login.vue
const signInWithGoogle = async () => {
  const result = await FirebaseAuthentication.signInWithGoogle();
  console.log(result.user); // successfully get result
};

Other information:

Capacitor doctor:

💊 Capacitor Doctor 💊

Latest Dependencies:

@capacitor/cli: 3.3.2
@capacitor/core: 3.3.2
@capacitor/android: 3.3.2
@capacitor/ios: 3.3.2

Installed Dependencies:

@capacitor/cli: 3.2.3
@capacitor/core: 3.2.3
@capacitor/android: 3.2.5
@capacitor/ios: 3.2.5

[success] Android looking great! 👌
[error] Xcode is not installed

I'm currently baffled and not sure how to proceed or if I'm missing something. Any help would be appreciated!

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.