Home > other >  How can i change user role automatically in ASP.NET MVC
How can i change user role automatically in ASP.NET MVC

Time:09-16

I want to change user role once they do some jobs automatically but normal db.savechanges() are not working they are not even throwing any error can some fix the issue?

Code used in controller for changing gthe user role in data base is:

[AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(PRSV_Login loginData, string ReturnUrl = "")
        {
            string message = "";
            using (PRSVEntities db = new PRSVEntities())
            {
                var dataItem = db.PRSV_Login.Where(x => x.Email == loginData.Email).FirstOrDefault();
                if (dataItem != null)
                {
                    if(string.Compare(Encrypto.Hash(loginData.Password), dataItem.Password) == 0)
                    {
                        int timeout = 20;
                        var ticket = new FormsAuthenticationTicket(loginData.Email, true, timeout);// pass one more variable admin
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);

                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return Redirect(ReturnUrl);
                        }
                        else
                        {
                            if (dataItem.Role == "Admin")
                            {
                                return RedirectToAction("AdminPanel", "Home");
                            }
                            if (dataItem.Role == "Voter")
                            {
                                var isEmail = IsEmailExist(loginData.Email);
                                if (isEmail)
                                {
                                    loginData.Role = "Voted";
                                    db.SaveChanges();
                                    Session["username"] = dataItem.Name;
                                    Session["Email"] = dataItem.Email;
                                    ModelState.AddModelError("EmailExist", "Candidate has Already Voted!");
                                    Session["message"] = "<h1 class=\"display-5 fw-bold sorry\">sorry!</h1><br><p class=\"col-md-8 fs-4\"><b>"  
                                    dataItem.Name   ",</b> <br><br>You can not vote <b>twice or more!</b><br></p>";
                                    return RedirectToAction("Sorry", "Home");
                                }
                                else
                                {
                                    Session["username"] = dataItem.Name;
                                    Session["Email"] = dataItem.Email;
                                    TempData["Name"] = dataItem.Name;
                                    TempData["Email"] = dataItem.Email;
                                    return RedirectToAction("VotePanel", "Home");
                                }   
                            }
                            else
                            {
                                if (dataItem.Role == "Voted")
                                {
                                    Session["username"] = dataItem.Name;
                                    Session["Email"] = dataItem.Email;
                                    ModelState.AddModelError("EmailExist", "Candidate has Already Voted!");
                                    Session["message"] = "<h1 class=\"display-5 fw-bold sorry\">sorry!</h1><br><p class=\"col-md-8 fs-4\"><b>"  
                                    dataItem.Name   ",</b> <br><br>You can not vote <b>twice or more!</b><br></p>";
                                    return RedirectToAction("Sorry", "Home");
                                    
                                }

                                else
                                {
                                    message = "Invalid credential provided";
                                    return RedirectToAction("Index", "Home");
                                }
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid Email-Id/Password");
                        return View();
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid Email-Id/Password");
                    return View();
                }
            }
        }

I am also using the Identity package. I am also using a separate class for this role actions which is given below

namespace DEE_PRSV_V2_3.MyRoleProvider
{

    public class SiteRole : RoleProvider
    {
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException();
        }

        public override string[] GetRolesForUser(string Email)
        {
            PRSVEntities db = new PRSVEntities();
            string data = db.PRSV_Login.Where(x => x.Email == Email).FirstOrDefault().Role;
            string[] result = { data };
            return result;
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            throw new NotImplementedException();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }
    }
}

CodePudding user response:

You are changing the value of your method parameter loginData, which is not attached to your context. You should change the Role of your dataItem retrieved from the database.

CodePudding user response:

If you're using ASP.NET Identity you may inject UserManager into your controllers.

private readonly UserManager<ApplicationUser> _userManager;

public MyController(UserManager<ApplicationUser> userManager)
{
    _userManager = userManager;
}

//Action Method

public async Task<IActionResult> Login(...)
{
    // Get current user. You can also use UserManager's 
    // FindByIdAsync or FindByEmailAsync methods.
    var user = await _userManager.GetUserAsync(HttpContext.User);

    // Add user to role
    var result = await _userManager.AddToRoleAsync(user, "MyRole");

    if(result.Succeeded)
    {
        //Handle result
    }
}
  • Related