-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccountController.cs
More file actions
80 lines (70 loc) · 2.76 KB
/
Copy pathAccountController.cs
File metadata and controls
80 lines (70 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.Security.Claims;
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 SampleCRMApp.Data;
using SampleCRMApp.Data.Entities;
namespace SampleCRMApp.Controllers;
public class AccountController(
ApplicationDbContext db,
IPasswordHasher<User> passwordHasher,
ILogger<AccountController> logger) : Controller
{
[HttpPost]
[Route("/account/do-login")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DoLogin(
[FromForm] string email,
[FromForm] string password,
[FromForm] string? returnUrl,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
return Redirect("/account/login?error=1");
var user = await db.Users.FirstOrDefaultAsync(
u => u.Email == email.Trim() && u.Active,
cancellationToken);
if (user is null)
{
logger.LogWarning("Login failed: user not found for {Email}", email);
return Redirect("/account/login?error=1");
}
var verify = passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password);
if (verify == PasswordVerificationResult.Failed)
{
logger.LogWarning("Login failed: bad password for {Email}", email);
return Redirect("/account/login?error=1");
}
if (verify == PasswordVerificationResult.SuccessRehashNeeded)
{
user.PasswordHash = passwordHasher.HashPassword(user, password);
await db.SaveChangesAsync(cancellationToken);
}
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.UserId.ToString()),
new(ClaimTypes.Name, user.Name),
new(ClaimTypes.Email, user.Email),
new(ClaimTypes.Role, user.Role),
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity));
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
return Redirect("/");
}
[HttpGet]
[Route("/account/logout")]
[Authorize]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/account/login");
}
}