Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. /**
  2. * User Registration
  3. * Sends a response object with success true if user was registered.
  4. * Sends a response object with success false if user couldn't be registered.
  5. */
  6. router.post('/', function(req, res, next) {
  7. var userInfo = req.body;
  8.  
  9. userInfo.email = sanitize(userInfo.email);
  10. userInfo.password = sanitize(userInfo.password);
  11.  
  12. if(!validEmail(userInfo.email) || !validPassword(userInfo.password)) { //If the request info is invalid
  13. sendJsonResponse(res, false, error, 400);
  14. }
  15. else {
  16. //Check if e-mail already exists
  17. User.find({email: userInfo.email}, function(err, docs) {
  18. if(err) {
  19. console.log(err);
  20. sendJsonResponse(res, false, "There was an error processing your request.", 400);
  21. }
  22. else if(docs.length > 0) { //If e-mail was found in database, generate error
  23. sendJsonResponse(res, false, "This e-mail already exists, please login or use another e-mail.", 409);
  24. }
  25. else {
  26. //Create user based on data submitted.
  27. var user = new User({email: sanitize(userInfo.email), password: bcrypt.hashSync(sanitize(userInfo.password), 10), permission_level: 'REGULAR'});
  28.  
  29. //Save it in the database.
  30. user.save(function (err) {
  31. if (err) {
  32. sendJsonResponse(res, false, "There was an error processing your request.", 400);
  33. }
  34. else { //If everything is fine
  35.  
  36. //Create token to login the registered user
  37. var token = jwt.sign(user, config.secret, {
  38. expiresIn: '24h' // expires in 24 hours
  39. });
  40.  
  41. sendJsonResponse(res, true, "You have been registered!", 200, token);
  42. }
  43. });
  44. }
  45. });
  46. }
  47. error = "";
  48. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement