Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get userid when a user login, against that userid im trying to get the the roles.
based on the role the user is going to be authorized what he can do.
so what my main objective is to do the role based authorization.

What I have tried:

// Login Varification  ActionMethod (check if the user is valid)
      public int Authenticate(string email, string password)  // get user id
      {
          var loggedUser = Mdb.Users.FirstOrDefault(x => x.Email.ToLower() == email.ToLower() && x.Password == password && x.IsDeleted == false);
          if (loggedUser != null)
          {
              return loggedUser.id;
          }
          return 0;
      }

//Security Controller 

   public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)

        {
            var Model = new LoginModel();

            if (ModelState.IsValid)
            {
                var userId = uServices.Authenticate(model.Email, model.Password);
                if (userId > 0)
                {
                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    Session["Userid"] = userId;                   
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        if (returnUrl.Equals("/"))
                        {
                            return RedirectToAction("List", "User");
                        }
                        else
                        {
                            return Redirect(returnUrl);
                        }
                    }
                    else
                    {
                        return RedirectToAction("List", "User");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid Email or Password");
                }
             
            }
            else
            {
                ModelState.AddModelError("", "Invalid Email or Password");
            }

            return View(Model);

        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            Session.RemoveAll();
            return RedirectToAction("Login");
        }


// static class permissions 
    public static class Permissions
    {
        public readonly static string Can_Add_User = "Can_Add_User";

        public readonly static string Can_Edit_User = "Can_Edit_User";

        public readonly static string Can_Delete_User = "Can_Delete_User";

        public readonly static string Can_Manage_User = "Can_Manage_User";

        public readonly static string Can_ViewList = "Can_ViewList";

    }


 // here i need to write code to get role against loggedin id allow permissions from static class and need help with this code 
     
<pre> public bool HasPermission(string permissionkey, int userId) // pass value through session
        {
            var roles = Mdb.Users.Where(x => x.id == userId).Select(y => y.User_Role_Mapping.Select(u => u.Roles.Name));
           }



 //in controller checking if the logged in user has permission

if (UserServices.HasPermission(Permissions.Can_Add_User))
            {
               //  controller code here 
            } 
Posted
Updated 3-May-21 21:26pm

Not related to the problem you have noticed, but very relevant here ...

Never store passwords in clear text - it is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^]

And remember: if you have any European Union users then GDPR applies and that means you need to handle passwords as sensitive data and store them in a safe and secure manner. Text is neither of those and the fines can be .... um ... outstanding. In December 2018 a German company received a relatively low fine of €20,000 for just that.
 
Share this answer
 
Comments
Smile_o1 29-Apr-21 7:15am    
Thanks OriginalGriff, It was helpful.
your logic can be like this

var userId =Convert.ToInt32(HttpContext.Current.Session["Userid"]); //pass value through session

          var roles = Mdb.User_Role_Mapping.Where(r => r.UserID == userId).Select(r => r.Roles).ToList();

              foreach (var role in roles)
              {
              foreach (var permission in role.Role_Permission_Mapping)
                  if (permission.Permissions.SystemName.Equals(permissionKey, StringComparison.InvariantCultureIgnoreCase))
                      return true;
              }
             return false;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900