Skip to content

Instantly share code, notes, and snippets.

@LeeWarnock
Forked from RunnerRick/.sails-and-passport.md
Created September 27, 2016 01:51
Show Gist options
  • Select an option

  • Save LeeWarnock/873aa18b59a94af7cd436b0eeb8c7443 to your computer and use it in GitHub Desktop.

Select an option

Save LeeWarnock/873aa18b59a94af7cd436b0eeb8c7443 to your computer and use it in GitHub Desktop.

Revisions

  1. Rick Roth revised this gist Aug 5, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion .sails-and-passport.md
    Original file line number Diff line number Diff line change
    @@ -13,6 +13,6 @@
    3. Merge `application.js` with `config/application.js`.
    4. Merge `policies.js` with `config/policies.js`.
    5. Merge `routes.js` with `config/routes.js`.
    6. Merge `authentication.js` with `api/policies/authenticated.js`.
    6. Merge `authenticated.js` with `api/policies/authenticated.js`.
    7. Create `api/controllers/AuthController.js`.
    8. **If you are using a traditional, server-generated UI, then** create `views/auth/login.ejs`
  2. Rick Roth revised this gist Aug 5, 2013. 1 changed file with 0 additions and 19 deletions.
    19 changes: 0 additions & 19 deletions authenticated.js
    Original file line number Diff line number Diff line change
    @@ -1,22 +1,3 @@
    // We use passport to determine if we're authenticated
    module.exports = function(req, res, next) {
    if (req.isAuthenticated()) {
    return next();
    }

    // If you are using a traditional, server-generated UI then uncomment out this code:
    /*
    res.redirect('/login');
    */

    // If you are using a single-page client-side architecture and will login via socket or Ajax, then uncomment out this code:
    /*
    res.status(401);
    res.end();
    */

    };

    // We use passport to determine if we're authenticated
    module.exports = function(req, res, next) {

  3. Rick Roth revised this gist Aug 5, 2013. 1 changed file with 39 additions and 0 deletions.
    39 changes: 39 additions & 0 deletions authenticated.js
    Original file line number Diff line number Diff line change
    @@ -16,3 +16,42 @@ module.exports = function(req, res, next) {
    */

    };

    // We use passport to determine if we're authenticated
    module.exports = function(req, res, next) {

    'use strict';

    // Sockets
    if(req.isSocket)
    {
    if(req.session &&
    req.session.passport &&
    req.session.passport.user)
    {
    return next();
    }

    res.json(401);
    }
    // HTTP
    else
    {
    if(req.isAuthenticated())
    {
    return next();
    }

    // If you are using a traditional, server-generated UI then uncomment out this code:
    /*
    res.redirect('/login');
    */

    // If you are using a single-page client-side architecture and will login via socket or Ajax, then uncomment out this code:
    /*
    res.status(401);
    res.end();
    */
    }

    };
  4. Rick Roth revised this gist Jul 18, 2013. 1 changed file with 8 additions and 0 deletions.
    8 changes: 8 additions & 0 deletions policies.js
    Original file line number Diff line number Diff line change
    @@ -3,6 +3,14 @@ module.exports.policies = {
    // see api/policies/authenticated.js
    '*': 'authenticated',

    // whitelist the home controller, so the client-side app can be sent down
    // If you are using a single-page client-side architecture, then uncomment out this code:
    /*
    'home': {
    '*': true
    },
    */

    // whitelist the auth controller
    'auth': {
    '*': true
  5. Rick Roth revised this gist Jul 18, 2013. 7 changed files with 115 additions and 170 deletions.
    32 changes: 14 additions & 18 deletions AuthController.js
    Original file line number Diff line number Diff line change
    @@ -1,44 +1,40 @@
    // api/controllers/AuthController.js
    /*jshint node:true */

    /*---------------------
    :: Auth
    -> controller
    ---------------------*/
    var passport = require('passport');

    var AuthController = {

    login: function (req,res)
    {
    login: function(req, res) {
    res.view();
    },

    process: function(req, res)
    {
    passport.authenticate('local', function(err, user, info)
    {
    if ((err) || (!user))
    {
    process: function(req, res) {
    passport.authenticate('local', function(err, user, info) {
    if ((err) || (!user)) {
    res.redirect('/login');
    return;
    }

    req.logIn(user, function(err)
    {
    if (err)
    {
    req.logIn(user, function(err) {
    if (err) {
    res.view();
    return;
    }

    res.redirect('/');
    return;
    });
    })(req, res);
    },

    logout: function (req,res)
    {
    logout: function(req, res) {
    req.logout();
    res.redirect('/');
    }

    };

    module.exports = AuthController;
    module.exports = AuthController;
    114 changes: 64 additions & 50 deletions application.js
    Original file line number Diff line number Diff line change
    @@ -1,30 +1,39 @@
    var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;
    var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy;

    // some static users
    var users = [
    { id: 1, username: 'bob', password: 'secret', email: '[email protected]' }
    , { id: 2, username: 'joe', password: 'birthday', email: '[email protected]' }
    ];
    var users = [{
    id: 1,
    username: 'bob',
    password: 'secret',
    email: '[email protected]'
    }, {
    id: 2,
    username: 'joe',
    password: 'birthday',
    email: '[email protected]'
    }];

    // helper functions


    function findById(id, fn) {
    var idx = id - 1;
    if (users[idx]) {
    fn(null, users[idx]);
    } else {
    fn(new Error('User ' + id + ' does not exist'));
    }
    var idx = id - 1;
    if (users[idx]) {
    fn(null, users[idx]);
    } else {
    fn(new Error('User ' + id + ' does not exist'));
    }
    }

    function findByUsername(username, fn) {
    for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    if (user.username === username) {
    return fn(null, user);
    }
    }
    return fn(null, null);
    for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    if (user.username === username) {
    return fn(null, user);
    }
    }
    return fn(null, null);
    }


    @@ -34,13 +43,13 @@ function findByUsername(username, fn) {
    // this will be as simple as storing the user ID when serializing, and finding
    // the user by ID when deserializing.
    passport.serializeUser(function(user, done) {
    done(null, user.id);
    done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
    findById(id, function (err, user) {
    done(err, user);
    });
    findById(id, function(err, user) {
    done(err, user);
    });
    });


    @@ -50,39 +59,44 @@ passport.deserializeUser(function(id, done) {
    // with a user object. In the real world, this would query a database;
    // however, in this example we are using a baked-in set of users.
    passport.use(new LocalStrategy(
    function(username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

    // Find the user by username. If there is no user with the given
    // username, or the password is not correct, set the user to `false` to
    // indicate failure and set a flash message. Otherwise, return the
    // authenticated `user`.
    findByUsername(username, function(err, user) {
    if (err) { return done(err); }
    if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
    if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
    return done(null, user);
    })
    });
    }
    ));

    // export

    function(username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function() {

    // Find the user by username. If there is no user with the given
    // username, or the password is not correct, set the user to `false` to
    // indicate failure and set a flash message. Otherwise, return the
    // authenticated `user`.
    findByUsername(username, function(err, user) {
    if (err) {
    return done(err);
    }
    if (!user) {
    return done(null, false, {
    message: 'Unknown user ' + username
    });
    }
    if (user.password != password) {
    return done(null, false, {
    message: 'Invalid password'
    });
    }
    return done(null, user);
    });
    });
    }));

    module.exports = {

    /* SNIP */

    // Custom express middleware - we use this to register the passport middleware
    // SNIP ...

    // Custom express middleware - we use this to register the passport middleware
    express: {
    customMiddleware: function(app)
    {
    customMiddleware: function(app) {
    app.use(passport.initialize());
    app.use(passport.session());
    }
    }

    /* SNIP */

    };
    };
    22 changes: 15 additions & 7 deletions authenticated.js
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,18 @@
    // api/policies/authenticated.js

    // We use passport to determine if we're authenticated
    module.exports = function(req, res, next)
    {
    if (req.isAuthenticated())
    module.exports = function(req, res, next) {
    if (req.isAuthenticated()) {
    return next();
    }

    // If you are using a traditional, server-generated UI then uncomment out this code:
    /*
    res.redirect('/login');
    */

    // If you are using a single-page client-side architecture and will login via socket or Ajax, then uncomment out this code:
    /*
    res.status(401);
    res.end();
    */

    res.redirect('/login')
    }
    };
    17 changes: 0 additions & 17 deletions login.ejs
    Original file line number Diff line number Diff line change
    @@ -1,17 +0,0 @@
    // views/auth/login.ejs


    <form action="/login" method="post">
    <div>
    <label>Username:</label>
    <input type="text" name="username"/><br/>
    </div>
    <div>
    <label>Password:</label>
    <input type="password" name="password"/>
    </div>
    <div>
    <input type="submit" value="Submit"/>
    </div>
    </form>
    <p><small>Hint - bob:secret</small></p>
    14 changes: 14 additions & 0 deletions login.ejs.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    <form action="/login" method="post">
    <div>
    <label>Username:</label>
    <input type="text" name="username"/>
    </div>
    <div>
    <label>Password:</label>
    <input type="password" name="password"/>
    </div>
    <div>
    <input type="submit" value="Submit"/>
    </div>
    </form>
    <p><small>Hint - bob:secret</small></p>
    18 changes: 5 additions & 13 deletions policies.js
    Original file line number Diff line number Diff line change
    @@ -1,18 +1,10 @@
    // config/policies.js

    /**
    * Policy defines middleware that is run before each controller/controller.
    * Any policy dropped into the /middleware directory is made globally available through sails.middleware
    * Below, use the string name of the middleware
    */
    module.exports.policies = {
    // default require authentication
    // see api/policies/authenticated.js
    // default require authentication
    // see api/policies/authenticated.js
    '*': 'authenticated',

    // whitelist the auth controller
    'auth':
    {
    // whitelist the auth controller
    'auth': {
    '*': true
    }
    };
    };
    68 changes: 3 additions & 65 deletions routes.js
    Original file line number Diff line number Diff line change
    @@ -1,79 +1,17 @@
    // Routes
    // *********************
    //
    // This table routes urls to controllers/actions.
    //
    // If the URL is not specified here, the default route for a URL is: /:controller/:action/:id
    // where :controller, :action, and the :id request parameter are derived from the url
    //
    // If :action is not specified, Sails will redirect to the appropriate action
    // based on the HTTP verb: (using REST/Backbone conventions)
    //
    // GET: /:controller/read/:id
    // POST: /:controller/create
    // PUT: /:controller/update/:id
    // DELETE: /:controller/destroy/:id
    //
    // If the requested controller/action doesn't exist:
    // - if a view exists ( /views/:controller/:action.ejs ), Sails will render that view
    // - if no view exists, but a model exists, Sails will automatically generate a
    // JSON API for the model which matches :controller.
    // - if no view OR model exists, Sails will respond with a 404.
    //
    module.exports.routes = {

    // To route the home page to the "index" action of the "home" controller:
    '/': {
    controller: 'home'
    },
    // SNIP ...

    // Custom routes for login:
    'get /login': {
    controller: 'auth',
    action: 'login'
    },

    'post /login': {
    controller: 'auth',
    action: 'process'
    }

    // If you want to set up a route only for a particular HTTP method/verb
    // (GET, POST, PUT, DELETE) you can specify the verb before the path:
    // 'post /signup': {
    // controller : 'user',
    // action : 'signup'
    // }
    // Keep in mind default routes exist for each of your controllers
    // So if you have a UserController with an action called "juggle"
    // a route will be automatically exist mapping it to /user/juggle.
    //
    // Additionally, unless you override them, new controllers will have
    // create(), find(), findAll(), update(), and destroy() actions,
    // and routes will exist for them as follows:
    /*
    // Standard RESTful routing
    // (if index is not defined, findAll will be used)
    'get /user': {
    controller : 'user',
    action : 'index'
    },
    'get /user/:id': {
    controller : 'user',
    action : 'find'
    },
    'post /user': {
    controller : 'user',
    action : 'create'
    },
    'put /user/:id': {
    controller : 'user',
    action : 'update'
    },
    'delete /user/:id': {
    controller : 'user',
    action : 'destroy'
    }
    */
    // SNIP ...
    };
  6. Rick Roth revised this gist Jul 18, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion .sails-and-passport.md
    Original file line number Diff line number Diff line change
    @@ -15,4 +15,4 @@
    5. Merge `routes.js` with `config/routes.js`.
    6. Merge `authentication.js` with `api/policies/authenticated.js`.
    7. Create `api/controllers/AuthController.js`.
    8. **If you are using a traditional server-generated UI, then** create `views/auth/login.ejs`
    8. **If you are using a traditional, server-generated UI, then** create `views/auth/login.ejs`
  7. Rick Roth revised this gist Jul 18, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion .sails-and-passport.md
    Original file line number Diff line number Diff line change
    @@ -15,4 +15,4 @@
    5. Merge `routes.js` with `config/routes.js`.
    6. Merge `authentication.js` with `api/policies/authenticated.js`.
    7. Create `api/controllers/AuthController.js`.
    8. *If you are using a traditional server-generated UI, then* create `views/auth/login.ejs`
    8. **If you are using a traditional server-generated UI, then** create `views/auth/login.ejs`
  8. Rick Roth revised this gist Jul 18, 2013. 2 changed files with 9 additions and 22 deletions.
    13 changes: 6 additions & 7 deletions .sails-and-passport.md
    Original file line number Diff line number Diff line change
    @@ -10,10 +10,9 @@
    #Steps#
    1. Create a new Sails application via `sails new <appName>`.
    2. Change your working directory to the root directory of the new Sails application via `cd <appName>`.
    3. Create an Ember application with Ember Tools via `create-ember.sh`.
    4. Unzip the Twitter Bootstrap package into `./bootstrap`.
    5. Copy the Twitter Bootstrap code to various locations via `integrate-bootstrap.sh`.
    5. Modify `./views/layout.ejs`.
    6. Modify `./ember/js/config/app.js` to require Bootstrap.
    7. Build the Ember application via `build-ember.sh`.
    8. Start the Sails application via `sails lift`.
    3. Merge `application.js` with `config/application.js`.
    4. Merge `policies.js` with `config/policies.js`.
    5. Merge `routes.js` with `config/routes.js`.
    6. Merge `authentication.js` with `api/policies/authenticated.js`.
    7. Create `api/controllers/AuthController.js`.
    8. *If you are using a traditional server-generated UI, then* create `views/auth/login.ejs`
    18 changes: 3 additions & 15 deletions application.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,3 @@
    // config/application.js

    var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;

    @@ -74,19 +72,7 @@ passport.use(new LocalStrategy(

    module.exports = {

    // Name of the application (used as default <title>)
    appName: "Sails Application",

    // Port this Sails application will live on
    port: 1337,

    // The environment the app is deployed in
    // (`development` or `production`)
    //
    // In `production` mode, all css and js are bundled up and minified
    // And your views and templates are cached in-memory. Gzip is also used.
    // The downside? Harder to debug, and the server takes longer to start.
    environment: 'development',
    /* SNIP */

    // Custom express middleware - we use this to register the passport middleware
    express: {
    @@ -97,4 +83,6 @@ module.exports = {
    }
    }

    /* SNIP */

    };
  9. Rick Roth revised this gist Jul 18, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions .sails-and-passport.md
    Original file line number Diff line number Diff line change
    @@ -4,8 +4,8 @@
    * Twitter Bootstrap (See http://twitter.github.io/bootstrap/index.html)
    * Passport.js (See http://passportjs.org)
    * `npm install passport`
    * `npm install passport-local`
    <small>Probably could express this as package.json</small>
    * `npm install passport-local`
    (Probably could express this as `package.json`)

    #Steps#
    1. Create a new Sails application via `sails new <appName>`.
  10. Rick Roth revised this gist Jul 18, 2013. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions .sails-and-passport.md
    Original file line number Diff line number Diff line change
    @@ -5,6 +5,7 @@
    * Passport.js (See http://passportjs.org)
    * `npm install passport`
    * `npm install passport-local`
    <small>Probably could express this as package.json</small>

    #Steps#
    1. Create a new Sails application via `sails new <appName>`.
  11. Rick Roth revised this gist Jul 18, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion .sails-and-passport.md
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@
    * Twitter Bootstrap (See http://twitter.github.io/bootstrap/index.html)
    * Passport.js (See http://passportjs.org)
    * `npm install passport`
    * `npm install passport-'ocal`
    * `npm install passport-local`

    #Steps#
    1. Create a new Sails application via `sails new <appName>`.
  12. Rick Roth revised this gist Jul 18, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions .sails-and-passport.md
    Original file line number Diff line number Diff line change
    @@ -3,8 +3,8 @@
    * Ember Tools (See https://github.com/rpflorence/ember-tools)
    * Twitter Bootstrap (See http://twitter.github.io/bootstrap/index.html)
    * Passport.js (See http://passportjs.org)
    ** `npm install passport`
    ** `npm install passport-'ocal`
    * `npm install passport`
    * `npm install passport-'ocal`

    #Steps#
    1. Create a new Sails application via `sails new <appName>`.
  13. Rick Roth renamed this gist Jul 18, 2013. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  14. Rick Roth revised this gist Jul 18, 2013. 1 changed file with 18 additions and 1 deletion.
    19 changes: 18 additions & 1 deletion .sails-and-passport
    Original file line number Diff line number Diff line change
    @@ -1 +1,18 @@
    .
    #Prerequisites#
    * Sails.js (See https://github.com/balderdashy/sails)
    * Ember Tools (See https://github.com/rpflorence/ember-tools)
    * Twitter Bootstrap (See http://twitter.github.io/bootstrap/index.html)
    * Passport.js (See http://passportjs.org)
    ** `npm install passport`
    ** `npm install passport-'ocal`

    #Steps#
    1. Create a new Sails application via `sails new <appName>`.
    2. Change your working directory to the root directory of the new Sails application via `cd <appName>`.
    3. Create an Ember application with Ember Tools via `create-ember.sh`.
    4. Unzip the Twitter Bootstrap package into `./bootstrap`.
    5. Copy the Twitter Bootstrap code to various locations via `integrate-bootstrap.sh`.
    5. Modify `./views/layout.ejs`.
    6. Modify `./ember/js/config/app.js` to require Bootstrap.
    7. Build the Ember application via `build-ember.sh`.
    8. Start the Sails application via `sails lift`.
  15. Rick Roth revised this gist Jul 17, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion .sails-and-passport
    Original file line number Diff line number Diff line change
    @@ -1 +1 @@
    #
    .
  16. Rick Roth revised this gist Jul 17, 2013. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions .sails-and-passport
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    #
  17. Rick Roth revised this gist Jul 15, 2013. 1 changed file with 7 additions and 2 deletions.
    9 changes: 7 additions & 2 deletions routes.js
    Original file line number Diff line number Diff line change
    @@ -27,10 +27,15 @@ module.exports.routes = {
    controller: 'home'
    },

    // Custom route for login:
    '/login': {
    // Custom routes for login:
    'get /login': {
    controller: 'auth',
    action: 'login'
    },

    'post /login': {
    controller: 'auth',
    action: 'process'
    }

    // If you want to set up a route only for a particular HTTP method/verb
  18. Rick Roth revised this gist Jul 15, 2013. 1 changed file with 74 additions and 0 deletions.
    74 changes: 74 additions & 0 deletions routes.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,74 @@
    // Routes
    // *********************
    //
    // This table routes urls to controllers/actions.
    //
    // If the URL is not specified here, the default route for a URL is: /:controller/:action/:id
    // where :controller, :action, and the :id request parameter are derived from the url
    //
    // If :action is not specified, Sails will redirect to the appropriate action
    // based on the HTTP verb: (using REST/Backbone conventions)
    //
    // GET: /:controller/read/:id
    // POST: /:controller/create
    // PUT: /:controller/update/:id
    // DELETE: /:controller/destroy/:id
    //
    // If the requested controller/action doesn't exist:
    // - if a view exists ( /views/:controller/:action.ejs ), Sails will render that view
    // - if no view exists, but a model exists, Sails will automatically generate a
    // JSON API for the model which matches :controller.
    // - if no view OR model exists, Sails will respond with a 404.
    //
    module.exports.routes = {

    // To route the home page to the "index" action of the "home" controller:
    '/': {
    controller: 'home'
    },

    // Custom route for login:
    '/login': {
    controller: 'auth',
    action: 'login'
    }

    // If you want to set up a route only for a particular HTTP method/verb
    // (GET, POST, PUT, DELETE) you can specify the verb before the path:
    // 'post /signup': {
    // controller : 'user',
    // action : 'signup'
    // }
    // Keep in mind default routes exist for each of your controllers
    // So if you have a UserController with an action called "juggle"
    // a route will be automatically exist mapping it to /user/juggle.
    //
    // Additionally, unless you override them, new controllers will have
    // create(), find(), findAll(), update(), and destroy() actions,
    // and routes will exist for them as follows:
    /*
    // Standard RESTful routing
    // (if index is not defined, findAll will be used)
    'get /user': {
    controller : 'user',
    action : 'index'
    },
    'get /user/:id': {
    controller : 'user',
    action : 'find'
    },
    'post /user': {
    controller : 'user',
    action : 'create'
    },
    'put /user/:id': {
    controller : 'user',
    action : 'update'
    },
    'delete /user/:id': {
    controller : 'user',
    action : 'destroy'
    }
    */
    };
  19. @theangryangel theangryangel created this gist Feb 28, 2013.
    44 changes: 44 additions & 0 deletions AuthController.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    // api/controllers/AuthController.js

    var passport = require('passport');

    var AuthController = {

    login: function (req,res)
    {
    res.view();
    },

    process: function(req, res)
    {
    passport.authenticate('local', function(err, user, info)
    {
    if ((err) || (!user))
    {
    res.redirect('/login');
    return;
    }

    req.logIn(user, function(err)
    {
    if (err)
    {
    res.view();
    return;
    }

    res.redirect('/');
    return;
    });
    })(req, res);
    },

    logout: function (req,res)
    {
    req.logout();
    res.redirect('/');
    }

    };

    module.exports = AuthController;
    100 changes: 100 additions & 0 deletions application.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,100 @@
    // config/application.js

    var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;

    // some static users
    var users = [
    { id: 1, username: 'bob', password: 'secret', email: '[email protected]' }
    , { id: 2, username: 'joe', password: 'birthday', email: '[email protected]' }
    ];

    // helper functions
    function findById(id, fn) {
    var idx = id - 1;
    if (users[idx]) {
    fn(null, users[idx]);
    } else {
    fn(new Error('User ' + id + ' does not exist'));
    }
    }

    function findByUsername(username, fn) {
    for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    if (user.username === username) {
    return fn(null, user);
    }
    }
    return fn(null, null);
    }


    // Passport session setup.
    // To support persistent login sessions, Passport needs to be able to
    // serialize users into and deserialize users out of the session. Typically,
    // this will be as simple as storing the user ID when serializing, and finding
    // the user by ID when deserializing.
    passport.serializeUser(function(user, done) {
    done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
    findById(id, function (err, user) {
    done(err, user);
    });
    });


    // Use the LocalStrategy within Passport.
    // Strategies in passport require a `verify` function, which accept
    // credentials (in this case, a username and password), and invoke a callback
    // with a user object. In the real world, this would query a database;
    // however, in this example we are using a baked-in set of users.
    passport.use(new LocalStrategy(
    function(username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

    // Find the user by username. If there is no user with the given
    // username, or the password is not correct, set the user to `false` to
    // indicate failure and set a flash message. Otherwise, return the
    // authenticated `user`.
    findByUsername(username, function(err, user) {
    if (err) { return done(err); }
    if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
    if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
    return done(null, user);
    })
    });
    }
    ));

    // export

    module.exports = {

    // Name of the application (used as default <title>)
    appName: "Sails Application",

    // Port this Sails application will live on
    port: 1337,

    // The environment the app is deployed in
    // (`development` or `production`)
    //
    // In `production` mode, all css and js are bundled up and minified
    // And your views and templates are cached in-memory. Gzip is also used.
    // The downside? Harder to debug, and the server takes longer to start.
    environment: 'development',

    // Custom express middleware - we use this to register the passport middleware
    express: {
    customMiddleware: function(app)
    {
    app.use(passport.initialize());
    app.use(passport.session());
    }
    }

    };
    10 changes: 10 additions & 0 deletions authenticated.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    // api/policies/authenticated.js

    // We use passport to determine if we're authenticated
    module.exports = function(req, res, next)
    {
    if (req.isAuthenticated())
    return next();

    res.redirect('/login')
    }
    17 changes: 17 additions & 0 deletions login.ejs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    // views/auth/login.ejs


    <form action="/login" method="post">
    <div>
    <label>Username:</label>
    <input type="text" name="username"/><br/>
    </div>
    <div>
    <label>Password:</label>
    <input type="password" name="password"/>
    </div>
    <div>
    <input type="submit" value="Submit"/>
    </div>
    </form>
    <p><small>Hint - bob:secret</small></p>
    18 changes: 18 additions & 0 deletions policies.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    // config/policies.js

    /**
    * Policy defines middleware that is run before each controller/controller.
    * Any policy dropped into the /middleware directory is made globally available through sails.middleware
    * Below, use the string name of the middleware
    */
    module.exports.policies = {
    // default require authentication
    // see api/policies/authenticated.js
    '*': 'authenticated',

    // whitelist the auth controller
    'auth':
    {
    '*': true
    }
    };