Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // routes/api.js
- const express = require('express');
- const router = express.Router();
- const passport = require('passport');
- const config = require('../config/database');
- require('../config/passport')(passport);
- const mongoose = require('mongoose');
- const jwt = require('jsonwebtoken');
- let User = require('../models/user');
- let Book = require('../models/book');
- const ExtractJwt = require('passport-jwt').ExtractJwt;
- router.post('/signup', function (req, res) {
- if (!req.body.username || !req.body.password) {
- res.json({success: false, msg: 'Please pass username and password.'});
- } else {
- let newUser = new User({
- username: req.body.username,
- password: req.body.password
- });
- // save the user
- newUser.save(function (err) {
- if (err) {
- return res.json({success: false, msg: 'Username already exists.'});
- }
- res.json({success: true, msg: 'Successful created new user.'});
- });
- }
- });
- router.post('/signin', function (req, res) {
- User.findOne({
- username: req.body.username
- }, function (err, user) {
- if (err) throw err;
- if (!user) {
- res.status(401).send({success: false, msg: 'Authentication failed. User not found.'});
- } else {
- // check if password matches
- user.comparePassword(req.body.password, function (err, isMatch) {
- if (isMatch && !err) {
- // if user is found and password is right create a token
- let token = jwt.sign(JSON.stringify(user), config.secret);
- // return the information including token as JSON
- res.json({success: true, token: 'JWT ' + token});
- } else {
- res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
- }
- });
- }
- });
- });
- router.post('/book',
- passport.authenticate('jwt', {
- session: false
- }), function (req, res) {
- let token = ExtractJwt.fromAuthHeaderAsBearerToken();
- if (token){
- Book.find(function (err, books) {
- if(err) return next(err);
- res.json(books);
- })
- } else {
- return res.status(403).send({success:false, msg:'Unauthorized.'})
- }
- });
- router.get('/book', passport.authenticate('jwt', {
- session:false
- }));
- module.exports = router;
Add Comment
Please, Sign In to add comment