-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathAuthenticateCommandHandler.cs
More file actions
69 lines (58 loc) · 2.45 KB
/
AuthenticateCommandHandler.cs
File metadata and controls
69 lines (58 loc) · 2.45 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
using Mediator;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using OpenAlprWebhookProcessor.Features.Users.Data;
using OpenAlprWebhookProcessor.Features.Users.Queries.GetAllUsers;
using System.Threading;
using System.Threading.Tasks;
namespace OpenAlprWebhookProcessor.Features.Users.Commands.Authenticate
{
public class AuthenticateCommandHandler : IQueryHandler<AuthenticateCommand, UserDto>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UsersContext _context;
public AuthenticateCommandHandler(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
UsersContext context)
{
_userManager = userManager;
_signInManager = signInManager;
_context = context;
}
public async ValueTask<UserDto> Handle(AuthenticateCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByNameAsync(request.Username);
if (user == null)
throw new AppException("Username or password is incorrect");
var result = await _signInManager.CheckPasswordSignInAsync(
user,
request.Password,
true);
if (result.IsLockedOut)
throw new AppException("Account locked due to multiple failed attempts");
if (!result.Succeeded)
throw new AppException("Username or password is incorrect");
// Check if user has passkeys
var hasPasskeys = await _context.PasskeyCredentials
.AnyAsync(p => p.UserId == user.Id, cancellationToken);
var authUser = new UserDto
{
FirstName = user.FirstName,
Id = user.Id,
TwoFactorEnabled = false,
HasPasskeys = hasPasskeys,
LastName = user.LastName,
Username = user.UserName,
};
if (await _userManager.GetTwoFactorEnabledAsync(user))
{
authUser.TwoFactorEnabled = true;
return authUser;
}
await _signInManager.SignInAsync(user, request.RememberMe);
return authUser;
}
}
}