How do I update currentUser after Accounts.createUser() and Accounts.loginWithPassword()? - meteor

I am trying to create my own UI for signing up/logging in users:
'submit .signin': function(event){
var user = {'email':event.target.email.value, 'password' :event.target.password.value}
Accounts.createUser(user, function(err) {
if (err){
console.log(err);
} else
console.log('success!');
});
Meteor.loginWithPassword(user['email'], user['password'], function(error){
if(error){
console.log(error)
}
else{
console.log('success')
}
});
}
My question is once this code logs in the user, how do I set the currentUser the way loginButtons automatically does after you sign in. Thanks!

You don't have to call login after user is created.
To modify user data you can use http://docs.meteor.com/#/full/accounts_oncreateuser
See examples here: https://github.com/juliancwirko/meteor-s-id

Related

Firebase getIdToken() + React Native + refreshing user database to authenticate email verified user

I am working on a React Native project and using Firebase.
I am trying to get the user to log in after (s)he has verified their email address. I send the user an email on registration, the user clicks on the verification link to verify themselves and then should be able to logon. My current code allows the user to log in post verification but only after I have refreshed the app. I would want the user to login after the verification without refreshing the app.
I found out that I can achieve it using getIdToken() in Firebase. But somehow I can't seem to get it working. Any pointers where and what I am doing wrong? Thanks in Advance.
My code snippet for this function is:
_login = () =>{
var me = this;
firebaseRef.auth().onAuthStateChanged(function(user) {
if(user){
user.getIdToken(forceRefresh).then(function() {
if( firebaseRef.auth().currentUser.emailVerified){
firebaseRef.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(){
// some function here, which is working perfectly
},
function(error) {
alert('The username or password is incorrect');
console.log(error);
})
}
else {
alert('Your email has not been verified');
}
},
function(error) {
alert('There is an email verification error');
console.log(error);
})
}
}
)
}
firebase.auth().signInWithEmailAndPassword(email, password)
.then(() => {
if(firebase.auth().currentUser.emailVerified === false) {
Alert.alert('Message')
} else {
Actions.screen()
}})
.catch(erro => Alert.alert(erro);
}

How to know whether the Register Email is verified or not in Firebase?

onSubmit(formData) {
if(formData.valid) {
console.log(formData.value);
this.af.auth.createUser({
email: formData.value.email,
password: formData.value.password
}).then(
authState => {
authState.auth.sendEmailVerification();
this.router.navigate(['/login'])
}).catch(
(err) => {
console.log(err);
this.error = err;
})
}
}
In Firebase, I set the SendEmailVerfication like the code above, and the email could send normally.However, in my app, there is no difference between the user who does not click the verification email with those clicked, how to make a difference?
According to the documentation, the User object contains an emailVerified property.
So the user to which the signInWithEmailAndPassword method's promise resolves - or the user that is passed to the onAuthStateChanged method's callback - can be inspected and the value of emailVerified can be checked.
You can use firebase.auth().currentUser.emailVerified
This will return true or false.
- If you are already loggedIn below solutions can help you to check email verified status.
1) The recommended way to get the current user is by setting an observer on the Auth object:
firebase.auth().onAuthStateChanged(authUser => {
if(authUser.user.emailVerified){ //This will return true or false
console.log('email is verified')
}else{
console.log('email not verified')
}
})
2) You can also get the currently signed-in user by using the currentUser property.
var user = firebase.auth().currentUser;
if (user.emailVerified) {
// email is verified.
} else {
// email is not verified.
}
- If you are not loggedIn then please try below solution.
firebase.auth().signInWithEmailAndPassword(email, password ).then(authUser => {
if(authUser.user.emailVerified){ //This will return true or false
console.log('email is verified')
}else{
console.log('email not verified')
}
}).catch(function(error) {
});
you can add an attribute at firebase database for the state of your user verification link

Firebase - no displayName for user

I can add users in Firebase console -> Auth but I can't do anything more than setting an email and password for them.
Could I in some way set for them displayName?
I guess if you just want to update users profile:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
user.updateProfile({
displayName: "Random Name"
}).then(function() {
// Update successful.
}, function(error) {
// An error happened.
});
} else {
// No user is signed in.
}
});
Additionally: https://firebase.google.com/docs/auth/web/manage-users
When you create a user you create it only with email and password but you can and the displayName in the promise, then inside the .then() method you call the updateProfile method and you are ready, right down is the code:
onSubmit(formData) {
if(formData.valid) {
console.log(formData.value);
this.af.auth.createUserWithEmailAndPassword(
formData.value.email,
formData.value.password
).then(
(success) => {
console.log(success);
success.updateProfile({
displayName: "Example User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).catch(
(err) => {
this.error = err;
});
this.router.navigate(['/login'])
}).catch(
(err) => {
this.error = err;
})
}
}
Note that in my example the displayName is set to "Example User", in the real app you just add the parameter as in my case it should be -> displayName:formData.value.name

Put the email address from Meteor.loginWithGoogle into a Session variable

I'm using Meteor.loginWithGoogle in my app. I'm trying to get the email address of the google user to put it into a Session variable.
Template.login.events({
'click #google-login': function(event){
Meteor.loginWithGoogle({}, function(err){
if ( err ) {
throw new Meteor.Error("Google login failed");
} else {
const emailAddress = ?; // how do I get this from google?
Session.set('email',emailAddress);
Router.go('/profile');
}
});
}
});
I'm not sure whether i understood your question, but i guess what you're trying to ask is: "After a user performed a loginWithGoogle, how can i get his email address, and set it into his Session?"
After a login, Meteor.user() holds the current user document. Having that in mind:
const currentUser = Meteor.user();
const userGoogleServiceMain = currentUser.services.google.email;
With that, you can have:
Template.login.events({
'click #google-login': function(event){
Meteor.loginWithGoogle({}, function(err){
if ( err ) {
throw new Meteor.Error("Google login failed");
} else {
const currentUser = Meteor.user();
const emailAddress = currentUser.services.google.email;
Session.set('email',emailAddress);
Router.go('/profile');
}
});
}
});
You may find more details about that in: Meteor documentation and http://cs.wellesley.edu/~mashups/pages/meteor6.html

Meteor showing Accounts.createUser errors

I have the following code in my Meteor app where I create new users, assign them 'basic' role. Yet I am having a trouble showing on the client side errors returned while processing Accounts.createUser, can someone please tell me how I can return errors returned by Accounts.createUser while having it on the server as my code below. Thanks
/server/users.js
Meteor.methods({
'createMemberAccount': function (data, role) {
var userId;
Meteor.call('createNewAccount', data, function(err, result) {
if (err) {
return err;
}
console.log('New account id: '+ result);
Roles.addUsersToRoles(result, role);
return userId = result;
});
return userId;
},
'createNewAccount': function (adminData) {
return Accounts.createUser({email: adminData.email, password : adminData.password, roles: adminData.roles});
}
});
/client/signup.js
Template.signupForm.events({
'submit #signup-form': function(e, t){
e.preventDefault();
var userData = {};
userData.email = $(e.target).find('[name=email]').val();
userData.password = $(e.target).find('[name=password]').val();
userData.roles = ['basic'];
Meteor.call('createMemberAccount', userData, 'basic', function(err, userId) {
if (!err) {
console.log('All OK');
} else {
console.log('Error: ' + err.message);
}
});
return false;
}
});
Since You are creating an static rol "basic", you don't need to do that pair of methods, and Meteor.calls, instead you can use
So, use the v on the client side, just like this.
Template.register.events({
'submit #register-form' : function(e, t) {
e.preventDefault();
var email = t.find('#account-email').value
, password = t.find('#account-password').value;
// Trim and validate the input
Accounts.createUser({email: email, password : password}, function(err){
if (err) {
// Inform the user that account creation failed
} else {
// Success. Account has been created and the user
// has logged in successfully.
}
});
return false;
}
});
If you see there is not any role yet incude, so now on the server.js use the onCreateUser method.
//Server.js
Accounts.onCreateUser(function(options, user) {
if (options.profile)
user.profile = options.profile;
user.role = "basic"
return user;
});
Now thats is more easy, and with less code, if you are trying to create 2 differents roles like "Admin" and "Basic", just on the client side create a profile field named "profile.roles" and do a if statement on the onCreateUser.
return Accounts.createUser({email: adminData.email, password : adminData.password, roles: adminData.roles});
This part returns the userId once it is created, it doesn't return any errors when it fails.
When it fails, the returned value will be undefined
Also, in the server, we cannot use callbacks with Accounts.createUser
If you want find the errors, you have to use Accounts.createUser in client side.
Coming to this late, but on the server side, you can assign the createUser to a variable and it will return the new user’s _id; then you can check if that exists. For example (server side only):
let email = 'foo#bar.com';
let password = 'bar';
let profile = {firstName: 'foo', lastName: 'bar'};
let newId = Accounts.createUser({
password: password,
email: email,
profile: profile
});
if (!newId) {
// New _id did not get created, reason is likely EMail Already Exists
throw new Meteor.Error(403, "Cannot create user: " + error.reason);
}
else {
// Stuff here to do after creating the user
}
The Meteor.Error line will be passed back as an error in the callback on the client side, so you can reflect that error to the browser.

Resources