homework/Controllers/AccountController.cs

113 lines
3.1 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TechnoWorld.Data;
using TechnoWorld.Models;
namespace TechnoWorld.Controllers;
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login(string? returnUrl = null)
{
ViewData["Title"] = "Вход";
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string? returnUrl = null)
{
ViewData["Title"] = "Вход";
if (ModelState.IsValid)
{
var user = UserStore.Validate(model.Login, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return Redirect(Url.IsLocalUrl(returnUrl) ? returnUrl : "/");
}
ModelState.AddModelError(string.Empty, "Неверный логин или пароль");
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpGet]
public IActionResult Register()
{
ViewData["Title"] = "Регистрация";
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
ViewData["Title"] = "Регистрация";
if (ModelState.IsValid)
{
var ok = UserStore.Register(model.Login, model.Name, model.Password);
if (ok)
{
var user = UserStore.Validate(model.Login, model.Password);
if (user != null)
{
await SignInAsync(user, false);
}
return RedirectToAction(nameof(Profile));
}
ModelState.AddModelError(nameof(RegisterViewModel.Login), "Логин уже занят");
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home");
}
[HttpGet]
[Authorize]
public IActionResult Profile()
{
ViewData["Title"] = "Мой аккаунт";
return View();
}
private async Task SignInAsync(AppUser user, bool remember)
{
var claims = new List<Claim>
{
new(ClaimTypes.Name, user.Login),
new(ClaimTypes.GivenName, user.Name)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties
{
IsPersistent = remember,
ExpiresUtc = remember ? DateTimeOffset.UtcNow.AddDays(7) : null
});
}
}