Advertisement
Guest User

Untitled

a guest
May 29th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.81 KB | None | 0 0
  1. Backend authenticate:
  2.  
  3. const express = require('express');
  4. const router = express.Router();
  5. const jwt = require('jsonwebtoken');
  6. const moment = require('moment');
  7. const Users = require('../helpers/userLookup');
  8. const userService = new Users();
  9.  
  10. module.exports = {
  11. authenticate
  12. };
  13. /**
  14. * decodes a basic auth string to authenticate a user
  15. * @param {object} req the recieved request body
  16. * @param {object} res response body to send back
  17. */
  18. function authenticate(req, res) {
  19. let creds = decode(req.headers.authorization);
  20. if (!creds.password) {
  21. res.status(401).json({
  22. error: 'Could not log in. One or more fields were missing.'
  23. });
  24. } else {
  25. validateUser(creds).then((result) => {
  26. let token = jwt.sign(result, 'defInItelyNotaSecReT', { expiresIn: '8h' });
  27. res.status(200).json({
  28. message: 'Login successful!',
  29. user: result,
  30. expires: moment().add(8, 'h').utc(),
  31. token: token
  32. });
  33. }).catch((error) => {
  34. if (error.serviceFailed) {
  35. res.status(500).json(error);
  36. } else {
  37. res.status(401).json(error);
  38. }
  39. });
  40.  
  41. }
  42. }
  43. /**
  44. * validates that a user with the given information exists in the database
  45. * @param {object} creds user information decoded from the basic auth string
  46. */
  47. function validateUser(creds) {
  48. return new Promise((resolve, reject) => {
  49. userService.retrieveByQuery({
  50. email: creds.email
  51. }).then((users) => {
  52. if (!users[0]) {
  53. reject({
  54. message: 'Could not log in. The email address you entered is not a valid user account. Please try again.'
  55. });
  56. } else if (users[0].password == creds.password) {
  57. resolve(users[0]);
  58. } else {
  59. reject({
  60. message: 'Could not log in. The password you entered is incorrect.'
  61. });
  62. }
  63. }).catch((error) => {
  64. reject({
  65. serviceFailed: true,
  66. message: error
  67. });
  68. });
  69. });
  70. }
  71.  
  72. /**
  73. * decodes a given basic auth string
  74. * @param {object} header the header field from post endpoint's request body
  75. */
  76. function decode(header) {
  77. let auth = header.split(' ');
  78. let buffer = Buffer.from(auth[1], 'base64').toString();
  79. let creds = buffer.split(':');
  80. if (!creds[1]) {
  81. creds[1] = false;
  82. }
  83. //The following allows passwords (but not email addresses!) to contain the ":" character.
  84. for (let i = 2; i < creds.length; ++i) {
  85. creds[1] += ':' + creds[i];
  86. }
  87. return {
  88. email: creds[0],
  89. password: creds[1]
  90. };
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement