updatePhoneNumber failed: First argument "phoneCredential" must be a valid phone credential - firebase

I am trying to updatePhoneNumber and keep getting the following error above. Looking at the docs I was under the impressing this is a method?
Js:
user.updatePhoneNumber({
phoneNumber: "+15618104444",
});
I tried setting this in the updateProfile Method as well and still no luck.
user.updateProfile({
displayName: displayName,
photoURL: photoURL,
phoneNumber: "+15618104444"
});

updatePhoneNumber requires a phone credential since the phone number needs to be verified by SMS.
// 'recaptcha-container' is the ID of an element in the DOM.
var applicationVerifier = new firebase.auth.RecaptchaVerifier(
'recaptcha-container');
var provider = new firebase.auth.PhoneAuthProvider();
provider.verifyPhoneNumber('+16505550101', applicationVerifier)
.then(function(verificationId) {
var verificationCode = window.prompt('Please enter the verification ' +
'code that was sent to your mobile device.');
return firebase.auth.PhoneAuthProvider.credential(verificationId,
verificationCode);
})
.then(function(phoneCredential) {
return user.updatePhoneNumber(phoneCredential);
});

Related

Confused how to customize meteor verification email

How do I get the verification link from the default Meteor method into a custom email method I have that uses sendgrid stmp.
here is the meteor verification method that works well on its own and has the link I want:
sendVerificationLink() {
let userId = Meteor.userId();
if ( userId ) {
return Accounts.sendVerificationEmail( userId );
}
},
Here is my custom method that uses sendgrid, everything works except for I cant figure out how to get the link with the custom token:
'signupEmail' (submission) {
this.unblock();
const link = ''
const message = `welcome ${submission.firstname} `
const text = `welcome ${submission.firstname}. Please verify your
account ${link}`
Email.send({
from: "hi#test.com",
to: submission.email,
subject: message,
text: text,
html: text,
});
}
Just in case anyone is looking for this in the future I found an answer on Meteor forums: https://forums.meteor.com/t/how-to-get-verification-link-for-custom-sent-verification-email/22932/2
Basically I added a token record and saved it in the database. Then used the token with the method: Accounts.urls.verifyEmail which created the link to insert in the email.
Here is my final method:
'signupEmail' (submission) {
this.unblock();
let userId = Meteor.userId();
var tokenRecord = {
token: Random.secret(),
address: submission.email,
when: new Date()};
Meteor.users.update(
{_id: userId},
{$push: {'services.email.verificationTokens': tokenRecord}}
);
const verifyEmailUrl = Accounts.urls.verifyEmail(tokenRecord.token);
const message = `welcome ${submission.firstname} `
const text = `welcome ${submission.firstname}. Please verify your account ${verifyEmailUrl}`
Email.send({
from: "hi#test.com",
to: submission.email,
subject: message,
text: text,
html: text,
});
},

unable to update displayName using firebase.auth().currentUser.updateProfile

I'm using ionic2 + firebase now.
After I createUserWithEmailAndPassword, I tried to update the displayName using firebase.auth().currentUser.updateProfile
However, when I try to log firebase.auth().currentUser.providerData, the displayName is still null.
Anyone can tell me what did I overlook?
Below is my code;
const name = form.value.name //e.g james
var user = firebase.auth().currentUser
console.log('name: '+name) //manage to print "name: james"
user.updateProfile({
displayName: name,
photoURL: ''
}).then(function(){
console.log(JSON.stringify(user.providerData))
//it print "displayName":null
}, function(error){
console.log(error)
});

Firebase user.getToken having stale value after signout

