Robert
Robert

Reputation: 3

How can I map users to roles and execute code accordingly in javascript?

I've got 5 user roles ("admin","modifier","manager","projectmanager","readonly") and need to execute different code depending on the specific role (only one role per user). Before I setup users and roles in a databse, I want to make it work and test the functionality in JavaScript. How can I 'connect' the users (hardcoded values) to the right role and execute the code?

Should I use arrays or maybe a switch case?

Something like:

//Declaration
arrAdmin["user1","user5","user9"];
arrModifier["user3","user6","user8"];
arrManager[];
arrProject["user4"];
arrReadOnly["user2","user7","user10","user11"]
...

function executeFunctionality(user){
var userFound = false;
while(userFound == false){
    for(var i=0; i<arrAdmin.length; i++){
        if(user == arrAdmin[i]){
            userFound = true;
            executeAdmin();
        }
    }
    for(var i=0; i<arrModifier.length; i++){
        if(user == arrModifier[i]){
            userFound = true;
            executeModifier();
        }
    }
    for(var i=0; i<arrManager.length; i++){
        if(user == arrManager[i]){
            userFound = true;
            executeManager();
        }
    }
    //etc...
}
}

or a switch case maybe?

switch(user){
"user1" : executeAdmin();
"user2" : executeReadOnly();
"user3" : executeModifier();
"user4" : executeProject();
"user5" : executeAdmin();
// etc ...
}

Thanks in advance!

Upvotes: 0

Views: 344

Answers (3)

Lave Loos
Lave Loos

Reputation: 1302

With a slight modification to this answer you should be able to do something like this:

var dispatcher = {
    "user1": executeAdmin,
    "user3": executeModifier,
    "user4": executeProject,
    "user5": executeAdmin
//...
};

(dispatcher[user] || executeReadOnly)();

Note: if the 'readonly' user role means basic privileges for all users - which seems to be the case in your example - there's no need to map any users to it. Just implement a default scenario that applies to all users (that don't have any extras).

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388376

This should do

function executeFunctionality(user){
    if(executeUserFunction(arrAdmin, user, executeAdmin)){
        return true;
    }

    if(executeUserFunction(arrModifier, user, executeAdmin)){
        return true;
    }

    if(executeUserFunction(arrManager, user, executeAdmin)){
        return true;
    }
    //etc
    return false;
}

function executeUserFunction(array, user, fn){
    var i;

    for(i = 0; i < array.length; i++){
        if(user == array[i]){
            fn();
            return true;
        }
    }
    return false;
}

Upvotes: 0

Rob
Rob

Reputation: 11798

You should definitely put that logic on the server side and deliver content and scripts according to th current user's role, because your JS can be accessed by anyone. It is NOT safe to dal with that on the client side!

Upvotes: 2

Related Questions