Skip to content

Commit

Permalink
Implement JWT
Browse files Browse the repository at this point in the history
  • Loading branch information
khanglu committed Jun 2, 2017
1 parent ab52873 commit 0c365e3
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 6 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
node_modules
config.js
10 changes: 9 additions & 1 deletion controllers/authentication.js
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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) });
});
});
};
1 change: 0 additions & 1 deletion models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
9 changes: 7 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
}

0 comments on commit 0c365e3

Please sign in to comment.