Last active
January 16, 2019 15:49
-
-
Save sanath-kumar/f53110d6a1cb027656ea21477a9ba7af to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const user = require('../models/user') | |
var config = require('../config/keys') | |
const jwt = require('jsonwebtoken') | |
const passport = require('passport'); | |
module.exports.signup = function(req,res){ | |
var newUser = new user({ | |
email: req.body.email, | |
username: req.body.username, | |
password: req.body.password, | |
}); | |
newUser.save(function(err,user) { | |
if (err) { | |
if (err.code === 11000) { | |
return res.json({success: false, msg: 'Username already exists.'}); | |
}else{ | |
return res.json({success: false, msg: 'Signup failed'}); | |
} | |
}else{ | |
var token = jwt.sign(user.toObject(), config.secret); | |
res.json({success: true, token:'JWT ' + token, msg: 'Successful created new user.'}); | |
} | |
}); | |
} | |
module.exports.signin = function(req,res){ | |
user.findOne({ | |
email: req.body.email | |
}, function(err, user) { | |
if (err) throw err; | |
if (!user) { | |
res.send({success: false, msg: 'Authentication failed. User not found.'}); | |
} else { | |
user.comparePassword(req.body.password, function (err, isMatch) { | |
if (isMatch && !err) { | |
var token = jwt.sign(user.toObject(), config.secret); | |
res.json({success: true,token:'JWT ' + token,user : user}); | |
} else { | |
res.send({success: false, msg: 'Authentication failed. Wrong password.'}); | |
} | |
}); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment