Hello.
I want to make a simple login page using MVC4, where both users and admins can log in. The users should be allowed to see their own details, edit their details. The administrators should be able to list all the users, show a specific users details, edit those details and delete users. Also, the admin should be able make some of the users administrators by checking a checkbox or something.
My problem is that I'm not sure how I should seperate the users and administrators when they log in. I want them both to use the same login page, where administrators get access to some extra settings that users can't access.
I've currently made a login page where only users can log in, where I'm using sessions. Here are some of the methods I've used for the users in my User Controller:
public ActionResult LogIn()
{
if (Session["LoggedIn"] == null)
{
Session["LoggedIn"] = false;
ViewBag.LoggedIn = false;
}
else
{
ViewBag.LoggedIn = (bool)Session["LoggedIn"];
}
return View();
}
[HttpPost]
public ActionResult LogIn(FormCollection input)
{
string email = input["Username"];
string password = input["Password"];
if (userExists(Username, password))
{
Session["LoggedIn"] = true;
ViewBag.LoggedIn = true;
return RedirectToAction("MyPage");
}
else
{
Session["LoggedIn"] = false;
ViewBag.LoggedIn = false;
return View();
}
}
public Boolean userExists(string username, string password)
{
using (var db = new databaseContext())
{
byte[] passwd = hashPassword(password);
dbUser foundUser = db.Users.FirstOrDefault(b => b.password == passwd && b.username == username);
if (foundUser == null)
{
return false;
}
else
{
var editUser = from d in db.Users
where d.username.Equals(foundUser.username)
select d;
foreach (dbUser user in editUser)
{
user.logInTime = DateTime.Now;
}
db.SaveChanges();
return true;
}
}
}
This is how some of my code looks like. A user can simply log in, works quite well. I want to keep using sessions (the method I use) before I look at cookies.
How should I seperate the administrators and the users? I was thinking about adding a boolean variable to my dbUser class, where it's true if the user is admin and false otherwise. Making it true for the first user who registers, and false for the rest. Then use this variable and check if it's true, we make a new Session["AdminLoggedIn"].
Any suggestions?