I am following Firebase guide for authentication for the web (https://github.com/firebase/FirebaseUI-Web), it works fine for most of the cases. However, if I log out of my Gmail account it still shows the data of the previously logged in user. The biggest challenge is user.getToken() is getting the old token. Has anyone faced similar issue? What would be the way to resolve it.
Here are the details ( please note it is not full-fledged application, I am exploring the authentication part before using in my web application)
In chrome browser, I log into my Gmail account
Go to my test web application/SPA, on the same browser
I see my details on the page (see the code below)
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var uid = user.uid;
var providerData = user.providerData;
user.getToken().then(function(accessToken) {
document.getElementById('sign-in-status').textContent = 'Signed in';
document.getElementById('sign-in').textContent = 'Sign out';
document.getElementById('account-details').textContent = JSON.stringify({
displayName: displayName,
email: email,
emailVerified: emailVerified,
photoURL: photoURL,
uid: uid,
accessToken: accessToken,
providerData: providerData
}, null, ' ');
});
Now I log out of my Gmail account
Go to test web application/SPA, still seeing the details
Go to chrome debugger and type user.getToken(), not null value is returned.
Ideally, it should be null.
Appreciate any help.
Kind Regards

Firebase v3 updateProfile Method

Firebase v3 Auth offers an updateProfile method that passes displayName and photoURL to Firebase.
My understanding is that these properties are retrieved from 3rd party oAuth providers Google, Facebook, Twitter, or GitHub upon user login. In case of Password based Auth, they are not available or viewable from the Admin console.
Can I store this info for password Auth accounts, and if so can I view/administer this info via the Admin console?
BTW: I know this could be stored in the Realtime Database under a users node/branch but I am asking about storing this info in the Firebase Auth system.
// Updates the user attributes:
user.updateProfile({
displayName: "Jane Q. User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
// Profile updated successfully!
// "Jane Q. User"
var displayName = user.displayName;
// "https://example.com/jane-q-user/profile.jpg"
var photoURL = user.photoURL;
}, function(error) {
// An error happened.
});
// Passing a null value will delete the current attribute's value, but not
// passing a property won't change the current attribute's value:
// Let's say we're using the same user than before, after the update.
user.updateProfile({photoURL: null}).then(function() {
// Profile updated successfully!
// "Jane Q. User", hasn't changed.
var displayName = user.displayName;
// Now, this is null.
var photoURL = user.photoURL;
}, function(error) {
// An error happened.
});
.updateProfile stores the displayName and photoURL properties in the Firebase Auth system. Therefore, there is no need to set/get this stuff under a users node in your Realtime Database.
You will not see these properties in the Firebase v3 Auth Console. It's not viewable that way.
Rolled into one, here how to register a password user:
registerPasswordUser(email,displayName,password,photoURL){
var user = null;
//nullify empty arguments
for (var i = 0; i < arguments.length; i++) {
arguments[i] = arguments[i] ? arguments[i] : null;
}
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function () {
user = firebase.auth().currentUser;
user.sendEmailVerification();
})
.then(function () {
user.updateProfile({
displayName: displayName,
photoURL: photoURL
});
})
.catch(function(error) {
console.log(error.message);
});
console.log('Validation link was sent to ' + email + '.');
}

get UID of recently created user on Firebase

Is there a way to get the UID of a recently created user?
According to createUser() documentation, it doesn't look like it returns anything.
How would one go about obtaining this information so that we can start storing information about the user?
I know a way that could be achieved would be logging in the user upon creation. But I don't want to overwrite my existing session.
var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com');
firebaseRef.createUser({
email : "bobtony#firebase.com",
password : "correcthorsebatterystaple"
}, function(err) {
if (err) {
switch (err.code) {
case 'EMAIL_TAKEN':
// The new user account cannot be created because the email is already in use.
case 'INVALID_EMAIL':
// The specified email is not a valid email.
case default:
}
} else {
// User account created successfully!
}
});
The above answers are for old firebase.
For the ones looking for new firebase implementation :
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function success(userData){
var uid = userData.uid; // The UID of recently created user on firebase
var displayName = userData.displayName;
var email = userData.email;
var emailVerified = userData.emailVerified;
var photoURL = userData.photoURL;
var isAnonymous = userData.isAnonymous;
var providerData = userData.providerData;
}).catch(function failure(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode + " " + errorMessage);
});
Source : Firebase Authentication Documentation
Firebase recently released an updated JavaScript client (v2.0.5) which directly exposes the user id of the newly-created user via the second argument to the completion callback. Check out the changelog at https://www.firebase.com/docs/web/changelog.html and see below for an example:
ref.createUser({
email: '...',
password: '...'
}, function(err, user) {
if (!err) {
console.log('User created with id', user.uid);
}
});
After the user is created you can authenticate him as mentioned right above the code sample on the page that you link to:
Creates a new email / password based account using the credentials specified. After the account is created, users may be authenticated with authWithPassword().
then in the authWithPassword callback, you can access the new user's auhtData. https://www.firebase.com/docs/web/api/firebase/authwithpassword.html
I asked this question on the support forums of firebase and got this answer from Jacob. I hope this helps anyone having the same issue.
Copy and pasted from http://groups.google.com/group/firebase-talk/
All you need to do is just authenticate to a different Firebase context. You can do this via an undocumented context argument when creating a new Firebase object.
// adminRef will be used to authenticate as you admin user (note the "admin" context - also note that this can be ANY string)
var adminRef = new Firebase("https://<your-firebase>.firebaseio.com", "admin");
adminRef.authWithCustomToken("<token>", function(error, authData) {
if (error !== null) {
// now you are "logged in" as an admin user
// Let's create our user using our authenticated admin ref
adminRef.createUser({
email: <email>,
password: <password>
}, function(error) {
if (error !== null) {
// let's create a new Firebase ref with a different context ("createUser" context, although this can be ANY string)
var createUserRef = new Firebase("https://<your-firebase>.firebaseio.com", "createUser");
// and let's use that ref to authenticate and get the uid (note that our other ref will still be authenticated as an admin)
createUserRef.authWithPassword({
email: <email>,
password: <password>
}, function(error, authData) {
if (error !== null) {
// Here is the uid we are looking for
var uid = authData.uid;
}
});
}
});
}
});
Note that we will be releasing a new version of Firebase soon that does return the uid in the createUser() callback. At that point, this somewhat hacky workaround will not be needed.

Resources