Guest User

Untitled

a guest
Jul 29th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. const jwt = require('jsonwebtoken');
  2. const user = require('../../models/dummyUser');
  3.  
  4. module.exports = (app) => {
  5.  
  6. app.post('/user/login', (req, res, next) => {
  7. const { body } = req;
  8. const { username } = body;
  9. const { password } = body;
  10.  
  11. //checking to make sure the user entered the correct username/password combo
  12. if(username === user.username && password === user.password) {
  13. //if user log in success, generate a JWT token for the user with a secret key
  14. jwt.sign({user}, 'privatekey', { expiresIn: '1h' },(err, token) => {
  15. if(err) { console.log(err) }
  16. res.send(token);
  17. });
  18. } else {
  19. console.log('ERROR: Could not log in');
  20. }
  21. })
  22.  
  23. //This is a protected route
  24. app.get('/user/data', checkToken, (req, res) => {
  25. //verify the JWT token generated for the user
  26. jwt.verify(req.token, 'privatekey', (err, authorizedData) => {
  27. if(err){
  28. //If error send Forbidden (403)
  29. console.log('ERROR: Could not connect to the protected route');
  30. res.sendStatus(403);
  31. } else {
  32. //If token is successfully verified, we can send the autorized data
  33. res.json({
  34. message: 'Successful log in',
  35. authorizedData
  36. });
  37. console.log('SUCCESS: Connected to protected route');
  38. }
  39. })
  40. });
  41.  
  42. }
  43.  
  44. //Check to make sure header is not undefined, if so, return Forbidden (403)
  45. const checkToken = (req, res, next) => {
  46. const header = req.headers['authorization'];
  47.  
  48. if(typeof header !== 'undefined') {
  49. const bearer = header.split(' ');
  50. const token = bearer[1];
  51.  
  52. req.token = token;
  53. next();
  54. } else {
  55. //If header is undefined return Forbidden (403)
  56. res.sendStatus(403)
  57. }
  58. }
Add Comment
Please, Sign In to add comment