使用connect-roles& amp;设置管理员角色Passport.JS

时间:2016-02-23 15:42:53

标签: javascript node.js express passport.js

我目前正在尝试设置管理员角色,以便使用以下文档访问简单的管理页面:connect-roles

我一直在猛烈抨击它一段时间而且我仍然对如何设置角色感到迷茫EG现在正在从DB中提取管理员值并暂时将其存储在全局变量中但是我不知道如何使用连接角色说只允许访问特定用户的管理页面。

任何人都可以澄清或展示如何执行此操作的示例/一些指导,因为我的文档只有在用户是管理员的情况下才能帮助我确保访问网页?

Ave发布了一些代码,显示了目前的样子。

代码

var admin = 'Admin';
var mysql = require('mysql');
var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '',
    database : 'test'
  });
var passport = require('passport');
var ConnectRoles = require('connect-roles');
var roles = new ConnectRoles();
var passportLocal = require('passport-local');


  app.use(passport.initialize());
  app.use(passport.session());
  app.use(roles.middleware());

  passport.use(new passportLocal.Strategy(function (username, password, done) {
      connection.query({
        sql : 'SELECT * from `userman_users` WHERE `username`= ?AND`password` = sha1(?)',
        timeout : 40000, // 40s
        values : [username, password]
      }, function (error, results, rows) {
        if (results.length > 0) {
          response = "Success";
        } else {
          console.log('Error while performing Query.');
          response = "Failed";
        }
        if (response === "Success") {
          done(null, {
            id : username
          });
        } else if (response === "Failed") {
          done(null, null);
        }
      });

    })
  );

  passport.serializeUser(function (user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function (id, done) {
    done(null, {
      id : id
    });
  });

roles.use(function (req, action) {
  if (!req.isAuthenticated()) return action === 'access home page';
})

roles.use(function (req) {
  if (req.user.role === 'admin') {
    return true;
  }
});

  app.get('/', redirectToIndexIfLoggedIn, function (req, res) {
    res.render('login');
  });

  app.get('/index', checkLoggedIn, function (req, res) {
    res.render('index', {
      isAuthenticated : req.isAuthenticated(),
      user : req.user
    });
  });

app.get('/admin', user.can('access admin page'), function (req, res) {
  res.render('admin');
});

  function checkLoggedIn(req, res, next) {
    if (req.isAuthenticated())
      return next();
    res.redirect('/');
  }

3 个答案:

答案 0 :(得分:5)

这是一个例子:

var express = require('express');
...
var passport = require('passport');
var LocalStrategy = require('passport-local');
var ConnectRoles = require('connect-roles');

...
var app = express();

//===============PASSPORT=================

// Passport session setup.
passport.serializeUser(function(user, done) {
  console.log("serializing " + user.username);
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  console.log("deserializing " + obj);
  // simulate an admin user
  obj.role = obj.username == 'admin' ? 'admin' : 'user';
  done(null, obj);
});

...

//===============CONNECTION RULES=================

var user = new ConnectRoles({
  failureHandler: function (req, res, action) {
    // optional function to customise code that runs when
    // user fails authorisation
    var accept = req.headers.accept || '';
    res.status(403);
    if (~accept.indexOf('html')) {
      res.render('access-denied', {action: action});
    } else {
      res.send('Access Denied - You don\'t have permission to: ' + action);
    }
  }
});


...
app.use(passport.initialize());
app.use(passport.session());
app.use(user.middleware());


//anonymous users can only access the home page
//returning false stops any more rules from being
//considered
user.use(function (req, action) {
  if (!req.isAuthenticated()) return action === 'access home page';
});

//users logged can access to public pages
user.use(function(req, action){
    if(req.isAuthenticated() && action != 'access private page' && action != 'access admin page')
      return true;
});

//moderator users can access private page, but
//they might not be the only ones so we don't return
//false if the user isn't a moderator
user.use('access private page', function (req) {
  console.log('access private page');
  if (req.user.role === 'moderator') {
    return true;
  }
});

//admin users can access all pages
user.use(function (req) {
  if (req.user.role === 'admin') {
    return true;
  }
});


...


/* GET home page. */
app.get('/', user.can('access home page'), function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//displays our signup page
app.get('/signin', function(req, res){
  res.render('signin');
});

//sends the request through our local signup strategy, and if successful takes     user to homepage, otherwise returns then to signin page
app.post('/local-reg', passport.authenticate('local-signup', {
  successRedirect: '/',
  failureRedirect: '/signin'
  })
);

//sends the request through our local login/signin strategy, and if successful    takes user to homepage, otherwise returns then to signin page
app.post('/login', passport.authenticate('local-signin', {
    successRedirect: '/',
    failureRedirect: '/signin'
  })
);

// Simple route middleware to ensure user is authenticated.
app.use(function(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
      req.session.error = 'Please sign in!';
      res.redirect('/signin');
});

//logs user out of site, deleting them from the session, and returns to homepage
app.get('/logout', function(req, res){
  var name = req.user.username;
  console.log("LOGGIN OUT " + req.user.username)
  req.logout();
  res.redirect('/');
  req.session.notice = "You have successfully been logged out " + name + "!";
});

app.get('/private', user.can('access private page'), function (req, res) {
  res.render('private');
});

app.get('/admin', user.can('access admin page'), function (req, res) {
  res.render('admin');
});


app.use('/users', users);

....


module.exports = app;

使用connect-rules定义要使用的规则(在本例中为user.use)。如果将操作作为第一个参数传递,则仅在函数中传递的操作等于该操作时才使用策略。然后,在user.can传递action的路径中触发规则。在此示例中,我定义了一个额外的过滤策略,以授予对已记录用户的访问权限,并请求未标记adminmoderator权限的路由,例如

/* GET home page. */
app.get('/', user.can('access home page'), function(req, res, next) {
  res.render('index', { title: 'Express' });
});

用户登录后,如果用户不是adminmoderator,我们需要采用其他策略。

答案 1 :(得分:2)

你可以使用像sailsJS和npm模块sails-generate-auth

这样的框架

设置完成后,使用您自己的中间件阻止路由

//allow admin only  localhost:PORT/admin at policies.js
'admin': ['passport', 'sessionAuth', 'isAdmin'],
'*': ['passport', 'sessionAuth'],


//isAdmin policy
module.exports = function(req, res, next) {
// User is allowed, proceed to the next policy, 
// or if this is the last policy, the controller
if (req.user.role == 'admin') {
    return next();
}

// User is not allowed
return res.forbidden('You are not permitted to perform this action.');
};

答案 2 :(得分:1)

使用以下逻辑,我可以根据DB中的值获得管理功能:

app.get('/admin', function (req, res) {
        connection.query({
            sql : 'SELECT role from `auth_users` WHERE `username`= ?',
            timeout : 40000, // 40s
            values : [req.user['id']]
        }, function (error, results, rows) {
            if (results[0]['role'] === "admin") {
                admin = (results[0]['role']);
                res.render('admin', {
                    isAuthenticated : req.isAuthenticated(),
                    user : req.user
                });
            } else {
                admin = "";
                res.redirect('/index');
            }
        })
    });