Giter VIP home page Giter VIP logo

cordova-plugin-firebase-authentication's Introduction

Cordova plugin for Firebase Authentication

NPM version NPM downloads NPM total downloads Twitter

Donate Your help is appreciated. Create a PR, submit a bug or just grab me 🍺

Index

Supported Platforms

  • iOS
  • Android

Installation

cordova plugin add cordova-plugin-firebase-authentication

Use variables IOS_FIREBASE_POD_VERSION and ANDROID_FIREBASE_BOM_VERSION to override dependency versions for Firebase SDKs:

$ cordova plugin add cordova-plugin-firebase-authentication \
--variable IOS_FIREBASE_POD_VERSION="9.3.0" \
--variable ANDROID_FIREBASE_BOM_VERSION="30.3.1"

To use phone number authentication on iOS, your app must be able to receive silent APNs notifications from Firebase. For iOS 8.0 and above silent notifications do not require explicit user consent and is therefore unaffected by a user declining to receive APNs notifications in the app. Thus, the app does not need to request user permission to receive push notifications when implementing Firebase phone number auth.

Adding required configuration files

Cordova supports resource-file tag for easy copying resources files. Firebase SDK requires google-services.json on Android and GoogleService-Info.plist on iOS platforms.

  1. Put google-services.json and/or GoogleService-Info.plist into the root directory of your Cordova project
  2. Add new tag for Android platform
<platform name="android">
    ...
    <resource-file src="google-services.json" target="app/google-services.json" />
</platform>
...
<platform name="ios">
    ...
    <resource-file src="GoogleService-Info.plist" />
</platform>

Type Aliases

UserDetails

UserDetails: Object

Represents a user's profile information in your Firebase project's user database.

Type declaration

Name Type Description
displayName string Main display name of this user from the Firebase project's user database
email string Main email address of the user, as stored in the Firebase project's user database.
emailVerified boolean true if the user's email is verified.
phoneNumber string | null Phone number of the user, as stored in the Firebase project's user database, or null if none exists.
photoURL string URL of this user's main profile picture, as stored in the Firebase project's user database.
providerId string -
uid string String used to uniquely identify your user in your Firebase project's user database

Functions

createUserWithEmailAndPassword

createUserWithEmailAndPassword(email, password): Promise<void>

Creates a new user account with the given email address and password.

Example

cordova.plugins.firebase.auth.createUserWithEmailAndPassword("[email protected]", "pa55w0rd");

Parameters

Name Type Description
email string User account email
password string User accound password

Returns

Promise<void>

Callback when operation is completed


getCurrentUser

getCurrentUser(): Promise<UserDetails>

Returns the current user in the Firebase instance.

Returns

Promise<UserDetails>

Fulfills promise with user details


getIdToken

getIdToken(forceRefresh): Promise<string>

Returns a JWT token used to identify the user to a Firebase service.

Example

cordova.plugins.firebase.auth.getIdToken().then(function(idToken) {
    // send token to server
});

Parameters

Name Type Description
forceRefresh boolean When true cached value is ignored

Returns

Promise<string>

Fulfills promis with id token string value


onAuthStateChanged

onAuthStateChanged(callback, errorCallback?): () => void

Registers a block as an auth state did change listener. To be invoked when:

  • The block is registered as a listener,
  • A user with a different UID from the current user has signed in, or
  • The current user has signed out.

Parameters

Name Type Description
callback (userDetails: UserDetails) => void Callback function
errorCallback? (error: string) => void Error callback function

Returns

fn

(): void

Returns

void


sendEmailVerification

sendEmailVerification(): Promise<void>

Initiates email verification for the current user.

Example

cordova.plugins.firebase.auth.sendEmailVerification();

Returns

Promise<void>

Callback when operation is completed


sendPasswordResetEmail

sendPasswordResetEmail(email): Promise<void>

Triggers the Firebase Authentication backend to send a password-reset email to the given email address, which must correspond to an existing user of your app.

Example

cordova.plugins.firebase.auth.sendPasswordResetEmail("[email protected]");

Parameters

Name Type Description
email string User account email

Returns

Promise<void>

Callback when operation is completed


signInAnonymously

signInAnonymously(): Promise<void>

Create and use temporary anonymous account to authenticate with Firebase.

Example

cordova.plugins.firebase.auth.signInAnonymously();

Returns

Promise<void>

Callback when operation is completed


signInWithApple

signInWithApple(idToken, rawNonce): Promise<void>

Uses Apples's idToken and rawNonce to sign-in into firebase account. For getting idToken (rawNonce is optional) you can use cordova-plugin-sign-in-with-apple (or any other cordova plugin for Apple Sign-In).

See

Example

