Guest User

Untitled

a guest
Sep 12th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. const UserSchema = new Schema({
  2. posts: [{
  3. type: Schema.Types.ObjectId,
  4. ref: 'posts'
  5. }],
  6. firstName: {
  7. type: String,
  8. required: true
  9. },
  10. lastName: {
  11. type: String,
  12. required: true
  13. },
  14. ...
  15. });
  16.  
  17. module.exports = User = mongoose.model('users', UserSchema);
  18.  
  19. const PostSchema = new Schema({
  20. user: {
  21. type: Schema.Types.ObjectId,
  22. ref: 'users'
  23. },
  24. text: {
  25. type: String,
  26. required: true
  27. },
  28. name: {
  29. type: String
  30. },
  31. ...
  32. });
  33.  
  34. module.exports = Post = mongoose.model('posts', PostSchema);
  35.  
  36. const User = require('../../models/User');
  37.  
  38. router.post('/login', (req, res) => {
  39. const { errors, isValid } = validateLoginInput(req.body);
  40.  
  41. // Check Validation
  42. if (! isValid) {
  43. return res.status(400).json(errors);
  44. }
  45.  
  46. const email = req.body.email;
  47. const password = req.body.password;
  48.  
  49. // Find user by email
  50. User.findOne({ email })
  51. .populate('posts')
  52. .then(user => {
  53. if (! user) {
  54. errors.email = 'User not found';
  55. return res.status(400).json(errors);
  56. }
  57.  
  58. // Check password
  59. bcrypt.compare(password, user.password).then(isMatch => {
  60. if (isMatch) {
  61. // User Matched
  62. // Create JWT Payload
  63. const payload = {
  64. id: user.id,
  65. firstName: user.firstName,
  66. lastName: user.lastName,
  67. name: user.firstName + ' ' + user.lastName,
  68. avatar: user.avatar,
  69. posts: user.posts
  70.  
  71. };
  72.  
  73. jwt.sign(
  74. payload,
  75. keys.secretOrKey,
  76. { expiresIn: 3600 }, (err, token) => {
  77. res.json({
  78. success: true,
  79. token: 'Bearer ' + token,
  80. payload
  81. });
  82. });
  83.  
  84. } else {
  85. errors.password = 'Password is incorrect';
  86. return res.status(400).json(errors);
  87. }
  88. });
  89. });
  90. });
  91.  
  92. router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
  93. const { errors, isValid } = validatePostInput(req.body);
  94.  
  95. if (! isValid) {
  96. // Return errors with 400 status
  97. return res.status(400).json(errors)
  98. }
  99.  
  100. const newPost = new Post({
  101. text: req.body.text,
  102. name: req.body.name,
  103. avatar: req.body.avatar,
  104. user: req.user.id
  105. });
  106.  
  107. newPost.save().then(post => res.json(post));
  108. });
Add Comment
Please, Sign In to add comment