Skip to content

Commit

Permalink
Adds JWT token to application
Browse files Browse the repository at this point in the history
  • Loading branch information
DeadlockDruid committed Sep 25, 2018
1 parent 240c652 commit 981ed09
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 4 deletions.
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
54 changes: 51 additions & 3 deletions server/models/user.js
Original file line number Diff line number Diff line change
@@ -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 };
12 changes: 12 additions & 0 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
});
Expand Down

0 comments on commit 981ed09

Please sign in to comment.