Advertisement
Guest User

Untitled

a guest
Apr 5th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.19 KB | None | 0 0
  1. const express = require('express');
  2. const bodyParser = require('body-parser');
  3. const morgan = require('morgan'); // Log all HTTP requests to the console
  4. const app = express();
  5. const checkJwt = require('express-jwt'); // Check for access tokens automatically
  6. const bcrypt = require('bcrypt'); // Used for hashing passwords!
  7.  
  8. /****** Configuration *****/
  9. app.use(bodyParser.json()); // Make sure all json data is parsed
  10. app.use(morgan('combined')); // Log all requests to the console
  11.  
  12. const port = (process.env.PORT || 8080);
  13.  
  14.  
  15. if (!process.env.JWT_SECRET) {
  16. console.error('You need to put a secret in the JWT_SECRET env variable!');
  17. process.exit(1);
  18. }
  19.  
  20. /****** Middleware *****/
  21.  
  22. // Additional headers to avoid triggering CORS security errors in the browser
  23. // Read more: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
  24. app.use((req, res, next) => {
  25. res.header("Access-Control-Allow-Origin", "*");
  26. res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
  27. res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
  28.  
  29. // intercepts OPTIONS method
  30. if ('OPTIONS' === req.method) {
  31. // respond with 200
  32. console.log("Allowing OPTIONS");
  33. res.sendStatus(200);
  34. } else {
  35. // move on
  36. next();
  37. }
  38. });
  39.  
  40. // Open paths that does not need login
  41. let openPaths = [
  42. '/api/users/authenticate'
  43. ];
  44. // Validate the user using authentication
  45. app.use(
  46. checkJwt({ secret: process.env.JWT_SECRET }).unless({ path : openPaths})
  47. );
  48. app.use((err, req, res, next) => {
  49. if (err.name === 'UnauthorizedError') {
  50. res.status(401).json({ error: err.message });
  51. }
  52. });
  53.  
  54. /****** Data *****/
  55. // TODO: Move data to MongoDB using Mongoose
  56. const data = [
  57. { id: 0, task: "Do laundry", done: false},
  58. { id: 1, task: "Clean bedroom", done: false},
  59. { id: 2, task: "Bake cake", done: false},
  60. { id: 3, task: "Pick up groceries", done: true},
  61. { id: 4, task: "Post letter", done: false}
  62. ];
  63.  
  64. // TODO: Remove clear text passwords from data!
  65. // TODO: Move data to MongoDB using Mongoose!
  66. // Mock user data for testing! Don't do this in production!
  67. const users = [
  68. { id: 0, username: "krdo", password: '123'},
  69. { id: 1, username: "tosk", password: 'password'},
  70. { id: 2, username: "mvkh", password: 'l33th0xor'},
  71. ];
  72.  
  73. // TODO: Only hash passwords when creating new users or updating their password
  74. // Hash all the passwords for testing!
  75. users.forEach(user => {
  76. bcrypt.hash(user.password, 10, function(err, hash) {
  77. user.hash = hash;
  78. console.log(`Hash generated for ${user.username}`, user);
  79. });
  80. });
  81.  
  82. /****** Routes ******/
  83. let tasksRouter = require('./tasks_router')(data);
  84. app.use('/api/tasks', tasksRouter);
  85.  
  86. let usersRouter = require('./users_router')(users);
  87. app.use('/api/users', usersRouter);
  88.  
  89. /****** Error handling ******/
  90. app.use(function (err, req, res, next) {
  91. console.error(err.stack);
  92. res.status(500).send({msg: 'Something broke!'})
  93. });
  94.  
  95. /****** Listen ******/
  96. app.listen(port, () => console.log(`API running on port ${port}!`));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement