From 0c4d13caed53b2702eef41461d0c8a4b25df48f6 Mon Sep 17 00:00:00 2001 From: Sergey Chebotar Date: Mon, 6 Mar 2023 07:41:35 +0300 Subject: Base authorization/authentification --- Controllers/AccountController.cs | 80 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Controllers/AccountController.cs (limited to 'Controllers/AccountController.cs') diff --git a/Controllers/AccountController.cs b/Controllers/AccountController.cs new file mode 100644 index 0000000..432b671 --- /dev/null +++ b/Controllers/AccountController.cs @@ -0,0 +1,80 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using MyDarling.Models; + +namespace MyDarling.Controllers; + +public class AccountController : Controller +{ + public UserManager UserManager { get; set; } + private SignInManager SignInManager; + + public AccountController(UserManager userManager, SignInManager signInManager) + { + UserManager = userManager; + SignInManager = signInManager; + } + + public IActionResult List() + { + return View(UserManager.Users); + } + + public IActionResult Create() + { + return View(new IdentityUser()); + } + + [HttpPost] + public async Task Create([Bind] IdentityUser user, [Bind] string Password) + { + if (ModelState.IsValid) + { + IdentityResult result = await UserManager.CreateAsync(user, Password); + if (result.Succeeded) + { + return RedirectToAction(nameof(List)); + } + + foreach (IdentityError error in result.Errors) + { + ModelState.AddModelError("", error.Description); + } + } + return View(); + } + + public ViewResult Login(string returlUrl) + { + return View(new LoginModel { ReturnUrl = returlUrl }); + } + + [HttpPost] + public async Task Login(LoginModel loginModel) + { + if (ModelState.IsValid) + { + IdentityUser user = await UserManager.FindByNameAsync(loginModel.Name); + if (user != null) + { + await SignInManager.SignOutAsync(); + if ((await SignInManager.PasswordSignInAsync(user, + loginModel.Password, false, false)) + .Succeeded) + { + return Redirect(loginModel?.ReturnUrl ?? "/Bundle"); + } + } + ModelState.AddModelError("", "Invalid name or password"); + } + return View(loginModel); + } + + [Authorize] + public async Task Logout(string returlUrl = "/Account/Login") + { + await SignInManager.SignOutAsync(); + return Redirect(returlUrl); + } +} \ No newline at end of file -- cgit v1.2.3