11using ApiIntegrationMvc . Areas . Account . Models ;
22using Microsoft . AspNetCore . Mvc ;
3+ using System . Text . Json ;
34using UserManagement . Contracts . Auth ;
45using UserManagement . Sdk . Abstractions ;
56
@@ -9,7 +10,8 @@ namespace ApiIntegrationMvc.Areas.Account.Controllers
910 public class LoginController : Controller
1011 {
1112 private readonly IUserManagementClient _users ;
12- public LoginController ( IUserManagementClient users ) => _users = users ;
13+ private readonly IAccessTokenProvider _cache ;
14+ public LoginController ( IUserManagementClient users , IAccessTokenProvider cache ) => ( _users , _cache ) = ( users , cache ) ;
1315
1416 [ HttpGet ]
1517 [ ResponseCache ( NoStore = true , Location = ResponseCacheLocation . None ) ]
@@ -23,22 +25,44 @@ public IActionResult Index()
2325 [ ValidateAntiForgeryToken ]
2426 public async Task < IActionResult > Index ( LoginViewModel model , CancellationToken ct )
2527 {
26- if ( ! ModelState . IsValid )
28+ try
2729 {
28- return View ( model ) ;
29- }
30+ if ( ! ModelState . IsValid )
31+ {
32+ return View ( model ) ;
33+ }
34+
35+ var req = new LoginRequest ( model . Username , model . Password ) ;
36+ var result = await _users . LoginAsync ( req , ct ) ;
3037
31- var req = new LoginRequest ( model . Username , model . Password ) ;
32- var result = await _users . LoginAsync ( req , ct ) ;
38+ if ( result == null || string . IsNullOrWhiteSpace ( result . Token ) )
39+ {
40+ TempData [ "Error" ] = "Invalid username or password." ;
41+ return RedirectToAction ( nameof ( Index ) ) ; // ← PRG on failure
42+ }
3343
34- if ( result == null || string . IsNullOrWhiteSpace ( result . AccessToken ) )
44+
45+ _cache . SetAccessToken ( result . Token , result . UserId , result . ExpiresAtUtc ) ;
46+
47+ return RedirectToAction ( "Index" , "Home" , new { area = "Home" } ) ;
48+ }
49+ catch ( HttpRequestException hx )
3550 {
36- TempData [ "Error" ] = "Invalid username or password." ;
37- return RedirectToAction ( nameof ( Index ) ) ; // ← PRG on failure
51+ TempData [ "Error" ] = hx . Message ;
52+ return RedirectToAction ( nameof ( Index ) ) ; // ← PRG on failure
53+ }
54+ catch ( JsonException jx )
55+ {
56+ TempData [ "Error" ] = jx . Message ;
57+ return RedirectToAction ( nameof ( Index ) ) ; // ← PRG on failure
58+ }
59+ catch ( Exception ex )
60+ {
61+ TempData [ "Error" ] = "Internal Error. Please contact administrator." ;
62+ return RedirectToAction ( nameof ( Index ) ) ; // ← PRG on failure
3863 }
39-
40- return RedirectToAction ( "Index" , "Home" ) ; // PRG on success too
41-
4264 }
65+
66+
4367 }
4468}
0 commit comments