Guest User

Untitled

a guest
Dec 14th, 2018
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. const express = require('express');
  2. const queryString = require('query-string');
  3.  
  4. const app = express();
  5.  
  6.  
  7. const USERS = [
  8. {id: 1,
  9. firstName: 'Joe',
  10. lastName: 'Schmoe',
  11. userName: 'joeschmoe@business.com',
  12. position: 'Sr. Engineer',
  13. isAdmin: true,
  14. // NEVER EVER EVER store passwords in plain text in real life. NEVER!!!!!!!!!!!
  15. password: 'password'
  16. },
  17. {id: 2,
  18. firstName: 'Sally',
  19. lastName: 'Student',
  20. userName: 'sallystudent@business.com',
  21. position: 'Jr. Engineer',
  22. isAdmin: true,
  23. // NEVER EVER EVER store passwords in plain text in real life. NEVER!!!!!!!!!!!
  24. password: 'password'
  25. },
  26. {id: 3,
  27. firstName: 'Lila',
  28. lastName: 'LeMonde',
  29. userName: 'lila@business.com',
  30. position: 'Growth Hacker',
  31. isAdmin: false,
  32. // NEVER EVER EVER store passwords in plain text in real life. NEVER!!!!!!!!!!!
  33. password: 'password'
  34. },
  35. {id: 4,
  36. firstName: 'Freddy',
  37. lastName: 'Fun',
  38. userName: 'freddy@business.com',
  39. position: 'Community Manager',
  40. isAdmin: false,
  41. // NEVER EVER EVER store passwords in plain text in real life. NEVER!!!!!!!!!!!
  42. password: 'password'
  43. }
  44. ];
  45.  
  46. function gateKeeper(req, res, next) {
  47. const {user, pass} = Object.assign(
  48. {user: null, pass: null}, queryString.parse(req.get('x-username-and-password')));
  49. req.user = USERS.find(
  50. (usr, index) => usr.userName === user && usr.password === pass);
  51. next();
  52. }
  53. app.use(gateKeeper);
  54.  
  55.  
  56. app.get("/api/users/me", (req, res) => {
  57. // send an error message if no or wrong credentials sent
  58. if (req.user === undefined) {
  59. return res.status(403).json({message: 'Must supply valid user credentials'});
  60. }
  61. // we're only returning a subset of the properties
  62. // from the user object. Notably, we're *not*
  63. // sending `password` or `isAdmin`.
  64. const {firstName, lastName, id, userName, position} = req.user;
  65. return res.json({firstName, lastName, id, userName, position});
  66. });
  67.  
  68. app.listen(process.env.PORT, () => {
  69. console.log(`Your app is listening on port ${process.env.PORT}`);
  70. });
Add Comment
Please, Sign In to add comment