如何使用asp.net mvc从头开始添加用户角色

问题描述 投票:0回答:1

我想从头开始创建用户角色和身份,并且不使用创建单个身份验证ASP.NET MVC项目时提供的默认值。当我研究时,会得到使用该项目默认连接的项目。当我创建注册并从头开始登录时,我实际上不知道在哪里或如何添加角色。

下面是我所做的:

Controller

   public class RegistrationController : Controller
{
    //Registration Action
    [HttpGet]
    public ActionResult Registration()
    {
        return View();
    }

    //Registration Post Action
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] Customer user)
    {
        bool Status = false;
        string message = "";
        //
        // Model Validation 
        if (ModelState.IsValid)
        {

            #region //Email is already Exist 
            var isExist = IsEmailExist(user.EmailId);
            if (isExist)
            {
                ModelState.AddModelError("EmailExist", "Email already exist");
                return View(user);
            }
            #endregion

            #region Generate Activation Code 
            user.ActivationCode = Guid.NewGuid();
            #endregion

            #region  Password Hashing 
            user.Password = Crypto.Hash(user.Password);
            user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword); //
            #endregion
            user.IsEmailVerified = false;

            #region Save to Database
            using (mymodel dc = new mymodel())
            {
                user.CustomerId = Guid.NewGuid();
                dc.Customers.Add(user);
                dc.SaveChanges();

                //Send Email to User
                SendVerificationLinkEmail(user.EmailId, user.ActivationCode.ToString());
                message = " Registration successfully done. Account activation link " +
                    " has been sent to your email: " + user.EmailId;
                Status = true;
            }
            #endregion
        }
        else
        {
            message = "Invalid Request";
        }

        ViewBag.Message = message;
        ViewBag.Status = Status;
        return View(user);
    }

    //Verify Account
    [HttpGet]
    public ActionResult VerifyAccount(string id)
    {
        bool Status = false;
        using (mymodel dc = new mymodel())
        {
            dc.Configuration.ValidateOnSaveEnabled = false; // This line I have added here to avoid 
                                                            // Confirm password does not match issue on save changes
            var v = dc.Customers.Where(a => a.ActivationCode == new Guid(id)).FirstOrDefault();
            if (v != null)
            {
                v.IsEmailVerified = true;
                dc.SaveChanges();
                Status = true;
            }
            else
            {
                ViewBag.Message = "Invalid Request";
            }
        }
        ViewBag.Status = Status;
        return View();
    }


    //Login
    [HttpGet]
    public ActionResult Login()
    {
        return View();
    }

    //Login Post
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(UserLogin login, string ReturnUrl = "")
    {
        string message = "";
        using (mymodel dc = new mymodel())
        {
            var v = dc.Customers.Where(a => a.EmailId == login.EmailId).FirstOrDefault();
            if (v != null)
            {
                if (!v.IsEmailVerified)
                {
                    ViewBag.Message = "Please verify your email first";
                    return View();
                }
                if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0)
                {
                    int timeout = login.RememberMe ? 525600 : 20; // 525600 min = 1 year
                    var ticket = new FormsAuthenticationTicket(login.EmailId, login.RememberMe, timeout);
                    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
                    {
                        return RedirectToAction("Index", "Request");
                    }
                }
                else
                {
                    message = "Invalid credential provided";
                }
            }
            else
            {
                message = "Invalid credential provided";
            }
        }
        ViewBag.Message = message;
        return View();
    }

    //Logout
    [Authorize]
    [HttpPost]
    public ActionResult Logout()
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("Login", "Registration");
    }


    [NonAction]
    public bool IsEmailExist(string emailID)
    {
        using (mymodel dc = new mymodel())
        {
            var v = dc.Customers.Where(a => a.EmailId == emailID).FirstOrDefault();
            return v != null;
        }
    }

    //Verify Email Link
    [NonAction]
    public void SendVerificationLinkEmail(string emailID, string activationCode, string emailFor = "VerifyAccount")
    {
        var verifyUrl = "/Registration/" + emailFor + "/" + activationCode;
        var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);

        var fromEmail = new MailAddress("[email protected]", "Lifestyle Laundry");
        var toEmail = new MailAddress(emailID);
        var fromEmailPassword = "****"; // Replace with actual password

        string subject = "";
        string body = "";

        if (emailFor == "VerifyAccount")
        {
            subject = "Your account is successfully created";
            body = "<br/><br/>We are excited to tell you that your account is" +
           " successfully created. Please click on the below link to verify your account" +
           " <br/><br/><a href='" + link + "'>" + link + "</a> ";
        }



        else if (emailFor == "ResetPassword")
        {
            subject = "Reset Password";
            body = "Hi,<br/><br/>We got request for reset your account password. Please click on the below link to reset your password" +
                "<br/><br/><a href=" + link + ">Reset Password link</a>";
        }

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
        };

        using (var message = new MailMessage(fromEmail, toEmail)
        {
            Subject = subject,
            Body = body,
            IsBodyHtml = true
        })
            smtp.Send(message);
    }






    [HttpGet]
    public ActionResult ForgotPassword()
    {
        return View();
    }

    [HttpPost]
    public ActionResult ForgotPassword(string EmailID)
    {
        //Verify Email ID
        //Generate Reset password link 
        //Send Email 
        string message = "";
        bool status = false;

        using (mymodel dc = new mymodel())
        {
            var account = dc.Customers.Where(a => a.EmailId == EmailID).FirstOrDefault();
            if (account != null)
            {
                //Send email for reset password
                string resetCode = Guid.NewGuid().ToString();
                SendVerificationLinkEmail(account.EmailId, resetCode, "ResetPassword");
                account.ResetPasswordCode = resetCode;
                //This line I have added here to avoid confirm password not match issue , as we had added a confirm password property 
                //in our model class in part 1
                dc.Configuration.ValidateOnSaveEnabled = false;
                dc.SaveChanges();
                message = "Reset password link has been sent to your email.";
            }
            else
            {
                message = "Account not found";
            }
        }
        ViewBag.Message = message;
        return View();
    }


    public ActionResult ResetPassword(string id)
    {
        //Verify the reset password link
        //Find account associated with this link
        //redirect to reset password page
        if (string.IsNullOrWhiteSpace(id))
        {
            return HttpNotFound();
        }

        using (mymodel dc = new mymodel())
        {
            var user = dc.Customers.Where(a => a.ResetPasswordCode == id).FirstOrDefault();
            if (user != null)
            {
                ResetPasswordModel model = new ResetPasswordModel();
                model.ResetCode = id;
                return View(model);
            }
            else
            {
                return HttpNotFound();
            }
        }
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ResetPassword(ResetPasswordModel model)
    {
        var message = "";
        if (ModelState.IsValid)
        {
            using (mymodel dc = new mymodel())
            {
                var user = dc.Customers.Where(a => a.ResetPasswordCode == model.ResetCode).FirstOrDefault();
                if (user != null)
                {
                    user.Password = Crypto.Hash(model.NewPassword);
                    user.ResetPasswordCode = "";
                    dc.Configuration.ValidateOnSaveEnabled = false;
                    dc.SaveChanges();
                    message = "New password updated successfully";
                }
            }
        }
        else
        {
            message = "Something invalid";
        }
        ViewBag.Message = message;
        return View(model);
    }

}


Model
public partial class Customer
{
    public Guid CustomerId { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CustId { get; set; }

    [Required]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required]
    [StringLength(254)]
    public string EmailId { get; set; }

    [Required]
    [StringLength(100)]
    public string PhoneNumber { get; set; }

    public DateTime? CreatedDate { get; set; }

    [Required]
    public string Password { get; set; }

    [Required]
    public string ConfirmPassword { get; set; }

    public bool IsEmailVerified { get; set; }

    public Guid ActivationCode { get; set; }

    [StringLength(100)]
    public string ResetPasswordCode { get; set; }
}
asp.net-mvc entity-framework asp.net-mvc-4 model-view-controller user-roles
1个回答
0
投票

当然,您应该使用RoleManager类的实例,这将为用户提供创建,检查和分配角色的便利。

    private ApplicationRoleManager _roleManager;
    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

然后,要在表中注册新用户时,将以下代码放入注册方法中。

                if (!RoleManager.RoleExists("<roleName>"))
                {
                    var role = new IdentityRole("<roleName>");
                    var roleresult = await RoleManager.CreateAsync(role);
                    if (!roleresult.Succeeded)
                    {
                        ModelState.AddModelError("", roleresult.Errors.First());
                        return View(model);
                    }
                }
© www.soinside.com 2019 - 2024. All rights reserved.