// below we use cordova-plugin-sign-in-with-apple to trigger Apple Login UI
cordova.plugins.SignInWithApple.signin({
    requestedScopes: [0, 1]
}, function(res) {
    cordova.plugins.firebase.auth.signInWithApple(res.identityToken).then(function() {
        console.log("Firebase logged in with Apple");
    }, function(err) {
        console.error("Firebase login failed", err);
    });
}, function(err) {
    console.error("Apple signin failed", err);
});

Parameters

Name Type Description
idToken string Apple's ID token string
rawNonce string Apple's raw token string

Returns

Promise<void>

Callback when operation is completed


signInWithCustomToken

signInWithCustomToken(authToken): Promise<void>

You can integrate Firebase Authentication with a custom authentication system by modifying your authentication server to produce custom signed tokens when a user successfully signs in. Your app receives this token and uses it to authenticate with Firebase.

See

Parameters

Name Type Description
authToken string Custom auth token

Returns

Promise<void>

Callback when operation is completed


signInWithEmailAndPassword

signInWithEmailAndPassword(email, password): Promise<void>

Triggers the Firebase Authentication backend to send a password-reset email to the given email address, which must correspond to an existing user of your app.

Example

cordova.plugins.firebase.auth.signInWithEmailAndPassword("[email protected]", "pa55w0rd");

Parameters

Name Type Description
email string User account email
password string User accound password

Returns

Promise<void>

Callback when operation is completed


signInWithFacebook

signInWithFacebook(accessToken): Promise<void>

Uses Facebook's accessToken to sign-in into firebase account. In order to retrieve those tokens follow instructions for iOS and Android from Firebase docs.

See

Parameters

Name Type Description
accessToken string Facebook's access token string

Returns

Promise<void>

Callback when operation is completed


signInWithGoogle

signInWithGoogle(idToken, accessToken): Promise<void>

Uses Google's idToken and accessToken to sign-in into firebase account.

See

Example

// Below we use cordova-plugin-googleplus to trigger Google Login UI
window.plugins.googleplus.login({
    scopes: '... ',
    webClientId: '1234...',
    offline: true
}, function(res) {
    cordova.plugins.firebase.auth.signInWithGoogle(res.idToken, res.accessToken).then(function() {
        console.log("Firebase logged in with Google");
    }, function(err) {
        console.error("Firebase login failed", err);
    });
}, function(err) {
    console.error("Google login failed", err);
});

Parameters

Name Type Description
idToken string Google ID token
accessToken string Google Access token

Returns

Promise<void>

Callback when operation is completed


signInWithTwitter

signInWithTwitter(token, secret): Promise<void>

Uses Twitter's token and secret to sign-in into firebase account. In order to retrieve those tokens follow instructions for iOS and Android from Firebase docs.

See

Parameters

Name Type Description
token string Twitter's token string
secret string Twitter's secret string

Returns

Promise<void>

Callback when operation is completed


signInWithVerificationId

signInWithVerificationId(verificationId, code): Promise<void>

Completes phone number verification process and use it to sign in.

Example

cordova.plugins.firebase.auth.verifyPhoneNumber("+123456789").then(function(verificationId) {
    var code = prompt("Enter verification code");
    if (code) {
        return cordova.plugins.firebase.auth.signInWithVerificationId(verificationId, code);
    }
}).catch(function(err) {
    console.error("Phone number verification failed", err);
});

Parameters

Name Type Description
verificationId string [description]
code string 6-digit SMS code

Returns

Promise<void>

Callback when operation is completed


signOut

signOut(): Promise<void>

Signs out the current user and clears it from the disk cache.

Example

cordova.plugins.firebase.auth.signOut();

Returns

Promise<void>

Callback when operation is completed


updateProfile

updateProfile(profileDetails): Promise<void>

Updates the current user's profile data. Passing a null value will delete the current attribute's value, but not passing a property won't change the current attribute's value.

Example

cordova.plugins.firebase.auth.updateProfile({
    displayName: "Jane Q. User",
    photoURL: "https://example.com/jane-q-user/profile.jpg",
});

Parameters

Name Type Description
profileDetails Object User attributes.
profileDetails.displayName string -
profileDetails.photoURL string -

Returns

Promise<void>

Callback when operation is completed


useAppLanguage

useAppLanguage(): Promise<void>

Sets languageCode to the app’s current language.

Example

cordova.plugins.firebase.auth.useAppLanguage();

Returns

Promise<void>

Callback when operation is completed


useEmulator

useEmulator(host, port): Promise<void>

Sets languageCode to the app’s current language.

Example

cordova.plugins.firebase.auth.useEmulator('localhost', 8000);

Parameters

Name Type Description
host string Emulator host name
port number Emulator port

