source: StockMaster/Controllers/AccountController.cs@ dfe03b8

main
Last change on this file since dfe03b8 was dfe03b8, checked in by Ceyda <ceyda.huseini@…>, 2 days ago

Initialize StockMaster project

  • Property mode set to 100644
File size: 2.4 KB
Line 
1using Microsoft.AspNetCore.Mvc;
2using StockMaster.Services;
3using StockMaster.ViewModels;
4using Microsoft.AspNetCore.Http;
5using Microsoft.AspNetCore.Authentication;
6using Microsoft.AspNetCore.Authentication.Cookies;
7using System.Security.Claims;
8using System.Threading.Tasks;
9using System.Collections.Generic;
10
11namespace 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}
Note: See TracBrowser for help on using the repository browser.