From 1b8cb10a378cb554f2bd63fef6221c39503a422a Mon Sep 17 00:00:00 2001 From: Divyanshu Rathore Date: Tue, 25 Sep 2018 23:48:51 +0530 Subject: [PATCH] Adds Get /users/me and authentication middleware --- server/models/user.js | 18 ++++++++++++++++++ server/server.js | 7 ++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/server/models/user.js b/server/models/user.js index 66cd289..b4935f9 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -55,6 +55,24 @@ UserSchema.methods.generateAuthToken = function() { }) }; +UserSchema.statics.findByToken = function (token) { + var User = this; + + var decoded; + + try { + decoded = jwt.verify(token, 'abc123'); + } catch(e) { + return Promise.reject(); + } + + return User.findOne({ + '_id': decoded._id, + 'tokens.token': token, + 'tokens.access': 'auth' + }); +}; + 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 8f77b77..84fdcd6 100644 --- a/server/server.js +++ b/server/server.js @@ -6,9 +6,10 @@ const { ObjectID } = require('mongodb'); const { mongoose } = require('./db/mongoose'); const { Todo } = require('./models/todo'); const { User } = require('./models/user'); +const { authenticate } = require('./middleware/authenticate'); const app = express(); -const port = process.env.PORT || 3000; +const port = process.env.PORT || 3000; app.use(bodyParser.json()); @@ -98,6 +99,10 @@ app.post('/users', (req, res) => { }).catch(e => res.status(400).send(e)); }); +app.get('/users/me', authenticate, (req, res) => { + res.send(req.header(user)); +}); + app.listen(port, () => { console.log(`Started on port: ${port}`); });