Returns

Promise<void>

Callback when operation is completed


verifyPhoneNumber

verifyPhoneNumber(phoneNumber, timeoutMillis?): Promise<string>

Starts the phone number verification process for the given phone number.

Android supports auto-verify and instant device verification. You must register onAuthStateChanged to get callback on instant verification.

Maximum allowed value for timeout is 2 minutes. Use 0 to disable SMS-auto-retrieval. If you specify a positive value less than 30 seconds, library will default to 30 seconds.

Parameters

Name Type Description
phoneNumber string Phone number in international format
timeoutMillis? number Maximum amount of time you are willing to wait for SMS auto-retrieval to be completed by the library.

Returns

Promise<string>

Fulfills promise with verificationId to use later for signing in

cordova-plugin-firebase-authentication's People

Contributors

andreszs avatar cairin avatar chemerisuk avatar douglaszaltron avatar ebhsgit avatar javierpaytef avatar mariuszgola 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-firebase-authentication's Issues

SMS message APP_CODE overwritten

Hi,
In firebase console, the template is %LOGIN_CODE% is your verification code for %APP_NAME%.
After I use the plugin in my android application, the sms received became
"123456 is your verification code for Payments".
I have checked multiple times that I did not include any definitions/naming as Payments in my app.
Is this something defined in the plugin itself? If yes, may I be able to change it somewhere?

Btw, although it seems to be working fine to call verifyPhoneNumber again for resending sms, there are something like force Resending Token in the official doc and another overload method to take it for resending. Hope to have the function in the future :) Thanks so much :)

Question: pass java "credential" back to js

Hi,

this might be a weird question, but I need to know if there is any chance to pass
https://github.com/chemerisuk/cordova-plugin-firebase-authentication/blob/master/src/android/FirebaseAuthenticationPlugin.java#L227

"credential" back to the app? It's not a problem for me to implement a pluginResult, I already tried that, but passing back "credential" isn't any JSON object or something, its something like "com.google.firebnase...@xxxx".

Some JavaInstance or Object I guess. You might ask why I would ever need that: simple; due to Instantverifications and Auto-retrival, my app has a unhandled case (I did not use your plugin, I used a mix from other plugins) and build a credential with the JS-SDK. But this requires a "verificationId", which won't be passed back, as "onCodeSent" won't trigger if there was any instant-verification or auto-retrieval. "credential" only has getProvider() and getSmsCode() - which is useless for me, as getSmsCode can also be null.

I just want to know if you have any idea how to get a working "credential" (maybe as string) so I can just

        // generate credential object with ID from last page and newly entered code
        var credential = firebase.auth.PhoneAuthProvider.credential(
            params.verificationId,
            $scope.code
        );

or REPLACE the "credential" which I have to pass for the JS-SDK. Maybe there is an internal API which still can deliver the verificationId even on instant/auto-retrieval?)

Im not a native speaker, I hope I could make myself clear enough.
Currently, my app relies on the js-sdk, I don't have any chance to change my code to 100% incorporate your awesome plugin (as I also do need to upload images and using store-functions, which requires a js-auth)

Would love to donate some $ if you can help me on this.

Can't sign in with firebase / GoogleAuthProvider

I've followed the instructions from https://firebase.google.com/docs/auth/web/cordova and I'm having the next issue:

After the this.afAuth.auth.signInWithRedirect(provider) the app redirect to google chrome to the firebase service from google. Then the service return back to a http://localhost:8080/login which is denied by my app with a ERR_CONNECTION_REFUSED.

This is my angular component:

`import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { auth } from 'firebase/app';

@component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

username: string ="";
password: string ="";
kk: string = "";
constructor(public afAuth: AngularFireAuth) { }

ngOnInit() {
this.kk = "hola";
}

async login() {
const {username, password} = this;
try {
const res = await this.afAuth.auth.signInWithEmailAndPassword(username + '@codedamn.com', password)
} catch(err) {
console.dir(err)
if (err.code === "auth/user-not-found") {
console.log("User not found");
}
}
}

async login2() {
var provider = new auth.GoogleAuthProvider();
await this.afAuth.auth.signInWithRedirect(provider).then(function() {
return this.afAuth.auth.auth().getRedirectResult();
}).then(function(result) {
// This gives you a Google Access Token.
// You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});

}

}`

Firebase configure xcode runtime error

