最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Firebase reauthenticateAndRetrieveDataWithCredential problems - Stack Overflow

programmeradmin0浏览0评论

Method reauthenticateAndRetrieveDataWithCredential requires credential.

I tried this and it gives me an error:

const user = firebase.auth().currentUser;
const credential = firebase.auth.OAuthCredential;
await user.reauthenticateAndRetrieveDataWithCredential(credential);
await user.updateEmail(email);
return email;

Error message

reauthenticateAndRetrieveDataWithCredential failed: First argument "credential" must be a valid credential.

I only have oath authentication (no email + password). So I can't figure out what credential firebase need. Any help?

Edit: For some reason my firebase.auth.OAuthCredential or (firebase.auth.AuthCredential) return undefined. User is signedIn/authed.

Method reauthenticateAndRetrieveDataWithCredential requires credential.

I tried this and it gives me an error:

const user = firebase.auth().currentUser;
const credential = firebase.auth.OAuthCredential;
await user.reauthenticateAndRetrieveDataWithCredential(credential);
await user.updateEmail(email);
return email;

Error message

reauthenticateAndRetrieveDataWithCredential failed: First argument "credential" must be a valid credential.

I only have oath authentication (no email + password). So I can't figure out what credential firebase need. Any help?

Edit: For some reason my firebase.auth.OAuthCredential or (firebase.auth.AuthCredential) return undefined. User is signedIn/authed.

Share Improve this question edited Aug 7, 2018 at 13:26 Frank van Puffelen 601k85 gold badges890 silver badges860 bronze badges asked Aug 7, 2018 at 8:45 nl pkrnl pkr 6561 gold badge12 silver badges21 bronze badges 3
  • Can you try it with the accessToken property of the credential? – André Kool Commented Aug 7, 2018 at 8:53
  • For some reason my firebase.auth.OAuthCredential or (firebase.auth.AuthCredential) return undefined. User is authed – nl pkr Commented Aug 7, 2018 at 9:36
  • That sounds like very useful information to include in your question. Unfortunatly I won't be able to help you any further :( – André Kool Commented Aug 7, 2018 at 9:37
Add a ment  | 

3 Answers 3

Reset to default 5

Ran into this issue in a Vue.js project where we have a firebase.js file that handles module imports and exports of const.

Hoping this will help someone save time when using a similar setup.

File: firebase.js

import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/database'


// Initialize Firebase
const app = firebase.initializeApp(options)
export const fb = firebase
export const auth = app.auth()
export const db = app.database()
export const functions = app.functions()

Example of changePassword() in other script file or inside *.vue

import { fb, auth } from './firebase.js'
...
changePassword() {
  if (yourFormValidation == true) {
    let user = auth.currentUser

    const credentials = fb.auth.EmailAuthProvider.credential(
      user.email,
      this.current_password
    )
    user.reauthenticateAndRetrieveDataWithCredential(credentials)
      .then(() => {
        user.updatePassword(this.new_password)
          .then(() => {
            console.log('your password was successfully changed.')
          })
          .catch(error => console.log(error))
      })
      .catch(error => console.log(error.message))
  }
}

Where I was running into Cannot read property 'credential' of undefined"...

Importing only { auth } from './firebase.js and then calling auth.EmailAuthProvider().

How to access other classes found on firebase.auth()...

  1. export const fb = firebase in firebase.js

  2. import { fb, auth } from './firebase.js' where you are writing your function

  3. Call fb.auth.EmailAuthProvider.credential() or other class needed

The documentation for reauthenticating the user shows this example:

var user = firebase.auth().currentUser;
var credential;

// Prompt the user to re-provide their sign-in credentials

user.reauthenticateAndRetrieveDataWithCredential(credential).then(function() {
  // User re-authenticated.
}).catch(function(error) {
  // An error happened.
});

Your code fails to implement the ment correctly. You will need to show a prompt to the user to provide their credentials again, put those into the correct credential object type, and pass that in.

For example:

var credential = firebase.auth.EmailAuthProvider.credential(
    email,
    password
);

You need to use a subscription to watch for the changes. Use AngularFire to watch for when they are logged in and get the UID (assuming you are using the Authentication login in Firebase so that all data is saved using the UID as the tree path.

You can also add a set timeout to unsubscribe them after a given time

   import { AngularFirestore } from 'angularfire2/firestore';
    import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
    import { AngularFireAuth } from 'angularfire2/auth';
    import { switchMap, map } from 'rxjs/operators';
    import { Observable,  pipe } from 'rxjs';
    import { Observable, Subscription } from 'rxjs';
    import firebase as firebase from 'firebase/app';

private myOAuthSubscription: Subscription;
private myDatasubscription: Subscription;    
public userloggedin:boolean = false;
public uid:string = '';
private functionhasrun:boolean = false;

    public this.items:any = [];

    constructor(
      public _DB: AngularFireDatabase,
      public _afAuth: AngularFireAuth,
    ) {

    //check that the user is logged in 
    try {
      this.myOAuthSubscription = this._afAuth.authState.subscribe(user => {

        if (user && user.uid) {

          console.log('loggedin = true');
          this.userloggedin = true;
          this.uid = String(user.uid);

          if(this.functionhasrun==false){

           this.functionhasrun = true;
           this.funDoDB():

          }

        } else {

        console.log('loggedin = false');
        this.userloggedin = true;
        this.uid = '';

        }
      });
    } catch (e) {
      console.error("fbData_subscription", e);
    }



    }

    ngOnDestroy() {
      this.myOAuthSubscription.unsubscribe();
      this.myDatasubscription.unsubscribe();
    }


    private funDoDB(){
          if(this.userloggedin == true){
          try {

        //subscription using AngulaFire
        this.myDatasubscription = this._DB.list('myDataPath/' + this.uid).snapshotChanges().pipe(map(actions => {
            return actions.map(action => ({ key: action.key, val: action.payload.val() }));
          }))
          .subscribe(items => {

            this.items = [];
            this.items = items.map(item => item);

            console.log("db results",this.items);

            var icount=0;

            for (let i in this.items) {

             console.log("key",this.items[i].key);
             console.log("val",this.items[i].val); 
             console.log("----------------------------------);

             //checking if something exists
             if (this.items[i].key == 'SomeNodePath') {
               var log = this.items[i].val;
             }

            }


          } catch (e) {
            console.error(e);
          }


          });
        }
        }

    npm install --save angularfire2 firebase
    npm install -D [email protected] [email protected]
发布评论

评论列表(0)

  1. 暂无评论