Alex
Alex

Reputation: 921

Firebase create user with email, password, display name and photo url

According to Firebase site, I am using this code to create a new user:

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

How can I add display name and photo url to Auth when creating the new user?

This link shows the supported user data returned from an identity provider in Auth.

Upvotes: 23

Views: 33998

Answers (6)

Antonio Ooi
Antonio Ooi

Reputation: 1828

You can use the Firebase Admin SDK in Firebase Function exactly for your purpose, i.e. to fill up other user properties as the user is created:

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

// Put this code block in your Firebase Function:
admin.auth().createUser({
        email: email,
        emailVerified: false,
        password: password,
        displayName: `${fname} ${lname}`,
        disabled: false
    })

But creating user with Firebase Admin SDK may give you problem in sending email verification because the promise does not return the User object that has the sendEmailVerification() method. You may eventually need to use the Firebase client API (as shown in your own code) to create the user and update the user profile before sending the email verification:

var user = firebase.auth().currentUser;

user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
  // Update successful.
}).catch(function(error) {
  // An error happened.
});

It make sense to update the displayName before sending email verification so that the Firebase email template will greet the new user with proper name rather than just Hello (sounds like a spam) when the displayName is not set.

Upvotes: 0

Modesto Cabrera
Modesto Cabrera

Reputation: 539

I think this should solve it for you, let me know if you need anything else. or have any further questions on this matter.

    func handleSignUp() {
    guard let userName = userNameTF.text else { return }
    guard let email = emailTF.text else { return }
    guard let password = passwordTF.text else { return }
    guard let image = profileImage.image else { return }

    continueButton.setBackgroundImage(#imageLiteral(resourceName: "inactiveButtonBG"), for: .normal)
    activityIndicator.startAnimating()

        Auth.auth().createUser(withEmail: email, password: password) { user, error in
            if error == nil && user != nil {
                print("User created!")
                self.uploadProfileImage(image: image) { url in

                    if url != nil {
                        let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
                        changeRequest?.displayName = userName
                        changeRequest?.photoURL = url

                        changeRequest?.commitChanges { error in
                            if error == nil {
                                self.saveProfile(username: userName, profileImageURL: url!) { success in
                                    if success {
                                        print("Success upload of profile image")
                                        self.dismiss(animated: true, completion: nil)
                                    }
                                }
                                self.dismiss(animated: true, completion: nil)
                            } else {
                                guard let message = error?.localizedDescription else { return }
                                self.userAlert(message: message)
                            }
                        }
                    } else {
                        self.userAlert(message: "Unable to load profile image to Firebase Storage.")
                    }
                }

                self.dismiss(animated: true, completion: nil)
            } else {
                guard let message = error?.localizedDescription else { return }
                self.userAlert(message: message)
            }
        }

}

Upvotes: 5

Cyril
Cyril

Reputation: 2818

To change/add the display name:

user!.createProfileChangeRequest().displayName = "Your name"

To change/add photoURL

user!.createProfileChangeRequest().photoURL = URL(string: "image url")

Upvotes: 1

kelsheikh
kelsheikh

Reputation: 1338

I think you mean adding display name and photo url to Firebase Database after Auth. This is pretty much what I do all on same registration.

   if let email = emailField.text where email != "", let pwd = passwordField.text where pwd != ""{

        FIRAuth.auth()?.createUserWithEmail(email, password: pwd, completion: { (user, error) in
            if error != nil {
                print("DEVELOPER: Unable to authenticate with Firebase using email")
            }else {
                print("DEVELOPER: Successfully authenticated with Firebase using email")
                if let user = user {
                    let userData = ["provider": user.providerID, "userName": "\(user.displayName)", "profileImg": "\(user.photoURL)"]
                    self.completeMySignIn(user.uid, userData: userData)
                }
            }
        })

     } else {
       // Email and Password where not filled in
    }
}

Now adding your profile image and users username in DB here

func completeMySignIn(id: String, userData: Dictionary<String, String>){
    {YourFirebaseUserURL}.updateChildValues(userData)
}

Upvotes: 0

Hitesh Surani
Hitesh Surani

Reputation: 13557

Simply you can solve your problem as follow.

1) Create a user using following statement.

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

2) success of above statement Please authenticate this user as follow.

     self.rootRef.authUser(email, password)
 // USER_ID = Here you get user_ID

3) Success of above function set user name and profile picture to user as follow.

  usersRef.updateChildValues(dict, withCompletionBlock:

-Here userRef contain your userDetails/USER_ID

Might be work for you. i have code but work for older firebase version so not work for you otherwise i had share with you.

Upvotes: 0

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

You can update your profile with FIRUserProfileChangeRequest class .. check this Doc.

let user = FIRAuth.auth()?.currentUser
   if let user = user {
      let changeRequest = user.profileChangeRequest()

      changeRequest.displayName = "Jane Q. User"
      changeRequest.photoURL =
          NSURL(string: "https://example.com/jane-q-user/profile.jpg")
      changeRequest.commitChangesWithCompletion { error in
        if let error = error {
          // An error happened.
        } else {
          // Profile updated.
        }
      }
    }

Upvotes: 32

Related Questions