简体   繁体   中英

How to register a User in Firebase using Node.js?

PROBLEM:

0) The user is created in the auth system in Firebase (I see it in the Auth tab),

1) But no changes are made to the database.

2) The page seems to be stuck infinitely loading.

3) Only "Started 1..." is logged to the console.


CODE:

router.post('/register', function(req, res, next) {
    var username = req.body.username;
    var email = req.body.email;
    var password = req.body.password;
    var password2 = req.body.password2;

    // Validation
    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('email', 'Email is required').notEmpty();
    req.checkBody('email', 'Email is not valid').isEmail();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors){
        res.render('users/register', {
            errors: errors
        });
    } else {
        console.log("Started 1...");
        firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error, userData) {
            console.log("Started 2...");
            if(error){
                var errorCode = error.code;
                var errorMessage = error.message;
                req.flash('error_msg', 'Registration Failed. Make sure all fields are properly filled.' + error.message);
                res.redirect('/users/register');
                console.log("Error creating user: ", error);
            } else {
                console.log("Successfully created");
                console.log("Successfully created user with uid:", userData.uid);
                var user = {
                    uid: userData.uid,
                    email: email,
                    username: username
                }

                var userRef = firebase.database().ref('users/');
                userRef.push().set(user);

                req.flash('success_msg', 'You are now registered and can login');
                res.redirect('/users/login');
            }

        });
    }
});

EDIT 1:

This is what seems to be happening:

The user is created in the auth System. The page loads for about 5 minutes (very long!), then tells me the registration failed because the email address is already in use (it was not).

It seems the user is created but the registration fails because the code loops back after the user is created as if it had not been created, therefore creating an error of type : this email address is already in our database.

But why does this happen ?

not sure this is all, but here's what i think happens:

the user is created, but you are not handling it properly. there is no handling of a success case (fulfilled promise), only a rejected one. also, when you're trying to write to the database when an error occurs, that means the user is not authenticated, which means that if you haven't changed your firebase security rules, you won't be able to write. (the default firebase security rules prevents non-authenticated users from reading/writing to your database)

this line:

firebase.auth().createUserWithEmailAndPassword(email,password) .catch(function(error, userData) { ...

should be changed to this:

firebase.auth().createUserWithEmailAndPassword(email, password) .then(userData => { // success - do stuff with userData }) .catch(error => { // do stuff with error })

mind that when an error occurs, you won't have access to userData , just the errors.

Hope this helps!

I've recently run into this problem. It seems that some functions, such as createUser() or listUsers() from firebase-admin , when using NodeJS need to have the app initialized using a private key file, that means that you can not use such funtions and initilize your app like this:

const admin = require('firebase-admin');

const config = {
    apiKey: "an_amazing_API_KEY",
    authDomain: "lolthatsfunny.firebaseapp.com",
    databaseURL: "https://lolthatsfunny.firebaseio.com",
    projectId: "lolthatsfunny",
    storageBucket: "lolthatsfunny.appspot.com",
    messagingSenderId: 1212121212
};

admin.initializeApp(config);

Instead, you have to:

  1. Log in the Firebase Console: https://console.firebase.google.com/
  2. Click on the project
  3. Click on "Project Settings"
  4. Click on the "Service Accounts" tab
  5. Click Generate New Private Key, then confirm by clicking Generate Key
  6. Then, in your NodeJS app, initilize your firebase application like this:
const admin = require("firebase-admin");

const serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://cuidatushabitos-cth.firebaseio.com"
});

Now, you will be able to use the previously mentioned functions like createUser() :

admin.auth().createUser({
  email: 'user@example.com',
  emailVerified: false,
  phoneNumber: '+11234567890',
  password: 'secretPassword',
  displayName: 'John Doe',
  photoURL: 'http://www.example.com/12345678/photo.png',
  disabled: false
})
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully created new user:', userRecord.uid);
  })
  .catch(function(error) {
    console.log('Error creating new user:', error);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM