Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Security.Claims;
- using System.Threading.Tasks;
- using Ad.ViewModels;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Authentication.Cookies;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Site.Data;
- using Site.Data.Models;
- namespace Ad.Controllers
- {
- [AllowAnonymous]
- public class AccountController : Controller
- {
- private SiteDbContext _context;
- public AccountController(SiteDbContext context)
- {
- _context = context;
- }
- public IActionResult Login() => View();
- [HttpPost]
- public async Task<IActionResult> Login(LoginViewModel model)
- {
- if (ModelState.IsValid)
- {
- User user = await _context.Users
- .Include(u => u.Role)
- .FirstOrDefaultAsync(u => u.UserName == model.UserName && u.Password == model.Password);
- if (user != null)
- {
- await Authenticate(user); // аутентификация
- return RedirectToAction("Index", "Profile");
- }
- ModelState.AddModelError("", "Некорректный логин и(или) пароль");
- }
- return View(model);
- }
- private async Task Authenticate(User user)
- {
- // создаем один claim
- var claims = new List<Claim>
- {
- new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName),
- new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role?.Name)
- };
- // создаем объект ClaimsIdentity
- ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
- ClaimsIdentity.DefaultRoleClaimType);
- // установка аутентификационных куки
- await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
- }
- public IActionResult Register()
- {
- return View();
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<IActionResult> Register(RegisterModel model)
- {
- if (ModelState.IsValid)
- {
- User user = await _context.Users.FirstOrDefaultAsync(u => u.UserName == model.UserName);
- if (user == null)
- {
- // добавляем пользователя в бд
- user = new User { UserName = model.UserName, Email = model.Email, Password = HashPassword(model.Password) };
- Role userRole = await _context.Roles.FirstOrDefaultAsync(r => r.Name == "User");
- if (userRole != null)
- user.Role = userRole;
- _context.Users.Add(user);
- await _context.SaveChangesAsync();
- await Authenticate(user); // аутентификация
- return RedirectToAction("Login", "Account");
- }
- else
- ModelState.AddModelError("", "Некорректные логин и(или) пароль");
- }
- return View(model);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement