Advertisement
kushaldsouza

UsersController

Feb 22nd, 2014
795
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * UsersController
  3.  *
  4.  * @module      :: Controller
  5.  * @description :: A set of functions called `actions`.
  6.  *
  7.  *                 Actions contain code telling Sails how to respond to a certain type of request.
  8.  *                 (i.e. do stuff, then send some JSON, show an HTML page, or redirect to another URL)
  9.  *
  10.  *                 You can configure the blueprint URLs which trigger these actions (`config/controllers.js`)
  11.  *                 and/or override them with custom routes (`config/routes.js`)
  12.  *
  13.  *                 NOTE: The code you write here supports both HTTP and Socket.io automatically.
  14.  *
  15.  * @docs        :: http://sailsjs.org/#!documentation/controllers
  16.  */
  17.  
  18. var UsersController = {
  19.  
  20.   /*
  21.    * Function that lists all the users currently registered
  22.    */
  23.   index: function( req, res ) {
  24.     res.locals.user = _.clone( req.session.user )
  25.     var usersList = {};
  26.     Users.find().exec( function( err, users ) {
  27.         usersList = users;
  28.         return res.view({users: usersList});
  29.     });
  30.   },
  31.  
  32.   /*
  33.    * Function that handles the singup page
  34.    */
  35.   signup: function( req, res ) {
  36.     res.locals.user = _.clone( req.session.user )
  37.     // Get errors from session flash
  38.     res.locals.flash = _.clone(req.session.flash);
  39.     req.session.flash = {};
  40.     var errorsList = {};
  41.     // Check if there are any validation errors and pass these to the form
  42.     if ( res.locals.flash && res.locals.flash.err && res.locals.flash.err.ValidationError )
  43.     {
  44.         errorsList = res.locals.flash.err.ValidationError;
  45.         return res.view({errors: errorsList, data:res.locals.flash.data});
  46.     } else {
  47.         return res.view({errors: false});
  48.     }
  49.     // Reset flash variables
  50.     req.session.flash = {};
  51.   },
  52.  
  53.   /*
  54.    * Function that creates a new user
  55.    */
  56.   create: function( req, res, next ) {
  57.     res.locals.user = _.clone( req.session.user )
  58.     var formData = {
  59.         firstName: req.body.firstName,
  60.         lastName: req.body.lastName,
  61.         email: req.body.email
  62.     };
  63.  
  64.     Users.create( req.params.all(), function userCreated( err, user ) {
  65.       if( err )
  66.       {
  67.  
  68.         // Handle duplicate email
  69.         if (err.code == 11000) {
  70.           if (err.ValidationError) {
  71.             err.ValidationError.email = true;
  72.           } else {
  73.             err.ValidationError = {
  74.               email: true
  75.             }
  76.           }
  77.         }
  78.  
  79.         console.log( err );
  80.           req.session.flash = {
  81.               err: err,
  82.               data:formData
  83.           };
  84.         return res.redirect('Users/signup');
  85.       }
  86.       return res.redirect("Users/index");
  87.       req.session.flash = {};
  88.     });
  89.   },
  90.  
  91.   /**
  92.    * Function that handles the login page
  93.    * @param  {[type]}   req  [description]
  94.    * @param  {[type]}   res  [description]
  95.    * @param  {Function} next [description]
  96.    * @return {[type]}        [description]
  97.    */
  98.   login: function( req, res ) {
  99.  
  100.     // Check if user has already been authenticated
  101.     if( !req.session.user ) {
  102.  
  103.       res.locals.flash = _.clone( req.session.flash );
  104.       req.session.flash = {};
  105.  
  106.       // Check for any errors
  107.       if ( res.locals.flash && res.locals.flash.err && res.locals.flash.err.ValidationError ) {
  108.        
  109.         errorsList = res.locals.flash.err.ValidationError;
  110.         return res.view({errors: errorsList, data:res.locals.flash.data});
  111.      
  112.       } else if( res.locals.flash && res.locals.flash.err && res.locals.flash.err.ServerError ) {
  113.        
  114.         errorsList = {
  115.           ServerError: res.locals.flash.err.ServerError
  116.         };
  117.  
  118.         if ( !res.locals.flash.data ) {
  119.           res.locals.flash.data = {
  120.             email: "",
  121.             password: ""
  122.           };
  123.         }
  124.         return res.view({errors: errorsList, data:res.locals.flash.data});
  125.      
  126.       } else {
  127.         return res.view({errors: false});
  128.       }
  129.     } else {
  130.       res.locals.user = _.clone( req.session.user )
  131.       return res.redirect( "Users/index" );
  132.     }
  133.  
  134.     // Reset flash variables
  135.     req.session.flash = {};
  136.   },
  137.  
  138.   /**
  139.    * Function that authenticates a user
  140.    * @param  {[type]} req [description]
  141.    * @param  {[type]} res [description]
  142.    * @return {[type]}     [description]
  143.    */
  144.   authenticate: function( req, res ) {
  145.     var bcrypt = require('bcrypt');
  146.  
  147.     // Get the form data
  148.     var formData = {
  149.       email: req.body.email
  150.     };
  151.  
  152.     // Check for form validation errors
  153.     var formErrors = {
  154.       containsErrors: false
  155.     };
  156.  
  157.     if( req.body.email == "" ) {
  158.       formErrors.containsErrors = true;
  159.       formErrors.email = true;
  160.     }
  161.  
  162.     if( req.body.password == "" ) {
  163.       formErrors.containsErrors = true;
  164.       formErrors.password = true;
  165.     }
  166.  
  167.     if( formErrors.containsErrors )
  168.     {
  169.       req.session.flash = {
  170.           err: {
  171.             ValidationError: formErrors
  172.           },
  173.           data:formData
  174.       };
  175.       return res.redirect('Users/login');
  176.     }
  177.  
  178.     // Try to retrieve the user
  179.     Users.findOneByEmail( req.body.email ).done( function ( err, user ) {
  180.  
  181.       if ( err ) {
  182.         req.session.flash = {
  183.           err: {
  184.             ServerError: "DB Error"
  185.           },
  186.           data: formData
  187.         };
  188.         return res.redirect('Users/login');
  189.       }
  190.  
  191.       if ( user ) {
  192.         bcrypt.compare( req.body.password, user.password, function ( err, match ) {
  193.           if ( err ) {
  194.             req.session.flash = {
  195.               err: {
  196.                 ServerError: "Server error"
  197.               },
  198.               data: formData
  199.             };
  200.             return res.redirect('Users/login');
  201.           }
  202.  
  203.           if ( match ) {
  204.             // password match
  205.             var sessionUser = {
  206.               firstName: user.firstName,
  207.               lastName: user.lastName,
  208.               email: user.email
  209.             }
  210.             req.session.user = sessionUser;
  211.             req.session.authenticated = true;
  212.             return res.redirect('Users/index');
  213.           } else {
  214.             // invalid password
  215.             if ( req.session.user ) req.session.user = null;
  216.             req.session.flash = {
  217.               err: {
  218.                 ServerError: "Invalid password"
  219.               },
  220.               data: formData
  221.             };
  222.             return res.redirect('Users/login');
  223.           }
  224.         });
  225.       } else {
  226.         req.session.flash = {
  227.           err: {
  228.             ServerError: "User not found"
  229.           },
  230.           data: formData
  231.         };
  232.         return res.redirect('Users/login');
  233.       }
  234.  
  235.       // Reset the flash variables
  236.       req.session.flash = {};
  237.  
  238.     });
  239.   }
  240. }
  241. module.exports = UsersController;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement