Guest User

Untitled

a guest
Nov 16th, 2017
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. /**
  2. * POST /signup
  3. * Create a new local account.
  4. */
  5.  
  6. // TODO: if you try existing email and exist. username, this will trigger an errors
  7. // Error: Can't set headers after they are sent.
  8. // not sure why this happens, it works sometimes
  9.  
  10.  
  11. exports.postSignup = (req, res, next) => {
  12. req.assert('email', 'Email is not valid').isEmail();
  13. req.check('username', 'username must be 6-50 lower case characters, only letters and numbers, no spaces allowed.').isAlphanumeric().isLowercase().len(6);
  14. req.sanitize('email').normalizeEmail({
  15. gmail_remove_dots: false
  16. });
  17.  
  18. const errors = req.validationErrors();
  19.  
  20. if (errors) {
  21. req.flash('errors', errors);
  22. return res.redirect('/signup');
  23. }
  24.  
  25. const user = new User({
  26. email: req.body.email,
  27. username: req.body.username,
  28. // password: req.body.password
  29. });
  30.  
  31. User.findOne({
  32. email: req.body.email
  33. }, (err, existingEmail) => {
  34. if (err) {
  35. return next(err);
  36. }
  37. if (existingEmail) {
  38. req.flash('errors', {
  39. msg: 'Account with that email address already exists.'
  40. });
  41. return res.redirect('/signup');
  42. } else {
  43. User.findOne({
  44. username: req.body.username
  45. }, (err, existingUser) => {
  46. if (err) {
  47. return next(err);
  48. }
  49. if (existingUser) {
  50. req.flash('errors', {
  51. msg: 'Account with that username name already exists.'
  52. });
  53. return res.redirect('/signup');
  54. } else { // if here... then unique email and unique username, so save it
  55.  
  56. user.save((err) => {
  57. if (err) {
  58. return next(err);
  59. }
  60. req.logIn(user, (err) => {
  61. if (err) {
  62. return next(err);
  63. }
  64. // doesn't wokr either res.redirect('/account');
  65. return res.redirect('/account');
  66. // res.redirect('/account');
  67. });
  68. }); // end user.save function
  69. } // end else if existing user
  70. }); // end User.findOne username
  71. } // end else existing email
  72. }); // end User.findOne email
  73.  
  74.  
  75.  
  76. }; // end main func.
Add Comment
Please, Sign In to add comment