text: var request = require('request');
  
  /**
   * Authentication Controller
   *
   * This is merely meant as an example of how your Authentication controller
   * should look. It currently includes the minimum amount of functionality for
   * the basics of Passport.js to work.
   */
  var AuthController = {
  
    /**
     * Log out a user and return them to the homepage
     *
     * Passport exposes a logout() function on req (also aliased as logOut()) that
     * can be called from any route handler which needs to terminate a login
     * session. Invoking logout() will remove the req.user property and clear the
     * login session (if any).
     *
     * For more information on logging out users in Passport.js, check out:
     * http://passportjs.org/guide/logout/
     *
     * @param {Object} req
     * @param {Object} res
     */
    logout: function (req, res) {
      req.logout();
  
      // mark the user as logged out for auth purposes
      req.session.authenticated = false;
  
      res.redirect('/');
    },
  
    /**
     * Create a third-party authentication endpoint
     *
     * @param {Object} req
     * @param {Object} res
     */
    provider: function (req, res) {
      // If token present, override oauth login
      if (process.env.TEST_AUTH && process.env.GITHUB_TOKEN) {
        request.get({
          url: 'https://api.github.com/user?access_token=' +
            process.env.GITHUB_TOKEN,
          json: true,
          headers: {
            'User-Agent': 'request'
          }
        }, function(err, clientReq, ghUser) {
          var record = { username: ghUser.login };
          User.findOrCreate(record, record, function(err, user) {
            if (err) return res.badRequest('Unable to log in with token');
            user = user.length ? user[0] : user;
            Passport.create({
              identifier: ghUser.id,
              protocol: 'oauth2',
              tokens: { accessToken: process.env.GITHUB_TOKEN },
              provider: 'github',
              user: user.id
            }, function(err, passport) {
              if (err) return res.badRequest('Unable to log in with token');
              user.passport = [passport];
              req.login(user, function (err) {
                if (err) return res.badRequest('Unable to log in with token');
                req.session.authenticated = true;
                res.redirect('/');
              });
            });
          });
        });
      } else {
        passport.endpoint(req, res);
      }
    },
  
    /**
     * Create a authentication callback endpoint
     *
     * This endpoint handles everything related to creating and verifying Pass-
     * ports and users, both locally and from third-aprty providers.
     *
     * Passport exposes a login() function on req (also aliased as logIn()) that
     * can be used to establish a login session. When the login operation
     * completes, user will be assigned to req.user.
     *
     * For more information on logging in users in Passport.js, check out:
     * http://passportjs.org/guide/login/
     *
     * @param {Object} req
     * @param {Object} res
     */
    callback: function (req, res) {
      function tryAgain (err) {
  
        if (err) sails.log.error(err);
  
        // Only certain error messages are returned via req.flash('error', someError)
        // because we shouldn't expose internal authorization errors to the user.
        // We do return a generic error and the original request body.
        var flashError = req.flash('error')[0],
            queryParam;
  
        if (err && err.message === 'Unauthorized') {
          req.flash('error', 'Error.Passport.Unauthorized');
        } else if (err && !flashError) {
          req.flash('error', 'Error.Passport.Generic');
        } else if (flashError) {
          req.flash('error', flashError);
        }
  
        queryParam = req.flash('error')[0];
        if (queryParam) queryParam = '?error=' + queryParam;
  
        // If an error was thrown, redirect the user to the
        // login, register or disconnect action initiator view.
        // These views should take care of rendering the error messages.
        var action = req.param('action');
  
        switch (action) {
          case 'register':
            res.redirect('/register' + queryParam);
            break;
          case 'disconnect':
            res.redirect('back');
            break;
          default:
            res.redirect('/' + queryParam);
        }
      }
  
      passport.callback(req, res, function (err, user, challenges, statuses) {
        if (err) return tryAgain(err);
        if (!user) return tryAgain(challenges);
  
        req.login(user, function (err) {
          if (err) {
            return tryAgain(err);
          }
  
          // Mark the session as authenticated to work with default Sails sessionAuth.js policy
          req.session.authenticated = true;
  
          // Upon successful login, send the user to the homepage were req.user
          // will be available.
          res.redirect('/');
        });
      });
    },
  
    /**
     * Disconnect a passport from a user
     *
     * @param {Object} req
     * @param {Object} res
     */
    disconnect: function (req, res) {
      passport.disconnect(req, res);
    }
  };
  
  module.exports = AuthController;
  