Advertisement
Guest User

Untitled

a guest
May 24th, 2017
513
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. const express = require('express');
  2. // you'll need to use `queryString` in your `gateKeeper` middleware function
  3. const queryString = require('query-string');
  4.  
  5.  
  6. const app = express();
  7.  
  8. const USERS = [
  9. {id: 1,
  10. firstName: 'Joe',
  11. lastName: 'Schmoe',
  12. userName: 'joeschmoe@business.com',
  13. position: 'Sr. Engineer',
  14. isAdmin: true,
  15. // NEVER EVER EVER store passwords in plain text in real life. NEVER!!!!!!!!!!!
  16. password: 'password'
  17. },
  18. {id: 2,
  19. firstName: 'Sally',
  20. lastName: 'Student',
  21. userName: 'sallystudent@business.com',
  22. position: 'Jr. Engineer',
  23. isAdmin: true,
  24. // NEVER EVER EVER store passwords in plain text in real life. NEVER!!!!!!!!!!!
  25. password: 'password'
  26. },
  27. {id: 3,
  28. firstName: 'Lila',
  29. lastName: 'LeMonde',
  30. userName: 'lila@business.com',
  31. position: 'Growth Hacker',
  32. isAdmin: false,
  33. // NEVER EVER EVER store passwords in plain text in real life. NEVER!!!!!!!!!!!
  34. password: 'password'
  35. },
  36. {id: 4,
  37. firstName: 'Freddy',
  38. lastName: 'Fun',
  39. userName: 'freddy@business.com',
  40. position: 'Community Manager',
  41. isAdmin: false,
  42. // NEVER EVER EVER store passwords in plain text in real life. NEVER!!!!!!!!!!!
  43. password: 'password'
  44. }
  45. ];
  46.  
  47. function gateKeeper(req, res, next) {
  48. const string = req.headers['x-username-and-password']
  49. const userQuery = queryString.parse(string)
  50. const matchedUser = USERS.find((user) => {
  51. return user.userName === userQuery.user
  52. })
  53. req.user = matchedUser
  54. next();
  55. }
  56.  
  57. app.use(gateKeeper)
  58.  
  59.  
  60. app.get("/api/users/me", (req, res) => {
  61. if (req.user === undefined) {
  62. return res.status(403).json({message: 'Must supply valid user credentials'});
  63. }
  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. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement