From 0c365e34151fb86fe9323d7deefc09b78a6ab8db Mon Sep 17 00:00:00 2001 From: khanglu Date: Sat, 3 Jun 2017 09:55:09 +1000 Subject: [PATCH] Implement JWT --- .gitignore | 3 ++- controllers/authentication.js | 10 +++++++++- models/user.js | 1 - package-lock.json | 9 +++++++-- package.json | 3 ++- 5 files changed, 20 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index b512c09..6da04de 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -node_modules \ No newline at end of file +node_modules +config.js \ No newline at end of file diff --git a/controllers/authentication.js b/controllers/authentication.js index cdb20d3..fc4e11b 100644 --- a/controllers/authentication.js +++ b/controllers/authentication.js @@ -1,4 +1,12 @@ +const jwt = require("jwt-simple"); const User = require("../models/user"); +const config = require("../config"); + +function tokenForUser(user) { + const timestamp = new Date().getTime(); + // supply 'subject' 'issued at time' and secret string to jwt encoder + return jwt.encode({ sub: user.id, iat: timestamp }, config.secret); +} exports.signup = function(req, res, next) { const email = req.body.email; @@ -27,7 +35,7 @@ exports.signup = function(req, res, next) { return next(err); } // Respond to request indicating the user was created - res.json(user); + res.json({ token: tokenForUser(user) }); }); }); }; diff --git a/models/user.js b/models/user.js index 396a087..2c48c8d 100644 --- a/models/user.js +++ b/models/user.js @@ -13,7 +13,6 @@ const userSchema = new Schema({ userSchema.pre("save", function(next) { // get access to the user model const user = this; // user.email, user.password - console.log(this); // generate a salt then run callback bcrypt.genSalt(10, (err, salt) => { if (err) { diff --git a/package-lock.json b/package-lock.json index 26f709b..156ad40 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "auth-server-udemy", + "name": "auth-server-sample", "version": "1.0.0", "lockfileVersion": 1, "dependencies": { @@ -1025,6 +1025,11 @@ "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=" }, + "jwt-simple": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/jwt-simple/-/jwt-simple-0.5.1.tgz", + "integrity": "sha1-eeoBiRth3mto4T5nwLS1vak3spQ=" + }, "kareem": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/kareem/-/kareem-1.4.1.tgz", @@ -1623,4 +1628,4 @@ "integrity": "sha1-7byQPMOF/ARSPZZqM1UEtVBNG9I=" } } -} +} \ No newline at end of file diff --git a/package.json b/package.json index 461c2b7..2986c2c 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,9 @@ "bcrypt-nodejs": "0.0.3", "body-parser": "^1.17.2", "express": "^4.15.3", + "jwt-simple": "^0.5.1", "mongoose": "^4.10.4", "morgan": "^1.8.2", "nodemon": "^1.11.0" } -} \ No newline at end of file +}