Advertisement
Guest User

Untitled

a guest
Apr 20th, 2017
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. /**
  2. * To get started install
  3. * express bodyparser jsonwebtoken express-jwt
  4. * via npm
  5. * command :-
  6. * npm install express bodyparser jsonwebtoken express-jwt --save
  7. */
  8.  
  9. // Bringing all the dependencies in
  10. const express = require('express');
  11. const bodyParser = require('body-parser');
  12. const jwt = require('jsonwebtoken');
  13. const exjwt = require('express-jwt');
  14.  
  15. // Instantiating the express app
  16. const app = express()
  17.  
  18. // Setting up bodyParser to use URL ENCODED and set it to req.body
  19. app.use(bodyParser.urlencoded({ extended: true }))
  20.  
  21. // INstantiating the express-jwt middleware
  22. const jwtMW = exjwt({
  23. secret: "keyboard cat 4 ever"
  24. })
  25.  
  26. // MOCKING DB just for test
  27. let users = [
  28. {
  29. id: 1,
  30. username: "test",
  31. password: "asdf123"
  32. },
  33. {
  34. id: 2,
  35. username: "test2",
  36. password: "asdf12345"
  37. }
  38. ]
  39.  
  40. // LOGIN ROUTE
  41. app.post('/login', (req, res) => {
  42. const { username, password } = req.body;
  43. // Use your DB ORM logic here to find user and compare password
  44. for (let user of users) { // I am using a simple array users which i made above
  45. if (username == user.username && password == user.password /* Use your password hash checking logic here !*/) {
  46. //If all credentials are correct do this
  47. let token = jwt.sign({ id: user.id }, "keyboard cat 4 ever", { expiresIn: 129600 }) // Sigining the token
  48. res.json({
  49. sucess: true,
  50. err: null,
  51. token
  52. })
  53. break;
  54. }
  55. else {
  56. res.json({
  57. sucess: false,
  58. token: null,
  59. err: "Username or password is incorrect"
  60. })
  61. }
  62. }
  63. })
  64.  
  65. app.get('/', jwtMW /* Using the express jwt MW here */, (req, res) => {
  66. res.send("You are authenticated") //Sending some response when authenticated
  67. })
  68.  
  69. // Starting the app on PORT 3000
  70. const PORT = 3000;
  71. app.listen(PORT, () => {
  72. console.log(`Magic happens on port ${PORT}`)
  73. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement