From 981ed09d262f1058798e3742734ac05d125daeec Mon Sep 17 00:00:00 2001 From: Divyanshu Rathore Date: Tue, 25 Sep 2018 23:02:51 +0530 Subject: [PATCH] Adds JWT token to application --- package.json | 5 +++- server/models/user.js | 54 ++++++++++++++++++++++++++++++++++++++++--- server/server.js | 12 ++++++++++ 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 4bc2d6f..3871ee5 100644 --- a/package.json +++ b/package.json @@ -15,13 +15,16 @@ "license": "ISC", "dependencies": { "body-parser": "^1.18.3", + "crypto-js": "^3.1.9-1", "expect": "^23.6.0", "express": "^4.16.3", + "jsonwebtoken": "^8.3.0", "lodash": "^4.17.11", "mocha": "^5.2.0", "mongodb": "^3.1.6", "mongoose": "^5.2.17", "nodemon": "^1.18.4", - "supertest": "^3.3.0" + "supertest": "^3.3.0", + "validator": "^10.7.1" } } diff --git a/server/models/user.js b/server/models/user.js index 78f962b..66cd289 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -1,12 +1,60 @@ -let mongoose = require('mongoose'); +const mongoose = require('mongoose'); +const validator = require('validator'); +const jwt = require('jsonwebtoken'); +const _ = require('lodash'); -let User = mongoose.model('User', { +var UserSchema = new mongoose.Schema({ email: { type: String, required: true, minlength: 5, + trim: true, + unique: true, + validate: { + validator: validator.isEmail, + message: `{VALUE} is not a valid email.` + } + }, + password: { + type: String, + minlength: 6, + required: true, trim: true - } + }, + tokens: [{ + access: { + type: String, + required: true + }, + token: { + type: String, + required: true + } + }] }); +UserSchema.methods.toJSON = function() { + var user = this; + var userObject = user.toObject(); + + return _.pick(userObject, ['_id','email']); +} + +UserSchema.methods.generateAuthToken = function() { + var user = this; + var access = 'auth'; + var token = jwt.sign({ + _id: user._id.toHexString(), + access + }, 'abc123').toString(); + + user.tokens.push({ access, token }); + + return user.save().then(() => { + return token; + }) +}; + +var User = mongoose.model('User', UserSchema); + module.exports = { User }; \ No newline at end of file diff --git a/server/server.js b/server/server.js index 9168a6e..8f77b77 100644 --- a/server/server.js +++ b/server/server.js @@ -86,6 +86,18 @@ app.put('/todos/:id', (req, res) => { }).catch((e) => res.status(400).send()); }); +app.post('/users', (req, res) => { + var body = _.pick(req.body, ['email', 'password']); + var user = new User(body); + + user.save().then(() => { + console.log(user.generateAuthToken()); + user.generateAuthToken(); + }).then((token) => { + res.header('x-auth', token).send(user); + }).catch(e => res.status(400).send(e)); +}); + app.listen(port, () => { console.log(`Started on port: ${port}`); });