Advertisement
Guest User

Untitled

a guest
Apr 13th, 2017
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. const express = require("express");
  2. const bodyParser = require("body-parser");
  3. const jsonwebtoken = require('jsonwebtoken');
  4. const jwt = require('express-jwt');
  5.  
  6. const app = express();
  7.  
  8. const secret = "topsecret"// should be in ENV
  9.  
  10. // Middleware
  11. app.use(bodyParser.urlencoded({ extended: false }))
  12.  
  13. // Public Route
  14. app.get('/', (req, res) => {
  15. res.json({ message: "Hey this route can be accessed by everyone!" })
  16. })
  17.  
  18. // Check if the request ist authenticated
  19. app.get('/secure', jwt({ secret }), (req, res) => {
  20. res.json({
  21. message: "Only VIP can see this 😁",
  22. user: req.user
  23. });
  24. })
  25.  
  26. app.post('/authenticate', (req, res, next) => {
  27. const { email, password } = req.body;
  28.  
  29. if (email && password) {
  30. // replace with DB verification
  31. if (email === "florian@awesome.at" && password === "password") {
  32.  
  33. // create JWT
  34. const payload = { email };
  35.  
  36. // generate a new token which is signed with the secret and expires in 7 days
  37. jsonwebtoken.sign(payload, secret, { expiresIn: "7d" }, (err, token) => {
  38. if (err) next(err);
  39. res.json({
  40. message: "Awww yeah! Your JWT is ready!",
  41. token
  42. })
  43. });
  44.  
  45. } else {
  46. res.status(403).json({ message: "Nope that was not right!" });
  47. }
  48. } else {
  49. res.status(422).json({ message: "WTF Dude??" });
  50. }
  51.  
  52. })
  53.  
  54. // Handle Unauthorized Error
  55. app.use((err, req, res, next) => {
  56. if (err.status !== 401) next(err)
  57. res.status(401).json(err.inner);
  58. });
  59.  
  60. // Error Handler
  61. app.use((err, req, res, next) => {
  62. console.error(err);
  63. res.status(500).json({ message: 'Something broke!' });
  64. });
  65.  
  66. app.listen(3000, () => console.log("Server running on port 3000"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement