I have a set of commands like:
Those commands are used in a chat room where I have several users with different access, for example:
When a command is used it goes to a bot that is present in the room, that bot will them verify the user, access and everything before performing the command.
Initially I have a user class assigned to a list:
public class Users
{
public string Name { get; set; }
public string Comments { get; set; }
public string Access { get; set; }
}
public List<Users> userList = new List<Users>();
Now I want to implement an easy way to query/check/verify if a given user has access to use a given command, but I am not sure on how to approach it.
I was thinking about having a second class assigned to a list something like the this:
public class UserAccess
{
public string AccessLevel { get; set; }
public List<string> Commands = new List<string>();
}
public List<UserAccess> accessList = new List<UserAccess>();
And query it with something like:
var user = userList.Find(x => x.Name == currentUser);
if (user != null && accessList.Exists(x => x.AccessLevel == user.Access && x.Commands.Contains(str_cmd))
{
// use the command
}
else
{
// cannot use the command
}
As I mentioned above, I have a background worker that is constantly reading the chat messages to capture when a user has typed a command which will then verify and process everything in a queue.
Registered users and access level are filled from my website API which returns JSON to my application when it starts and updates data every now and then when major commands are issued.
This is just an example, I could be over thinking the idea but I did like to hear some advices and ideas of how I could deal with this ?
You can try something like this. Although you may want to define your access list through a Db or through attributes/properties on where your actual commands are defined.
public class User
{
public static readonly UserAccess[] AccessList = {
new UserAccess() { AccessLevel = "Admin",
Commands = {".kick",".ban",".unban"}
},
new UserAccess() { AccessLevel = "User",
Commands = {".add",".del"}
},
new UserAccess() { AccessLevel = "Vip",
Commands = {".say"}
}};
public string Name { get; set; }
public string Comments { get; set; }
public string Access { get; private set; } //Assuming you can't modify this so we add the next property
public UserAccess AccessLevel { get; private set; }
public User(string access)
{
this.Access = access;
this.AccessLevel = AccessList.FirstOrDefault(x => x.AccessLevel == access);
}
}
public class UserAccess
{
public string AccessLevel { get; set; }
public List<string> Commands = new List<string>();
public bool HasCommand(string command)
{
return this.Commands.Any(x => x == command);
}
}