Newer
Older
const config = require(`${libs}/config`);
const log = require(`${libs}/log`)(module);
const User = require(`${libs}/models/user`);
const jwt = require('jwt-simple');
function emailSyntax(email) {
const regex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
return regex.test(email);
if (!req.body.email || !req.body.password) {
res.json({success: false, msg: 'Please pass email and password.'});
}, (req, res, next) => {
if(!emailSyntax(req.body.email)){
res.json({success: false, msg: 'Invalid email syntax.'});
} else {
next();
}, (req, res, next) => {
var newUser = new User({
email: req.body.email,
password: req.body.password
});
// save the user
newUser.save((err) => {
if (err) {
res.json({success: false, msg: 'Email already in use.'});
} else {
res.json({success: true, msg: 'Successful created new user.'});
}
});
userApp.post('/authenticate', (req, res) => {
User.findOne({
email: req.body.email
}, (err, user) => {
if (err) throw err;
if(!user){
res.json({success: false, msg: 'Authentication failed. User not found.'});
}
else {
user.comparePassword(req.body.password, (err, isMatch) => {
if (isMatch && !err) {
var secret = config.get('mongodb:secret');
// if user is found and password is right create a token
var token = jwt.encode(user, secret);
//returns user info including token as json
res.json({success: true, token: 'JWT ' + token});
}
else {
res.json({success: false, msg: 'Authentication failed. Wrong password'});
}
})
}
})
})