Studento919 Studento919 - 5 months ago 200
Node.js Question

Setting admin role using connect-roles & Passport.JS

I am currently trying to set up an admin role in order to access a simple admin page using the following documentation provided via : connect-roles

I ave been banging my head against it for a while and am still lost on how to set a role E.G As of right now am pulling a admin value out of the DB and storing it in a global var for the time being but I have no idea how to use that with connect-roles say to only allow access to my admin page for a specific user.

Can anyone clarify or show an example on how to do this/some guidance as I documentation didn't help me to ensure access to a web page only if the user is an admin?

Ave posted some of the code kinda showing what it looks like at the moment.

Code

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('/');
}

Answer

Using the following logic I was able to have admin functionality based on value within the 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');
            }
        })
    });