11using MediatR ;
2+ using Microsoft . AspNetCore . Identity ;
23using Microsoft . EntityFrameworkCore ;
3- using PaymentCoreServiceApi . Core . Interfaces . Repositories . Write ;
4+ using PaymentCoreServiceApi . Common ;
5+ using PaymentCoreServiceApi . Common . Mediator ;
46using PaymentCoreServiceApi . Infrastructure . DbContexts ;
57using PaymentCoreServiceApi . Services ;
68
79namespace PaymentCoreServiceApi . Features . Auth . Commands ;
810
9- public class LoginCommandHandler : IRequestHandler < LoginCommand , LoginResponse >
11+ public class LoginCommandHandler : IRequestApiResponseHandler < LoginCommand , LoginResponse >
1012{
1113 private readonly AppDbContext _context ;
1214 private readonly IJwtService _jwtService ;
1315 private readonly IExecutionContext _currentUser ;
16+ private readonly IPinHasher _pinHasher ;
1417
1518 public LoginCommandHandler (
16- AppDbContext context ,
19+ AppDbContext context ,
1720 IJwtService jwtService ,
18- IExecutionContext currentUser )
21+ IExecutionContext currentUser ,
22+ IPinHasher pinHasher )
1923 {
2024 _context = context ;
2125 _jwtService = jwtService ;
2226 _currentUser = currentUser ;
27+ _pinHasher = pinHasher ;
2328 }
2429
25- public async Task < LoginResponse > Handle ( LoginCommand request , CancellationToken cancellationToken )
30+ public async Task < ApiResponse < LoginResponse > > Handle ( LoginCommand request , CancellationToken cancellationToken )
2631 {
32+ if ( string . IsNullOrWhiteSpace ( request . UserName ) || string . IsNullOrWhiteSpace ( request . Password ) )
33+ {
34+ return ApiResponse < LoginResponse > . BadRequest ( "Username and password are required" ) ;
35+ }
36+
2737 var user = await _context . Users
28- . FirstOrDefaultAsync ( u => u . UserName == request . UserName , cancellationToken ) ;
38+ . FirstOrDefaultAsync ( u =>
39+ ( u . UserName == request . UserName || u . Email == request . UserName )
40+ && u . Active && ! u . Deleted ,
41+ cancellationToken ) ;
2942
30- if ( user == null || user . Password != request . Password )
43+ if ( user == null )
3144 {
32- throw new UnauthorizedAccessException ( "Invalid username or password" ) ;
45+ return ApiResponse < LoginResponse > . Unauthorized ( "Invalid username or password" ) ;
46+ }
47+ if ( ! _pinHasher . VerifyPin ( request . Password , user . Password ) )
48+ {
49+ return ApiResponse < LoginResponse > . Unauthorized ( "Invalid username or password" ) ;
3350 }
3451
52+ // Generate JWT token
3553 var token = _jwtService . GenerateToken ( user ) ;
3654
37- return new LoginResponse
55+ // Create response
56+ var loginResponse = new LoginResponse
3857 {
3958 Token = token ,
4059 RefreshToken = "" ,
41- Expiration = DateTime . Now . AddHours ( 1 )
60+ Expiration = DateTime . Now . AddHours ( 1 ) ,
4261 } ;
62+
63+ return ApiResponse < LoginResponse > . Success ( loginResponse ) ;
4364 }
44- }
65+ }
0 commit comments