policies.js 2.2 KB

// app - policies

var connectEnsureLogin = require('connect-ensure-login');
// var auth = require('basic-auth');
var _ = require('underscore');

exports = module.exports = function(IoC, User) {

  // policy/middleware helpers
   var ensureLoggedIn = connectEnsureLogin.ensureLoggedIn;
  // var ensureLoggedOut = connectEnsureLogin.ensureLoggedOut;

  // since there are issues with `passport-http` right now
  // this is implemented as a temporary solution
  function ensureApiToken(req, res, next) {
    // var creds = auth(req);

    // if (!creds || !_.isString(creds.name)) {
    //   res.statusCode = 401;
    //   return next({
    //     message: 'API token missing',
    //     param: 'username'
    //   });
    // }

    // User.findOne({
    //   api_token: creds.name
    // }, function(err, user) {
    //   if (err) return next(err);
    //   if (!user) {
    //     return next({
    //       message: 'Invalid API token provided',
    //       param: 'username'
    //     });
    //   }
    //   req.user = user;
    //   next();
    // });
    if(req.session.passport&&req.session.passport.user&&req.session.passport.user.token)
      next();
    else{
      res.statusCode = 401;
      return next({ message: 'API token missing',param: 'username'});
    }

  }

  function ensureLoggedOut(options){
    if (typeof options == 'string') {
      options = { redirectTo: options }
    }
    options = options || {};
    
    var url = options.redirectTo || '/signIn';
    var setReturnTo = (options.setReturnTo === undefined) ? true : options.setReturnTo;
    return function(req, res, next) { 
      if (!(req.session.passport&&req.session.passport.user&&req.session.passport.user.token)) {
        if (setReturnTo && req.session) {
          req.session.returnTo = req.originalUrl || req.url;
        } 
        res.statusCode=302;
        return res.send({redirect:'/'}); 
        // return res.redirect(url);
      }
      next();
    }
  }


  var policies = {
    ensureLoggedIn: ensureLoggedIn,
    ensureLoggedOut: ensureLoggedOut,
    ensureApiToken: ensureApiToken,
    notApiRouteRegexp: /^(?!\/__webpack_hmr\/)|(?!\/*.ico).*$/
  };

  return policies;

};

exports['@singleton'] = true;
exports['@require'] = [ '$container', 'models/user' ];