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?

With regard to asp.net, I'm familiar with webforms, not MVC. However, I dont really think your question is specific to MVC.

How should I seperate the administrators and the users

I think the best approach is to include "roles" into your design. At the moment, you are considering users and administrators, but in the future, there may be other types of members. If you simply use a boolean value, yes you can distiguish a user from an admin. However, once you add an additional role, this approach will no longer be applicable.

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"].

This could work, but based upon your vision of where you are going in the future, you would be the person to best answer this question. If you know that you'll only need to identify a user as an admin or non-admin, I dont see why this wouldnt work well. As you stated, you would check for this value, and store the appropriate value in your session variable or cookie (in the future).

Hello, Your code sounds good.
First, I suggest to use Cookie for LogIn Moudle in place of session. Just remove cookie when user logged out.
Second, Create one Field named "Role" or "UserType" in database and insert value "Admin" during admin creation and "User" for other Users.

During login Return usertype by passing Username and Password using LINQ as you did alreay. Check if Usertype is "Admin" then return RedirectToAction("Admin","Admin") or if "User" then return RedirectToAction("User","User")

If you still have query then send me complete code I will give rough overview.

Thanks

Hi, all? i am a programming student and i want to create a VB lo-gin code used to validate User type, Username and password using SQL 2008 connection.
The code is not working. i have been trying to build it from scratch. However, i want users to be able to select a user type e.g. Admin, accounts, HRM, Security and Operations from a combo box, then enter a username and password to log-in into the system and then access a menu form which i have already created for further actions. i have already created a table of system user access registration using SQL Server 2008 database with the following fields: EmployeeID, UserType,FirstName, LastName,Email,UserName and Password. Using this info, i want only authenticated users to be able to login.
Here is what i have tried to piece together, thnks.

Imports System.Data.SqlClient
Public Class FrmSystemAccess
Dim dbpath As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + "\KBUC_.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim con As New SqlConnection(dbpath) ' connection
'// SIMPLE UNIVERSAL CLEAR CODE (FOR NEXT BUTTON) Private Sub FrmSystemAccess_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Private Sub BtnLogin_Click(sender As System.Object, e As System.EventArgs) Handles BtnLogin.Click
If CombUserType.Text = "" Then
MessageBox.Show("Please select user type", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
CombUserType.Focus()
Return
End If
If TxtUserName.Text = "" Then
MessageBox.Show("Please enter user name", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
TxtUserName.Focus()
Return
End If
If TxtPassword.Text = "" Then
MessageBox.Show("Please enter password", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
TxtPassword.Focus()
Return
End If
Try
con = New OleDbConnection(cs)
cmd = New OleDbCommand("SELECT UserType,UserName,Password FROM SystemAccessRegistration WHERE UserType = '" & CombUserType.Text & "' AND UserName = '" & TxtUserName.Text & "' AND Password = '" & TxtPassword.Text & "'", con)
cmd.Connection.Open()
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
If rdr.Read() = True Then
Dim i As Integer
ProgressBar1.Visible = True
ProgressBar1.Maximum = 5000
ProgressBar1.Minimum = 0
ProgressBar1.Value = 4
ProgressBar1.[Step] = 1
For i = 0 To 5000
ProgressBar1.PerformStep()
Next
Me.Hide()
Dim frm As New frmMainMenu()
frm.lblUser.Text = TxtUserName.Text
frm.Show()
Else
MessageBox.Show("Login is Failed...Try again !", "Login Denied", MessageBoxButtons.OK, MessageBoxIcon.[Error])
TxtUserName.Clear()
TxtPassword.Clear()
TxtUserName.Focus()
End If
If con.State = ConnectionState.Open Then
con.Dispose()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
End Sub

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.