| 1 | using Microsoft.AspNetCore.Mvc;
|
|---|
| 2 | using StockMaster.Services;
|
|---|
| 3 | using StockMaster.ViewModels;
|
|---|
| 4 | using Microsoft.AspNetCore.Http;
|
|---|
| 5 | using Microsoft.AspNetCore.Authentication;
|
|---|
| 6 | using Microsoft.AspNetCore.Authentication.Cookies;
|
|---|
| 7 | using System.Security.Claims;
|
|---|
| 8 | using System.Threading.Tasks;
|
|---|
| 9 | using System.Collections.Generic;
|
|---|
| 10 |
|
|---|
| 11 | namespace StockMaster.Controllers
|
|---|
| 12 | {
|
|---|
| 13 | public class AccountController : Controller
|
|---|
| 14 | {
|
|---|
| 15 | private readonly IAuthService _authService;
|
|---|
| 16 |
|
|---|
| 17 | public AccountController(IAuthService authService)
|
|---|
| 18 | {
|
|---|
| 19 | _authService = authService;
|
|---|
| 20 | }
|
|---|
| 21 |
|
|---|
| 22 | [HttpGet]
|
|---|
| 23 | public IActionResult Login()
|
|---|
| 24 | {
|
|---|
| 25 | if (User.Identity.IsAuthenticated)
|
|---|
| 26 | {
|
|---|
| 27 | return RedirectToAction("Index", "Home");
|
|---|
| 28 | }
|
|---|
| 29 | return View();
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | [HttpPost]
|
|---|
| 33 | public async Task<IActionResult> Login(LoginViewModel model)
|
|---|
| 34 | {
|
|---|
| 35 | if (!ModelState.IsValid)
|
|---|
| 36 | return View(model);
|
|---|
| 37 |
|
|---|
| 38 | var user = await _authService.AuthenticateAsync(model.Username, model.Password);
|
|---|
| 39 |
|
|---|
| 40 | if (user == null)
|
|---|
| 41 | {
|
|---|
| 42 | ModelState.AddModelError("", "Invalid username or password");
|
|---|
| 43 | return View(model);
|
|---|
| 44 | }
|
|---|
| 45 |
|
|---|
| 46 | var claims = new List<Claim>
|
|---|
| 47 | {
|
|---|
| 48 | new Claim(ClaimTypes.Name, user.Username),
|
|---|
| 49 | new Claim(ClaimTypes.Role, user.Role),
|
|---|
| 50 | new Claim("UserId", user.UserId.ToString()),
|
|---|
| 51 | new Claim("FullName", user.FullName)
|
|---|
| 52 | };
|
|---|
| 53 |
|
|---|
| 54 | var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
|---|
| 55 |
|
|---|
| 56 | await HttpContext.SignInAsync(
|
|---|
| 57 | CookieAuthenticationDefaults.AuthenticationScheme,
|
|---|
| 58 | new ClaimsPrincipal(claimsIdentity));
|
|---|
| 59 |
|
|---|
| 60 |
|
|---|
| 61 | HttpContext.Session.SetInt32("UserId", user.UserId);
|
|---|
| 62 | HttpContext.Session.SetString("Username", user.Username);
|
|---|
| 63 | HttpContext.Session.SetString("Role", user.Role);
|
|---|
| 64 | HttpContext.Session.SetString("FullName", user.FullName);
|
|---|
| 65 |
|
|---|
| 66 | return RedirectToAction("Index", "Home");
|
|---|
| 67 | }
|
|---|
| 68 |
|
|---|
| 69 | public async Task<IActionResult> Logout()
|
|---|
| 70 | {
|
|---|
| 71 | HttpContext.Session.Clear();
|
|---|
| 72 | await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|---|
| 73 |
|
|---|
| 74 | return RedirectToAction("Login");
|
|---|
| 75 | }
|
|---|
| 76 | }
|
|---|
| 77 | } |
|---|