如何进行动态授权?

时间:2019-08-13 17:46:27

标签: c# authentication asp.net-mvc-5

我在使用控制器授权时很费力,我从头开始创建了一个用户表,一个角色表和权限,但是在Google上搜索了很多之后,我什么都没有创建自定义控制器权限。 我的想法是得到我的允许:

https://drive.google.com/file/d/1b1FNM7PRzLgFjUK1BEpPAqAo7Wp5acga/view?usp=sharing

我正在使用本地库(SQL Server 2017)和Visual Studio 2017 Pro 我的帐户管理员:

    //Registration Action
    [HttpGet]
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }
    //Registration POST action 
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(User user)
    {


        if (ModelState.IsValid)
        {

             var isExist = IsEmailExist(user.UserName);
                if (isExist)
                {
                    ModelState.AddModelError("EmailExist", "Email already exist");
                    return View(user);
                }
                user.ActivationCode = Guid.NewGuid();
                user.Password = Crypto.Hash(user.Password);
                user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword);
                user.ConfirmarEmail = false;
                user.IsEnabled = true;

                db.Users.Add(user);
                db.SaveChanges();
                string callbackUrl = await SendEmailConfirmationTokenAsync( user.UserName, "Por favor, confirme seu e-mail", Convert.ToString(user.ActivationCode));
                ViewBag.Message = "Por favor, verifique seu e-mail antes de continuar.";
                return View("Info");



        }



        return View(user);

    }
    //Verify Account  
    [AllowAnonymous]
    [HttpGet]
    public ActionResult VerifyAccount(string id)
    {
        bool Status = false;

        db.Configuration.ValidateOnSaveEnabled = false;
        var v = db.Users.Where(a => a.ActivationCode == new Guid(id)).FirstOrDefault();
        if (v != null)
        {
            v.ConfirmarEmail = true;
            db.SaveChanges();
            Status = true;
        }
        else
        {
            ViewBag.Message = "Requisição invalida";
        }

        ViewBag.Status = Status;
        return View();
    }

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

    //Login POST
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(UserLogin login, string ReturnUrl = "")
   {
        string message = "";
        var v = db.Users.Where(a => a.UserName == login.UserName).FirstOrDefault();
        if (v != null)
        {
            if (!v.ConfirmarEmail)
            {
                    Guid activationcode = v.ActivationCode;
                    string callbackUrl = await SendEmailConfirmationTokenAsync(Convert.ToString(v.UserId), v.UserName, "Confirmação de e-mail reenviada", activationcode.ToString());
                    ViewBag.Message = "Por favor, verifique seu e-mail antes de realizar o login.";
                    return View("Info");


            }

            if (v.IsEnabled == false)
            {
                return View("Lockout");
            }

            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.UserName, 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", "Home");
                }
            }

        }
        else
        {
            message = " E - mail e / ou senha incorreto(s).";
        }

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


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


    [NonAction]
    public bool IsEmailExist(string emailID)
    {

            var v = db.Users.Where(a => a.UserName == emailID).FirstOrDefault();
            return v != null;

    }

    [NonAction]

    private async Task<string> SendEmailConfirmationTokenAsync(string userName, string subject, string activationCode, string emailFor = "VerifyAccount")
    {
        var verifyUrl = "/Users/" + emailFor + "/" + activationCode;
        var callbackUrl = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);

        if (emailFor == "VerifyAccount")
        { 
            string body = macpartner.Resources.emailConfirmationBody;
        body = body.Replace("[link]", callbackUrl);
        await MailHelper.SendMail(userName, subject, body);
        }
        if(emailFor == "ResetPassword")
        {
            var body = macpartner.Resources.forgotPassBody;
            body = body.Replace("Oi[nome]", "Olá");
            body = body.Replace("[link]", callbackUrl);
            await MailHelper.SendMail(userName, subject, body);
        }

        return callbackUrl;
    }

    //Part 3 - Forgot Password
    [AllowAnonymous]
    public ActionResult ForgotPassword()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult> ForgotPassword(ForgotPasswordModel model)
    {
        var account = db.Users.Where(a => a.UserName == model.Email).FirstOrDefault();
        string message = "";

        if (account != null)
        {




                string resetCode = Guid.NewGuid().ToString();
                await SendEmailConfirmationTokenAsync(account.UserName, "IndicaMais - Cadastro de Nova Senha", resetCode, "ResetPassword");
                account.ResetPasswordCode = resetCode;
                db.Configuration.ValidateOnSaveEnabled = false;
                db.SaveChanges();



            return RedirectToAction("ForgotPasswordConfirmation", "Users");
        }
        else
        {
          message = "Usuário Não encontrado";
        }

        ViewBag.Message = message;
        return View(model);
    }

    //GET: /Account/ForgotPasswordConfirmation
   [AllowAnonymous]
    public ActionResult ForgotPasswordConfirmation()
    {
        return View();
    }

    [AllowAnonymous]
    public ActionResult ResetPassword(string id)
    {

        if (string.IsNullOrWhiteSpace(id))
        {
            return HttpNotFound();
        }


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

    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult ResetPassword(ResetPasswordModel model)
    {
        var message = "";
        if (ModelState.IsValid)
        {

                var user = db.Users.Where(a => a.ResetPasswordCode == model.ResetCode).FirstOrDefault();
                if (user != null)
                {
                    user.Password = Crypto.Hash(model.Password);
                    user.ResetPasswordCode = "";
                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.SaveChanges();
                 return RedirectToAction("ResetPasswordConfirmation", "Users");
            }

        }
        else
        {
            message = "Erro na requisição";
        }
        ViewBag.Message = message;
        return View(model);
    }

    // GET: /Account/ResetPasswordConfirmation
    [AllowAnonymous]
    public ActionResult ResetPasswordConfirmation()
    {
        return View();
    }

我的网络配置:

 <authentication mode="Forms">
      <forms cookieless="UseCookies" loginUrl="~/users/login" slidingExpiration="true"></forms>
    </authentication>

0 个答案:

没有答案