Guest User

Untitled

a guest
Nov 12th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. // routes/api.js
  2. const express = require('express');
  3. const router = express.Router();
  4. const passport = require('passport');
  5. const config = require('../config/database');
  6. require('../config/passport')(passport);
  7. const mongoose = require('mongoose');
  8. const jwt = require('jsonwebtoken');
  9. let User = require('../models/user');
  10. let Book = require('../models/book');
  11. const ExtractJwt = require('passport-jwt').ExtractJwt;
  12.  
  13. router.post('/signup', function (req, res) {
  14. if (!req.body.username || !req.body.password) {
  15. res.json({success: false, msg: 'Please pass username and password.'});
  16. } else {
  17. let newUser = new User({
  18. username: req.body.username,
  19. password: req.body.password
  20. });
  21. // save the user
  22. newUser.save(function (err) {
  23. if (err) {
  24. return res.json({success: false, msg: 'Username already exists.'});
  25. }
  26. res.json({success: true, msg: 'Successful created new user.'});
  27. });
  28. }
  29. });
  30.  
  31.  
  32. router.post('/signin', function (req, res) {
  33. User.findOne({
  34. username: req.body.username
  35. }, function (err, user) {
  36. if (err) throw err;
  37.  
  38. if (!user) {
  39. res.status(401).send({success: false, msg: 'Authentication failed. User not found.'});
  40. } else {
  41. // check if password matches
  42. user.comparePassword(req.body.password, function (err, isMatch) {
  43. if (isMatch && !err) {
  44. // if user is found and password is right create a token
  45. let token = jwt.sign(JSON.stringify(user), config.secret);
  46. // return the information including token as JSON
  47. res.json({success: true, token: 'JWT ' + token});
  48. } else {
  49. res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
  50. }
  51. });
  52. }
  53. });
  54. });
  55.  
  56. router.post('/book',
  57. passport.authenticate('jwt', {
  58. session: false
  59. }), function (req, res) {
  60. let token = ExtractJwt.fromAuthHeaderAsBearerToken();
  61. if (token){
  62. Book.find(function (err, books) {
  63. if(err) return next(err);
  64. res.json(books);
  65. })
  66. } else {
  67. return res.status(403).send({success:false, msg:'Unauthorized.'})
  68. }
  69. });
  70.  
  71. router.get('/book', passport.authenticate('jwt', {
  72. session:false
  73. }));
  74.  
  75.  
  76. module.exports = router;
Add Comment
Please, Sign In to add comment