SHARE
TWEET

Untitled

a guest Jan 25th, 2019 104 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. var bodyParser = require('body-parser');
  3. var jwt = require('jsonwebtoken');
  4.  
  5. var passport = require('passport');
  6. var passportJWT = require('passport-jwt');
  7.  
  8. var ExtractJwt = passportJWT.ExtractJwt;
  9. var JwtStrategy = passportJWT.Strategy;
  10.  
  11. var jwtOptions = {};
  12. jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
  13. jwtOptions.secretOrKey = 'wowwow';
  14.  
  15. // lets create our strategy for web token
  16. var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
  17.   console.log('payload received', jwt_payload);
  18.   var user = getUser({ id: jwt_payload.id });
  19.  
  20.   if (user) {
  21.     next(null, user);
  22.   } else {
  23.     next(null, false);
  24.   }
  25. });
  26. // use the strategy
  27. passport.use(strategy);
  28.  
  29. const app = express();
  30. // initialize passport with express
  31. app.use(passport.initialize());
  32.  
  33. // parse application/json
  34. app.use(bodyParser.json());
  35. //parse application/x-www-form-urlencoded
  36. app.use(bodyParser.urlencoded({ extended: true }));
  37.  
  38. const Sequelize = require('sequelize');
  39.  
  40. // initialze an instance of Sequelize
  41. const sequelize = new Sequelize({
  42.   database: 'test_sequelize',
  43.   username: 'root',
  44.   password: '',
  45.   dialect: 'mysql',
  46. });
  47.  
  48. // check the databse connection
  49. sequelize
  50.   .authenticate()
  51.   .then(() => console.log('Connection has been established successfully.'))
  52.   .catch(err => console.error('Unable to connect to the database:', err));
  53.  
  54. // create user model
  55. const User = sequelize.define('user', {
  56.   name: {
  57.     type: Sequelize.STRING,
  58.   },
  59.   password: {
  60.     type: Sequelize.STRING,
  61.   },
  62. });
  63.  
  64. // create table with user model
  65. User.sync()
  66.   .then(() => console.log('User table created successfully'))
  67.   .catch(err => console.log('oooh, did you enter wrong database credentials?'));
  68.  
  69. // create some helper functions to work on the database
  70. const createUser = async ({ name, password }) => {
  71.   return await User.create({ name, password });
  72. };
  73.  
  74. const getAllUsers = async () => {
  75.   return await User.findAll();
  76. };
  77.  
  78. const getUser = async obj => {
  79.   return await User.findOne({
  80.     where: obj,
  81.   });
  82. };
  83.  
  84. // set some basic routes
  85. app.get('/', function(req, res) {
  86.   res.json({ message: 'Express is up!' });
  87. });
  88.  
  89. // get all users
  90. app.get('/users', function(req, res) {
  91.   getAllUsers().then(user => res.json(user));
  92. });
  93.  
  94. // register route
  95. app.post('/register', function(req, res, next) {
  96.   const { name, password } = req.body;
  97.   createUser({ name, password }).then(user =>
  98.     res.json({ user, msg: 'account created successfully' })
  99.   );
  100. });
  101.  
  102. //login route
  103. app.post('/login', async function(req, res, next) {
  104.   const { name, password } = req.body;
  105.   if (name && password) {
  106.     var user = await getUser({ name: name });
  107.     if (!user) {
  108.       res.status(401).json({ message: 'No such user found' });
  109.     }
  110.     if (user.password === password) {
  111.       // from now on we'll identify the user by the id and the id is the
  112.       // only personalized value that goes into our token
  113.       var payload = { id: user.id };
  114.       var token = jwt.sign(payload, jwtOptions.secretOrKey);
  115.       res.json({ msg: 'ok', token: token });
  116.     } else {
  117.       res.status(401).json({ msg: 'Password is incorrect' });
  118.     }
  119.   }
  120. });
  121.  
  122. // protected route
  123. app.get('/protected', passport.authenticate('jwt', { session: false }), function(req, res) {
  124.   res.json('Success! You can now see this without a token.');
  125. });
  126.  
  127. // start app
  128. app.listen(3000, function() {
  129.   console.log('Express is running on port 3000');
  130. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top