Advertisement
Guest User

Untitled

a guest
May 9th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. 'use strict';
  2. var jwt = require('jsonwebtoken'),
  3. superSecret = 'hornetSecret',
  4. User = require('./../user/user.model'),
  5. config = require('./../config');
  6.  
  7. // validar user debe retornar primise
  8.  
  9. exports.validateUser = function(req, res, next){
  10. // check header or url parameters or post parameters for token
  11. // deleted req.body.token || / becouse is passing token from mercadopago module
  12. var token = req.query.token || req.headers['x-access-token'];
  13.  
  14. // decode token
  15. if (token) {
  16.  
  17. // verifies secret and checks exp
  18. jwt.verify(token, config.secret, function(err, decoded) {
  19. if (err) {
  20. return res.status(403).send({
  21. success: false,
  22. message: 'Failed to authenticate token.'
  23. });
  24. //return res.json({ success: false, message: 'Failed to authenticate token.' });
  25. } else {
  26. // if everything is good, save to request for use in other routes
  27. req.decoded = decoded;
  28. next();
  29. }
  30. });
  31.  
  32. } else {
  33. return res.status(403).send({
  34. success: false,
  35. message: 'No token provided.'
  36. });
  37.  
  38. // if there is no token
  39. // return an error
  40. //return res.json({ success: false, message: 'No token provided.' });
  41. }
  42. };
  43.  
  44. exports.authenticate = function (req, res) {
  45.  
  46. User.findOne({
  47. email : req.body.email
  48. }).select('name email password account').exec(function(err, user) {
  49.  
  50. if (err) throw err;
  51.  
  52. if (!user) {
  53. res.json({
  54. sucess : false,
  55. message: 'Authentication failed. User not found.'
  56. })
  57. } else if (user) {
  58.  
  59. var validPassword = user.comparePassword(req.body.password);
  60. if (!validPassword) {
  61. res.json({
  62. sucess : false,
  63. message : 'Authentication failed. Wrong password.'
  64. });
  65. } else {
  66. var token = jwt.sign({
  67. _id : user._id,
  68. name : user.name,
  69. email : user.email
  70. }, superSecret, {
  71. expireInMinutes : 1440 // expires in 24 hours
  72. });
  73.  
  74. res.json({
  75. sucess : true,
  76. message : 'Enjoy your token!',
  77. token : token
  78. });
  79. }
  80. }
  81. });
  82. };
  83.  
  84. exports.me = function(req, res){
  85. res.json({req: req.decoded});
  86. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement