Guest User

Untitled

a guest
May 3rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. // AuthHandler.js
  2.  
  3. /*
  4. * Helpers
  5. */
  6. function signToken(id) {
  7. return jwt.sign({ id: id }, process.env.JWT_SECRET, {
  8. expiresIn: 86400 // expires in 24 hours
  9. });
  10. }
  11.  
  12. function checkIfInputIsValid(eventBody) {
  13. if (
  14. !(eventBody.password &&
  15. eventBody.password.length >= 7)
  16. ) {
  17. return Promise.reject(new Error('Password error. Password needs to be longer than 8 characters.'));
  18. }
  19.  
  20. if (
  21. !(eventBody.name &&
  22. eventBody.name.length > 5 &&
  23. typeof eventBody.name === 'string')
  24. ) return Promise.reject(new Error('Username error. Username needs to longer than 5 characters'));
  25.  
  26. if (
  27. !(eventBody.email &&
  28. typeof eventBody.name === 'string')
  29. ) return Promise.reject(new Error('Email error. Email must have valid characters.'));
  30.  
  31. return Promise.resolve();
  32. }
  33.  
  34. function register(eventBody) {
  35. return checkIfInputIsValid(eventBody) // validate input
  36. .then(() =>
  37. User.findOne({ email: eventBody.email }) // check if user exists
  38. )
  39. .then(user =>
  40. user
  41. ? Promise.reject(new Error('User with that email exists.'))
  42. : bcrypt.hash(eventBody.password, 8) // hash the pass
  43. )
  44. .then(hash =>
  45. User.create({ name: eventBody.name, email: eventBody.email, password: hash })
  46. // create the new user
  47. )
  48. .then(user => ({ auth: true, token: signToken(user._id) }));
  49. // sign the token and send it back
  50. }
Add Comment
Please, Sign In to add comment