Meteor : Stop login if email is unverified - javascript

In my meteor.js app I only want verified users signing in. They must click the link in their email first.
I don't see any official mention of this in the documentation. Any ideas?
client javascript
Template.login.events({
'submit #login-form' : function(e,t){
e.preventDefault();
var email = t.find('#email').value;
var password = t.find('#password').value;
Meteor.loginWithPassword(email, password, function(error){
if (error){
console.log(error);
}
else{
console.log("success");
}
});
return false;
}
});
There are some stackoverflow posts but these only cover blocking unverified users from viewing certain pages:
Meteor: Block access to application if user's email is not verified

What you could do is check for the verified token inside the Accounts db.
Something of this sort:
if (Meteor.isServer) {
Meteor.methods({
'get_users_by_email': function(email) {
return Users.findOne({ emails.address: email }).fetch()[0].verified;
}
});
}
if (Meteor.isClient) {
a = Meteor.call('get_users_by_email', 'email-entered-by-user');
}
Then, you can check whether a is true or false.
When a is false, you could login the user, and when it is true, you can prevent the login by showing an error or whateever you want to tell people who have verified email adresses.

/lib/methods.js
Meteor.startup(function() {
checkEmailVerification: function(email) {
found_user = Meteor.users.findOne({ 'emails.address' : email })
if(found_user){
if(found_user.emails[0].verified == true){
return "verified";
}else{
return "unverified";
}
}else{
return "notfound";
}
}
});
});
/client/login.js
Template.login.events({
'submit #login' : function(event, t){
event.preventDefault();
var email = t.find('#email').value;
var password = t.find('#password').value;
Meteor.call('checkEmailVerification', email, function(error,data){
if (data == "verified"){
Meteor.loginWithPassword(email, password, function(err){
if (err){
FlashMessages.sendError("Either email or password is incorrect");
}
else{
FlashMessages.sendSuccess("Logged in");
}
});
}else if(data == "unverified"){
FlashMessages.sendError("Check your email for a verification link");
}else{
FlashMessages.sendError("Either email or password is incorrect");
}
});
}
});

Related

error = new Error('data and hash arguments required') in node js (Help )

I am trying to compare the password of user and their password in the DB where it is saved (MongoDB). When that user logs in, their input password and DB password need to be compared. But when I run the code it's showing me an error of Error: data and hash arguments required.
var db=require('../config/connection')
var collection=require('../config/collections')
const bcrypt=require('bcrypt')
module.exports={
doSignup:(userData)=>{
return new Promise(async(resolve,reject)=>{
userData.Password= await bcrypt.hash(userData.Password,10)
db.get().collection('user').insertOne(userData).then((data)=>{
resolve(data.insertedId)
})
})
},
doLogin:(userData)=>{
return new Promise(async(resolve,reject)=>{
let loginstatus=false
let response={}
let user=await db.get().collection(collection.USER_COLLECTION).findOne({Email:userData.Email})
if(user){
bcrypt.compare(userData.Password,user.Password).then((status)=>{
if(result){
console.log("login success");
}else{
console.log("login failed");
}
})
}else
{
console.log('login failed');
}
})
}
}

Unable to add array to specific part of mongodb

In my database i have the following setup for testdata:
test1 [
[0] { test: Array, comments: Array },
[1] { test: Array, comments: Array }
]
I've since before added the test Array using
var testet1 = { test: newTest1.split(" "), comments: Array };
user.test1.push(testet1);
But I'm for some reason unable to add an array to comments using:
user.test1[0].comments.push(newTest1);
Below is how i define the userSchema, it contains more but i think they are irrelevant in this scenario.
var UserSchema = new Schema({
test1: { type: Array, required: false },
test2: { type: Array, required: false },
test3: { type: Array, required: false }
});
Below is a part of the code that saves the data to the database. The "newTest1" is an array of comments. I've been trying to add a comment to the object but have been unable to.
No error is displayed, the array I'm trying to get into the object is just not added. It's really hard to find the why it's not working when no error is shown.
html:
<form name="edit.test1" ng-submit="ctrl.updateTest1(newComment1, newComment2, ctrl.artikel)">
<div class="form-group">
<label>Kommentarer:</label>
<input class="form-control" type="text" name="test1" placeholder="Comment on first value" ng-model="newComment1" autocomplete="off">
<br>
<input class="form-control" type="text" name="test1" placeholder="Comment on second value" ng-model="newComment2" autocomplete="off">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Controller:
app.updateTest1 = function(newComment1, newComment2, index) {
app.errorMsg = false; // Clear any error message
app.disabled = true; // Lock form while processing
// Check if username submitted is valid
var userObject = {}; // Create the user object to pass to function
userObject._id = app.currentUser; // Pass current user _id in order to edit
userObject.test1 = [$scope.newComment1, $scope.newComment2, index]; // Set the new username provided
// Runs function to update the user's username
User.editUser(userObject).then(function(data) {
// Behöver jag lägga till något här??
});
};
Userfactory:
userFactory.editUser = function(id) {
return $http.put('/api/edit', id);
};
Creating a new user when a user registers:
router.post('/users', function(req, res) {
var user = new User(); // Create new User object
user.username = req.body.username; // Save username from request to User object
user.password = req.body.password; // Save password from request to User object
user.email = req.body.email; // Save email from request to User object
user.name = req.body.name; // Save name from request to User object
user.temporarytoken = jwt.sign({ username: user.username, email: user.email }, secret, { expiresIn: '24h' }); // Create a token for activating account through e-mail
// Check if request is valid and not empty or null
if (req.body.username === null || req.body.username === '' || req.body.password === null || req.body.password === '' || req.body.email === null || req.body.email === '' || req.body.name === null || req.body.name === '') {
res.json({ success: false, message: 'Ensure username, email, and password were provided' });
} else {
// Save new user to database
user.save(function(err) {
if (err) {
// Check if any validation errors exists (from user model)
if (err.errors !== null) {
if (err.errors.name) {
res.json({ success: false, message: err.errors.name.message }); // Display error in validation (name)
} else if (err.errors.email) {
res.json({ success: false, message: err.errors.email.message }); // Display error in validation (email)
} else if (err.errors.username) {
res.json({ success: false, message: err.errors.username.message }); // Display error in validation (username)
} else if (err.errors.password) {
res.json({ success: false, message: err.errors.password.message }); // Display error in validation (password)
} else {
res.json({ success: false, message: err }); // Display any other errors with validation
}
} else if (err) {
// Check if duplication error exists
if (err.code == 11000) {
if (err.errmsg[61] == "u") {
res.json({ success: false, message: 'That username is already taken' }); // Display error if username already taken
} else if (err.errmsg[61] == "e") {
res.json({ success: false, message: 'That e-mail is already taken' }); // Display error if e-mail already taken
}
} else {
res.json({ success: false, message: err }); // Display any other error
}
}
} else {
// Create e-mail object to send to user
var email = {
from: 'MEAN Stack Staff, cruiserweights#zoho.com',
to: [user.email, 'gugui3z24#gmail.com'],
subject: 'Your Activation Link',
text: 'Hello ' + user.name + ', thank you for registering at localhost.com. Please click on the following link to complete your activation: http://www.herokutestapp3z24.com/activate/' + user.temporarytoken,
html: 'Hello<strong> ' + user.name + '</strong>,<br><br>Thank you for registering at localhost.com. Please click on the link below to complete your activation:<br><br>http://www.herokutestapp3z24.com/activate/'
};
// Function to send e-mail to the user
client.sendMail(email, function(err, info) {
if (err) {
console.log(err); // If error with sending e-mail, log to console/terminal
} else {
console.log(info); // Log success message to console if sent
console.log(user.email); // Display e-mail that it was sent to
}
});
res.json({ success: true, message: 'Account registered! Please check your e-mail for activation link.' }); // Send success message back to controller/request
}
});
}
});
api.js:
router.put('/edit', function(req, res) {
var editUser = req.body._id; // Assign _id from user to be editted to a variable
if (req.body.name) var newName = req.body.name; // Check if a change to name was requested
if (req.body.username) var newUsername = req.body.username; // Check if a change to username was requested
if (req.body.email) var newEmail = req.body.email; // Check if a change to e-mail was requested
if (req.body.permission) var newPermission = req.body.permission; // Check if a change to permission was requested
if (req.body.test1) {
var newTest1 = req.body.test1;
}
if (req.body.test2) {
var newTest2 = req.body.test2;
}
if (req.body.test3) {
var newTest3 = req.body.test3;
}
if (req.body.test4) {
var newTest4 = req.body.test4;
}
if (req.body.test5) {
var newTest5 = req.body.test5;
}
// Look for logged in user in database to check if have appropriate access
User.findOne({ username: req.decoded.username }, function(err, mainUser) {
if (err) {
// Create an e-mail object that contains the error. Set to automatically send it to myself for troubleshooting.
var email = {
from: 'MEAN Stack Staff, cruiserweights#zoho.com',
to: 'gugui3z24#gmail.com',
subject: 'Error Logged',
text: 'The following error has been reported in the MEAN Stack Application: ' + err,
html: 'The following error has been reported in the MEAN Stack Application:<br><br>' + err
};
// Function to send e-mail to myself
client.sendMail(email, function(err, info) {
if (err) {
console.log(err); // If error with sending e-mail, log to console/terminal
} else {
console.log(info); // Log success message to console if sent
console.log(user.email); // Display e-mail that it was sent to
}
});
res.json({ success: false, message: 'Something went wrong. This error has been logged and will be addressed by our staff. We apologize for this inconvenience!' });
} else {
// Check if logged in user is found in database
if (!mainUser) {
res.json({ success: false, message: "no user found" }); // Return error
} else {
// Check if a change to name was requested
-----> HERE if (newTest1) {
// Check if person making changes has appropriate access
if (mainUser.permission === 'admin') {
// Look for user in database
User.findOne({ _id: editUser }, function(err, user) {
if (err) {
res.json({ success: false, message: 'Something went wrong. This error has been logged and will be addressed by our staff. We apologize for this inconvenience!' });
} else {
// Check if user is in database
if (!user) {
res.json({ success: false, message: 'No user found' }); // Return error
} else {
if (Array.isArray(newTest1)) {
------> this does not work user.test1[0].comments.push(newTest1);
//user.test1.splice(index, 0, newTest1)
} else {
---> this works var testet1 = { test: newTest1.split(" "), comments: Array };
user.test1.push(testet1); // Assign new name to user in database
}
// Save changes
user.save(function(err) {
if (err) {
console.log(err); // Log any errors to the console
} else {
res.json({ success: true, message: 'Name has been updated!' }); // Return success message
}
});
}
}
});
Why is this? How can i add an array to comments in my db?

How to check if there's no errors in authentication process in Firebase Web?

I'm new to Web Development, especially to Firebase.
I'm trying to check if there are no errors while creating a user in Firebase Authentication system, so I can put this user into Database.
Here's my code:
function register() {
var firebaseRef = firebase.database().ref();
var shaObj = new jsSHA("SHA-256", "TEXT")
shaObj.update(passwordField.value)
//console.log(hash)
var email = emailField.value
var password = shaObj.getHash("HEX")
if (isBarber != null) {
if (email != "" && password != "") {
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
$('#errorMsg').show();
$('#errorMsg').text(error.message);
if (error === null) {
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}
});
} else {
alert('Email or password fields are empty')
}
} else {
alert('Select your role')
}
}
createUserWithEmailAndPassword works properly and creates a user, but I don't know how to check if there are no errors so I could add this user to database.
Thanks a lot
You can use then() to action on a successful registration as follows:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//Registration is successful
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}).catch(error) {
//Registration unsuccessful
$('#errorMsg').show();
$('#errorMsg').text(error.message);
});

Parse Facebook login - Save input username and email

I'm working on a Facebook login for a Parse App, and have added the login element, but would now like to add the FB profile email and name into the database. However, I am unable to do so. How would I be able to insert the username and email of a new user who is using Facebook to register on the app?
$scope.loginFacebook = function() {
Parse.FacebookUtils.logIn("email", {
success: function(user) {
if (!user.existed()) {
FB.api('/me?fields=name,email', function (response) {
var user = new Parse.User();
user.set("username", response.username);
user.set("email", response.email);
});
} else {
alert("You're logged in with Facebook!")
//redirect to dashboard page
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
};
Just found out the solution to this. I needed to make a request from FB graphs on the url:
$scope.loginFacebook = function() {
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
FB.api('/me?fields=id,name,email,permissions', function (response) {
user.set('username', response.name);
user.set('email', response.email);
user.save();
alert("You're registered and logged with via Facebook!");
//redirect to dashboard
});
} else {
alert("You're logged in with Facebook!");
//redirect to dashboard page
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
};
This should work for you...
FB.api('/me', function (me) {
user.set("facebook_id", me.id);
user.set("facebook_link", me.link);
user.set("firstName", me.first_name);
user.set("lastName", me.last_name);
user.setEmail(me.email);
user.save().then(function () {
//go to new page
});
});

Accounts.sendVerificationEmail Issue in Meteor

I Need to send VerificationEmail using Meteor.I did the code but It didn't send VerificationEmail and also got error on server side.Error is : Can't find user.I didn't have any idea about this.so Please see the below code & suggest me how to do.
JS Code:
if (Meteor.isClient)
{
Template.main.events
({
'submit #register-form' : function (e,t)
{
console.log("You pressed the button Register ");
e.preventDefault();
var username = t.find('#username').value
, name = t.find('#name').value
, email = t.find('#email1').value
, password = t.find('#pwd1').value;
console.log("password="+password);
var isValidPassword = function(val, field)
{
if (val.length >= 6) {
return true;
} else {
Session.set('displayMessage', 'Error & Too short.')
return false;
}
}
if (isValidPassword(password))
{
console.log(" *** isValidPassword *** ");
Accounts.createUser({email: email, password : password,username : username }, function(err)
{
if (err)
{
console.log(err);
}
else
{
console.log("Register Successfully");
Meteor.call('sendEmail',
'*****#gmail.com',
'****.com',
'Hello from Meteor!',
'This is a test of Email.send.');
}
});
}
else
{
console.log("*** Error ***");
}
}
});
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
});
//Meteor methods
Meteor.methods
({
sendEmail: function (to, from, subject, text)
{
Accounts.config({sendVerificationEmail: true, forbidClientAccountCreation: false});
process.env.MAIL_URL = 'smtp://****#gmail.com:*pwd*#smtp.gmail.com:587';
this.unblock();
Accounts.sendVerificationEmail(to);
}
});
}
Did you send the email to an email address? When you use to in Accounts.sendVerificationEmail(to);
it must be the _id of the user you want to send the confirmation email to, not their email address.

Categories

Resources