Error:
The default FIRApp instance must be configured before the default FIRAuthinstance can be initialized. One way to ensure that is to call [FIRApp configure]; (`FirebaseApp.configure()

How to do that?

Error in getIdToken

Hi , when I use cordova.plugins.firebase.auth.getIdToken().then(function(id){}) method "Uncaught (in promise) JSON error" this error returned.
how can I resolve it?

Android 4: Promise is not defined

The plugin does not work at all on Android 4.x because it relies on the new ES6 promise model:

promise

Please be aware that even when Google or Apache Cordova deprecates Android 4.x and 5.x there are still millions of devices out there using them, and there will be for a long time, specially in developing countries.

I think that plugins should stay as backwards compatible as possible, instead of relying on new methods, which should be used only when there is absolutely no alternative. Callbacks may take longer to develop but they just work.

Promises are completely unnecessary in this plugin and should be avoided like the plague if you want to develop an useful, reliable and popular plugin, otherwise why bother uploading it? The same goes for the CLI 7.1.0 requirement just because Gradle does not understand the FIREBASE_AUTH_VERSION parameter, another irrelevant feature that breaks the plugin.

If you agree, I'll create a PR to get rid of all promises and implement regular callbacks, otherwise I'll start my own Android 4 compatible branch, damaging the plugins ecosystem which is already quite messed up. Regards,
Andres.-

iOS compile error -FIRBundleUtil error

Hello,
Getting iOS compile error after installing the plugin

FIRBundleUtil.m:17:9: fatal error:
'GoogleUtilities/GULAppEnvironmentUtil.h' file not found
#import <GoogleUtilities/GULAppEnvironmentUtil.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Merge into the "main firebase repo"

Hi @chemerisuk

looks like you're the first one who really implemented the native way of authentication. Sadly, this repo lacks of all the other firebase features - probably for a reason. But would you consider to add your awesome verification stuff to https://github.com/arnesson/cordova-plugin-firebase ?

This would be something awesome, as the other menitoned repo has a very hacky workaround for the verification process (and it only supports the phone-verification in combination with the js api and it also does not cover instant-verification).

Im not sure if I should mix both libs.. feels dirty and might lead into issues with firebase versions..

Revert to cordova-android 6.3.0

Asking for cordova-android 7 creates several problems like a total incompatibility with Android 4, and failure to develop and deploy with Visual Studio. Creating PR to revert it to 6.3.0, it works perfectly fine with CLI 7.1.0 and on Android 4 using the polyfill for your Promise methods.

After adding the plugin, it fails and does not build anymore

image

My package.json

    "cordova-android": "7.1.4",
    "cordova-android-support-gradle-release": "^2.0.1",
    "cordova-ios": "4.4.0",
    "cordova-plugin-app-event": "^1.2.1",
    "cordova-plugin-camera": "^4.0.3",
    "cordova-plugin-compat": "^1.2.0",
    "cordova-plugin-console": "^1.1.0",
    "cordova-plugin-crosswalk-webview": "^2.4.0",
    "cordova-plugin-customurlscheme": "^4.3.0",
    "cordova-plugin-device": "^2.0.2",
    "cordova-plugin-dialogs": "^2.0.1",
    "cordova-plugin-file": "^6.0.1",
    "cordova-plugin-file-transfer": "^1.7.1",
    "cordova-plugin-firebase-authentication": "^1.0.1",
    "cordova-plugin-google-analytics": "^1.8.6",
    "cordova-plugin-image-picker": "^1.1.3",
    "cordova-plugin-inappbrowser": "^3.0.0",
    "cordova-plugin-network-information": "^2.0.1",
    "cordova-plugin-splashscreen": "^5.0.2",
    "cordova-plugin-statusbar": "^2.4.2",
    "cordova-plugin-velda-devicefeedback": "0.0.2",
    "cordova-plugin-video-editor": "^1.1.3",
    "cordova-plugin-whitelist": "^1.3.3",
    "cordova-support-android-plugin": "^1.0.1",
    "cordova-support-google-services": "^1.2.1",
    "de.appplant.cordova.plugin.local-notification": "^0.8.5"

Cordova -v: 8.0.0

property verifyPhoneNumber does not exist on type 'typeof auth'

How to use the methods, for example verifyPhoneNumber
cordova.plugins.firebase.auth.verifyPhoneNumber("+123456789").then(function(verificationId) { // pass verificationId to signInWithVerificationId });Here I get the error Cannot find name 'cordova'.

So I used this as

firebase.auth.verifyPhoneNumber("+123456789").then(function(verificationId) { // pass verificationId to signInWithVerificationId }); added import as import * as firebase from 'firebase';.

But I am getting the error :
property verifyPhoneNumber does not exist on type 'typeof auth'.

I am very new to ionic, What am I doing wrong here.

Error code 65 for command xcodebuild after adding the plugin

I've followed the advice from this related issue without success to solve this error:

The following build commands failed:
	CompileC /Users/andres/Library/Developer/Xcode/DerivedData/myapp-fzzedyqaehwzihfmlblyztcnfzqu/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FirebaseCore.build/Objects-normal/x86_64/FIRNetwork.o FirebaseCore/Firebase/Core/FIRNetwork.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/Users/andres/Documents/cordova/myapp/platforms/ios/cordova/build-debug.xcconfig,-workspace,myapp.xcworkspace,-scheme,myapp,-configuration,Debug,-sdk,iphonesimulator,-destination,platform=iOS Simulator,name=iPhone X,build,CONFIGURATION_BUILD_DIR=/Users/andres/Documents/cordova/myapp/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/andres/Documents/cordova/myapp/platforms/ios/build/sharedpch

Steps to reproduce please tell me if I missed something

  • Create blank app (cordova 7.1.0)
  • Add platform ios (4.5.4)
  • Open .xcworkspace in Xcode to:
    • Select my Signing team
    • Add the URL Scheme at the Info tab for my target
    • Enable Push Notifications capability
  • Add the plugin
  • Add <resource-file src="GoogleService-Info.plist" /> to config.xml
  • Run pod update and pod install in the platforms/ios folder
  • cordova build ios will now inevitably fail

The app can be built and deployed from Xcode only (making it impossible to use cordova now), and the plugin does work, with these warnings:

2018-06-23 20:48:51.901313-0300 myapp[1131:651997] Starting Firebase Authentication plugin
2018-06-23 20:48:51.906258-0300 myapp[1131:652210] 5.3.0 - [Firebase/Core][I-COR000003] The default Firebase app has not yet been configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your application initialization. Read more: https://goo.gl/ctyzm8.
2018-06-23 20:48:51.918088-0300 myapp[1131:652210] 5.3.0 - [Firebase/Core][I-COR000022] Firebase Analytics is not available

How can we fix the cordova build ios error 65 now?
Why does the plugin require firebase analytics?
Wasn't the initialization error fixed here?

The sms code has expired. Please re-send the verifiction code to try again.

Hi there,
When I called cordova.plugins.firebase.auth.verifyPhoneNumber("+91**********", 60000, function (verificationId) {}

and passed verificationId(received from above code) and verificationCode(received through sms) to
cordova.plugins.firebase.auth.signInWithVerificationId(verificationId, verificationCode, function (userInfo) {},
function (error) {alert(error);});

but I always received "The sms code has expired. Please re-send the verification code to try again."

So please let me know how could I do it.

question using firestore

Hi.
Im already login and have my firebase uid, when try tu use firestore (firebase-firestore.js) i cant, because dont detect my uid... are you know some way to solve?

when i use:
cordova.plugins.firebase.auth.onAuthStateChanged bring me back the user info.
but when i use:
firebase.auth().onAuthStateChanged the result is null.

if in firesotre modify the rule to allow all, work fine, but when i just allow when are loged in... dont work.

the rule:
allow read, write: if request.auth.uid != null;

VerifyPhoneNumber

When call verifyPhoneNumber from javascript, if phone is auto verified no sms is sent, on native side it seems onVerificationCompleted is called but no callback is passed to javascript side. How to handle this situation?

Ui Implementation

Hi @chemerisuk
thanks for this plugin. Does this plugin implement the native phone-sign-in UI? Or do we have to handle this ourselves? Thanks in advance!

How to write firebase database rules with this plugin

Hello,
thanks for the great plugins,

I used "signInWithVerificationId()" in my ionic Application. Every thing is working great. But i am not able to use Firebase database rules with this plugin. Below are my codes. Please help to implement database rules.

I used https://ionicframework.com/docs/v3/native/firebase-authentication/ to authenticate users
and https://www.npmjs.com/package/firebase to access firebase data.

Function to send OTP

send(){ this.firebaseAuthentication.verifyPhoneNumber(this.mobile,60).then((data)=>{ console.log(data) this.verificationId = data; alert('OTP SENT'); },error=>{ console.log(error) }) }

Code to login

verify(){ this.firebaseAuthentication.signInWithVerificationId(this.verificationId, this.code).then((verified)=>{ if(verified=='OK'){ console.log('user loggedin successfully') } },error=>{ console.log(error) }) }

Code to fetch data

this.firebaseAuthentication.onAuthStateChanged().subscribe((user)=>{ if(user){ console.log(user); firebase.database().ref('dummydata').on('value',snapshot=>{ console.log('data ',snapshot.val()) },error=>{ console.log('error ',error) }) }

Database rule

{ "rules": { "dummydata":{ ".read": "auth!=null", ".write": "auth!=null" } } }

Get emailVerified.

hi,
i have a cordova project in JS.
I can read userinfo properties but not user properties. I need lock authentication if email is not verified: how can i do?
Thanks.

signInWithVerificationId does not work properly

Hello,

I am trying to sign in with SMS on my project. My code with comments is following.

`function SendSMS(){
var phoneNumber=String(document.getElementById("inputPhoneNumber").value);

cordova.plugins.firebase.auth.verifyPhoneNumber(phoneNumber).then(function(verificationId) {
SMS_code = prompt("Please enter the code: ", ""); //this async function waits until user gives an input

alert("SMS_code: "+SMS_code+"\n verificationId: "+verificationId);       // I can see both code and verification ID 
cordova.plugins.firebase.auth.signInWithVerificationId(verificationId, SMS_code).then(
         user => {
            alert("user: "+user+"\n user.uid: "+user.uid);	  // user: [object Object] and user.uid: xyz... this line also works fine!	 					
								NameListRef="CompleteNameList";
								firebase.database().ref(NameListRef).once('value').then( function(snapshot){
								NameList=snapshot.val(); 
								alert("NameList: " +NameList);
								},
								function(error){
								alert("error: " +error); //Error: permission_denied. client does not have permission to access the desired data. 
								});					
				}, error=>{
					alert("error: "+error);
				});	

});
}`

The only rule for my database is authentication. After this point, I have checked whether I am signed in. I have added a listener and a function (fired by a button).

`cordova.plugins.firebase.auth.onAuthStateChanged(function(userInfo) {
if (userInfo && userInfo.uid) {
alert("user signed in"); // THIS ALERT NEVER FIRES
} else {
alert("user signed out");
}
});

function checkUser(){ // called by button
currentUserUID= firebase.auth().user;
alert("currentUserUID: " +currentUserUID); //UNDEFINED
}`

PS: I have added the correct package name and SHA-1 in the Firebase Console
PS2: I can see that new user is created at Firebase console and "last sign in time" is updated.

Thanks...

Handle incoming SMS auto verification in android

Hi,

First of all, thanks for this plugin. I have implemented this plugin in my Ionic Project for a while.

In Android, I was facing an issue that I occasionally get a message "The SMS code has expired" after I have entered SMS OTPcode and hit verify button. At that time I have already the verification code and everything else to proceed. It turns out the plugin has skipped one callback to handle incoming SMS auto verification. Please check this Auto-retrieval

If SMS auto retrieval is implemented, it will trigger action in onVerificationCompleted automatically. So when SMS arrives and user try to enter SMS OTP code to proceed with cordova.plugins.firebase.auth.signInWithVerificationId, at that time the error message will be shown that SMS code has expired. In fact verification has already been done when SMS has arrived.

Therefore I modified the source code (android) to handle this situation. I added a new function waitForSMSVerificationResult to register the callback to onVerificationCompleted. General code will be as below.

// after user wants to get OTP code
cordova.plugins.firebase.auth.waitForSMSVerificationResult(function(userInfo){
    // get user info after sign in successfully
    console.log(userInfo)
    // perform action after user sign in
});

cordova.plugins.firebase.auth.verifyPhoneNumber(phone, 0, function(verificationId) {
   if(verificationId) {
     // store verification somewhere else 
   }
});

// after user enters SMS OTP code
cordova.plugins.firebase.auth.signInWithVerificationId(verificationId, SMScode);

Above is just temporary modification, hope you can restructure the code for handling SMS auto-retrieval situation.

For IOS I didn't get any trouble on this. It always prompts user to enter SMS OTP code to proceed with phone verification, no instant or SMS autoretrieval verification.

Again thanks for this plugin.

Error installing the plugin

Hello,
Getting error installing the plugin...

Please let me know how to resolve

Thanks

cordova plugin add cordova-plugin-firebase-authentication --save
Installing "cordova-plugin-firebase-authentication" for android
Plugin dependency "[email protected]" already fetched, using that version.
Installing "cordova-support-android-plugin" for android
Android Studio project detected
Plugin dependency "[email protected]" already fetched, using that version.
Installing "cordova-support-google-services" for android
Subproject Path: CordovaLib
Subproject Path: app
Subproject Path: CordovaLib
Subproject Path: app
Installing "cordova-plugin-firebase-authentication" for browser
Installing "cordova-plugin-firebase-authentication" for ios
Failed to install 'cordova-plugin-firebase-authentication': Error: pod: Command failed with exit code 31
at ChildProcess.whenDone (/Users/Documents/testing/fb/MobileV2/platforms/ios/cordova/node_modules/cordova-common/src/superspawn.js:169:23)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
pod: Command failed with exit code 31

Error with signInWithVerificationId parameter mismatch

I am getting an error sending the verificationId and SMSCode:

by.chemerisuk.cordova.firebase.FirebaseAuthenticationPlugin.signInWithVerificationId argument 2 has type java.lang.String, got java.lang.Integer

this.firebaseAuthentication.signInWithVerificationId(this.verificationId, Number(code)) expects a number in the code parameter, but actually expects a string parameter.

Package json:

"cordova-plugin-firebase": "2.0.5",
"cordova-plugin-firebase-authentication": "1.0.1",

Cordova plugins:

"cordova-plugin-firebase": {},
"cordova-plugin-firebase-authentication": {
   "FIREBASE_AUTH_VERSION": "16.1.0"
}

build errors on Android and on iOS

The cordova plugin was aded without errors (cocoapods was installed and setup during the process). However the following errors occur when trying to build an app:

Android:
Could not get unknown property 'FIREBASE_VERSION' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

iOS:
ld: warning: directory not found for option ‘-L/Users/…/Debug-iphoneos/GTMSessionFetcher’
ld: warning: directory not found for option ‘-L/Users/…/Debug-iphoneos/GoogleToolboxForMac’
ld: warning: directory not found for option ‘-L/Users/…/Debug-iphoneos/nanopb’
ld: library not found for -lGTMSessionFetcher
clang: error: linker command failed with exit code 1 (use -v to see invocation)

how to get the idToken and accessToken for Google sign-in?

trying to implement the plugin for google sign in. Your text refers to the Firebase docs but they dont seem to refer to such tokens. The reference to android doc only mentions a server token and the reference to iOS doc mention other things (twitter stuff). Can you please provide more specific instructions for the tokens needed for Google sign in?

Thanks!
Z.

Auth state problem

I've used phone authentication . when I use auth state fun provided by firebase sdk , it doesn't observe
any change to users state . How could I solve this ?

Cordova 7.1.0: local variable callbackContext is accessed from within inner class; needs to be declared final

Cordova 7.1.0 with cordova-android 6.3.0 fails to build errors such as this:

1>MSBUILD : cordova-build error : D:\Cordova\FirebaseCLI710\platforms\android\src\by\chemerisuk\cordova\firebase\FirebaseAuthenticationPlugin.java:61: error: local variable callbackContext is accessed from within inner class; needs to be declared final
1>  D:\Cordova\FirebaseCLI710\platforms\android\src\by\chemerisuk\cordova\firebase\FirebaseAuthenticationPlugin.java:61: error: local variable callbackContext is accessed from within inner class; needs to be declared final
[...]

I've fixed these errors by adding the final keyword before all CallbackContext callbackContext function's arguments, and a pull request has been created for this.

error with firebase-analytics dependency version

Hi @chemerisuk, i tried to install cordova-plugin-firebase-authentication but got this error:


Installing "cordova-plugin-firebase-authentication" for ios
        Failed to install 'cordova-plugin-firebase-authentication': Error
             at /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:581:33
             at _fulfilled (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:787:54)
             at self.promiseDispatch.done (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:816:30)
             at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:749:13)
             at /usr/local/lib/node_modules/cordova/node_modules/q/q.js:509:49
             at flush (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:108:17)
             at _combinedTickCallback (internal/process/next_tick.js:131:7)
             at process._tickCallback (internal/process/next_tick.js:180:9)
        Error: Version of installed plugin: "[email protected]" does not satisfy dependency
        plugin requirement "cordova-plugin-firebase-analytics@~0.10.0". Try --force to use installed plugin as
        dependency.

Subtle Incompatibility between cordova-plugin-firebase-auth and cordova-plugin-firebase

Hi there,

It seems like perhaps there may be an incompatibility between cordova-plugin-firebase-auth and cordova-plugin-firebase. When running either of these two plugins independently, there is no issue in compile, but when these two are used in conjunction, I always seem to get the following errors:

/Users/jcrombie/Application_Building/SellMeToys/platforms/ios/SellMeToys/Plugins/cordova-plugin-firebase-authentication/FirebaseAuthenticationPlugin.m:41:41: Incompatible block pointer types sending 'void (^)(FIRAuthDataResult *__strong, NSError *__strong)' to parameter of type 'FIRAuthResultCallback _Nullable' (aka 'void (^)(FIRUser * _Nullable __strong, NSError * _Nullable __strong)')

/Users/jcrombie/Application_Building/SellMeToys/platforms/ios/SellMeToys/Plugins/cordova-plugin-firebase-authentication/FirebaseAuthenticationPlugin.m:88:37: Incompatible block pointer types sending 'void (^)(FIRAuthDataResult *__strong, NSError *__strong)' to parameter of type 'FIRAuthResultCallback _Nullable' (aka 'void (^)(FIRUser * _Nullable __strong, NSError * _Nullable __strong)')

/Users/jcrombie/Application_Building/SellMeToys/platforms/ios/SellMeToys/Plugins/cordova-plugin-firebase-authentication/FirebaseAuthenticationPlugin.m:95:53: Incompatible block pointer types sending 'void (^)(FIRAuthDataResult *__strong, NSError *__strong)' to parameter of type 'FIRAuthResultCallback _Nullable' (aka 'void (^)(FIRUser * _Nullable __strong, NSError * _Nullable __strong)')

Plugin List:

macbook34:ios$ cordova plugins
cordova-plugin-browsertab 0.2.0 "cordova-plugin-browsertab"
cordova-plugin-buildinfo 2.0.1 "BuildInfo"
cordova-plugin-compat 1.2.0 "Compat"
cordova-plugin-customurlscheme 4.3.0 "Custom URL scheme"
cordova-plugin-firebase 1.0.5 "Google Firebase Plugin"
cordova-plugin-firebase-authentication 1.0.1 "cordova-plugin-firebase-authentication"
cordova-plugin-firebase-dynamiclinks 1.0.0 "FirebaseDynamicLinksPlugin"
cordova-plugin-inappbrowser 3.0.0 "InAppBrowser"
cordova-plugin-whitelist 1.3.3 "Whitelist"
cordova-universal-links-plugin 1.2.1 "Universal Links Plugin"

I have tried adding one first, then the other (both ways)...clean/cleanBuildFolder, and clearing derived data...

Each works splendidly on their own, but together...not so much (at least for me)

Here is the pods in use here

macbook34:ios jcrombie$ cat Podfile.lock
PODS:

  • Firebase/Auth (5.4.0):
    • Firebase/CoreOnly
    • FirebaseAuth (= 5.0.2)
  • Firebase/Core (5.4.0):
    • Firebase/CoreOnly
    • FirebaseAnalytics (= 5.0.1)
  • Firebase/CoreOnly (5.4.0):
    • FirebaseCore (= 5.0.5)
  • FirebaseAnalytics (5.0.1):
    • FirebaseCore (~> 5.0)
    • FirebaseInstanceID (~> 3.0)
    • "GoogleToolboxForMac/NSData+zlib (~> 2.1)"
    • nanopb (~> 0.3)
  • FirebaseAuth (5.0.2):
    • FirebaseCore (~> 5.0)
    • GTMSessionFetcher/Core (~> 1.1)
  • FirebaseCore (5.0.5):
    • "GoogleToolboxForMac/NSData+zlib (~> 2.1)"
  • FirebaseInstanceID (3.1.1):
    • FirebaseCore (~> 5.0)
  • GoogleToolboxForMac/Defines (2.1.4)
  • "GoogleToolboxForMac/NSData+zlib (2.1.4)":
    • GoogleToolboxForMac/Defines (= 2.1.4)
  • GTMSessionFetcher/Core (1.1.15)
  • nanopb (0.3.8):
    • nanopb/decode (= 0.3.8)
    • nanopb/encode (= 0.3.8)
  • nanopb/decode (0.3.8)
  • nanopb/encode (0.3.8)

DEPENDENCIES:

  • Firebase/Auth (~> 5.0)
  • Firebase/Core

SPEC REPOS:
https://github.com/cocoapods/specs.git:
- Firebase
- FirebaseAnalytics
- FirebaseAuth
- FirebaseCore
- FirebaseInstanceID
- GoogleToolboxForMac
- GTMSessionFetcher
- nanopb

SPEC CHECKSUMS:
Firebase: d66f4f29c23f22d96808d9abc174d81d8eee968f
FirebaseAnalytics: b3628aea54c50464c32c393fb2ea032566e7ecc2
FirebaseAuth: 096e457cdd4274412a66c4a35874787e411f5a03
FirebaseCore: 42b3267233bd21a5abd54117ccc38ca3dd0f8e83
FirebaseInstanceID: f3f0657372592ecdfdfe2cac604a5a75758376a6
GoogleToolboxForMac: 91c824d21e85b31c2aae9bb011c5027c9b4e738f
GTMSessionFetcher: 5fa5b80fd20e439ef5f545fb2cb3ca6c6714caa2
nanopb: 5601e6bca2dbf1ed831b519092ec110f66982ca3

PODFILE CHECKSUM: 98899dd330043c312eb531d66cfc5c9813310161

COCOAPODS: 1.5.3

I noted that some flutter users were also having this issue here:

https://stackoverflow.com/questions/50251316/xcode-build-error-for-flutter-with-firebase-auth-plugin-on-beta-0-3-2-incompat

However, the prescribed fix of just running a pod repo update didnt seem to work....

If you have any suggestions?

Ionic 3

Can I use This plugin in my Ionic App Please Help

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.