Skip to content

Commit

Permalink
-added middleware to authunticate
Browse files Browse the repository at this point in the history
-users/me GET
  • Loading branch information
mbadr2200 committed Mar 24, 2018
1 parent 53bb1ab commit b4bf4b9
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 7 deletions.
22 changes: 22 additions & 0 deletions server/middleware/authunticate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const {User} = require('./../models/user');

var authunticate = (req,res,next) => {

var token = req.header('x-auth');

User.findByToken(token)
.then((user) => {

if(!user){
return Promise.reject();
}
req.user = user;
req.token = token;
next();
})
.catch((e) => {
res.status(401).send();
})
};

module.exports = {authunticate};
22 changes: 22 additions & 0 deletions server/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,28 @@ UserSchema.methods.toJSON = function () {
});
};

UserSchema.statics.findByToken = function (token) {

// search for the user with the token provided
var User = this,
decoded;

try{
decoded = jwt.verify(token,'thesecret');
}catch(e){
return Promise.reject();
}
// return to chain then on the server js
return User.findOne({
'_id':decoded._id,
'tokens.token':token,
'tokens.access':'auth'
});

};



var User = mongoose.model('user',UserSchema);


Expand Down
20 changes: 13 additions & 7 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ const bodyParser = require('body-parser');
const {ObjectID} =require('mongodb');
const jwt = require('jsonwebtoken');
//Files
const {mongoose} = require('./db/mongoose');
const {Todo} = require('./models/todo');
const {User} = require('./models/user');

var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var {authunticate} = require('./middleware/authunticate');

// get express work
var app = express();
Expand Down Expand Up @@ -66,7 +66,7 @@ app.get('/todos/:id',(req,res) => {
});
});


// delete todo section
app.delete('/todos/:id',(req,res) => {

var todo_id = req.params.id;
Expand All @@ -92,7 +92,7 @@ app.delete('/todos/:id',(req,res) => {

})


// update the todo
app.patch('/todos/:id',(req,res) => {
var id = req.params.id;
var body = _.pick(req.body,['text','completed']);
Expand Down Expand Up @@ -124,7 +124,7 @@ app.delete('/todos/:id',(req,res) => {
});
});


// sign up a new user
app.post('/users',(req,res) => {

var body = _.pick(req.body,['email','password']);
Expand All @@ -143,6 +143,12 @@ app.delete('/todos/:id',(req,res) => {
})

})

// log in with exsiting user
app.get('/users/me',authunticate,(req,res) => {
res.send(req.user);
});


// listen to port
app.listen(port,() =>console.log(`Server Connected to port ${port}...`));

0 comments on commit b4bf4b9

Please sign in to comment.