From 3b6364f48a132ac8fcd530f8c2e0d69c35821d26 Mon Sep 17 00:00:00 2001 From: Lucas Gabriel Lima <lgl15@inf.ufpr.br> Date: Tue, 27 Sep 2016 11:02:50 -0300 Subject: [PATCH] add user authentication route and JSON Web Token response --- src/libs/app.js | 1 - src/libs/routes/user.js | 37 +++++++++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/libs/app.js b/src/libs/app.js index 5c97ad4e..f03e2282 100644 --- a/src/libs/app.js +++ b/src/libs/app.js @@ -16,7 +16,6 @@ const api = require('./routes/api'); const passport = require('passport'); -const jwt = require('jwt-simple'); app.use(passport.initialize()); diff --git a/src/libs/routes/user.js b/src/libs/routes/user.js index 6e78914f..357a577a 100644 --- a/src/libs/routes/user.js +++ b/src/libs/routes/user.js @@ -4,19 +4,24 @@ const userApp = express(); const libs = `${process.cwd()}/libs`; +const config = require(`${libs}/config`); + const log = require(`${libs}/log`)(module); const User = require('../models/user'); +const jwt = require('jwt-simple'); + userApp.post('/', (req, res) => { if (!req.body.email || !req.body.password) { res.json({success: false, msg: 'Please pass email and password.'}); - } else { + } + else { var newUser = new User({ email: req.body.email, password: req.body.password - }); + });const jwt = require('jwt-simple'); // save the user newUser.save((err) => { if (err) { @@ -27,4 +32,32 @@ userApp.post('/', (req, res) => { } }); +userApp.post('/authenticate', (req, res) => { + User.findOne({ + email: req.body.email + }, (err, user) => { + if (err) throw err; + + if(!user){ + res.send({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.send({success: false, msg: 'Authentication failed. Wrong password'}); + } + }) + } + }) +}) + module.exports = userApp; -- GitLab