File size: 13,616 Bytes
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01be06d
 
 
3418204
 
 
 
 
691d646
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691d646
 
3418204
 
 
 
 
691d646
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691d646
 
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01be06d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3418204
 
 
01be06d
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01be06d
 
 
 
 
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691d646
3418204
 
 
691d646
3418204
 
 
 
691d646
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3418204
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using TaskTrackingSystem.Shared;
using TaskTrackingSystem.Shared.Models.Auth;
using TaskTrackingSystem.WebApp.Components.Partial;

namespace TaskTrackingSystem.WebApp;

public static class AccountEndpoints
{
    public static void MapAccountEndpoints(this WebApplication app)
    {
        app.MapPost("/account/login", LoginAsync);
        app.MapPost("/account/register", RegisterAsync);
        app.MapPost("/account/reset-password", ResetPasswordAsync);
        app.MapGet("/account/logout", LogoutAsync);
        app.MapPost("/account/logout", LogoutAsync);
    }

    private static async Task<IResult> LoginAsync(
        HttpContext context,
        IHttpClientFactory httpClientFactory,
        MenuAuthorizationService menuAuthorization,
        [FromForm] string usernameOrEmail,
        [FromForm] string password,
        [FromForm] bool? rememberMe,
        [FromForm] string? returnUrl)
    {
        if (string.IsNullOrWhiteSpace(usernameOrEmail) || string.IsNullOrWhiteSpace(password))
        {
            return RedirectToLogin(returnUrl, "invalid");
        }

        HttpResponseMessage response;
        try
        {
            var client = httpClientFactory.CreateClient("WebApi");
            response = await client.PostAsJsonAsync("Auth/login", new LoginDto
            {
                UsernameOrEmail = usernameOrEmail,
                Password = password
            });
        }
        catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or TimeoutException)
        {
            return RedirectToLogin(returnUrl, "unavailable");
        }

        if (!response.IsSuccessStatusCode)
        {
            return RedirectToLogin(returnUrl, "invalid");
        }

        var result = await response.Content.ReadFromJsonAsync<Result<AuthResponseDto>>(Serialization.CaseInsensitive);
        if (result?.IsSuccess != true || result.Value == null || string.IsNullOrWhiteSpace(result.Value.Username))
        {
            return RedirectToLogin(returnUrl, "invalid");
        }

        await SignInUserAsync(context, result.Value, rememberMe ?? false);
        var landingPage = await ResolveLandingPageAsync(menuAuthorization, result.Value);
        return Results.Redirect(GetSafeReturnUrl(returnUrl, landingPage));
    }

    private static async Task<IResult> RegisterAsync(
        HttpContext context,
        IHttpClientFactory httpClientFactory,
        MenuAuthorizationService menuAuthorization,
        [FromForm] RegisterDto registerDto)
    {
        HttpResponseMessage response;
        try
        {
            var client = httpClientFactory.CreateClient("WebApi");
            response = await client.PostAsJsonAsync("Auth/register", registerDto);
        }
        catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or TimeoutException)
        {
            return Results.Redirect($"/register?error={Uri.EscapeDataString("Unable to reach the API server. Please ensure TaskTrackingSystem.WebApi is running.")}");
        }

        string errorMessage = ResultMessages.RegistrationFailed;

        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadFromJsonAsync<Result<AuthResponseDto>>(Serialization.CaseInsensitive);
            if (result?.IsSuccess == true && result.Value != null && !string.IsNullOrWhiteSpace(result.Value.Username))
            {
                await SignInUserAsync(context, result.Value, false);
                var landingPage = await ResolveLandingPageAsync(menuAuthorization, result.Value);
                return Results.Redirect(GetSafeReturnUrl(null, landingPage));
            }
            else if (result != null && !string.IsNullOrEmpty(result.ErrorMessage))
            {
                errorMessage = result.ErrorMessage;
            }
        }
        else
        {
            try
            {
                var contentString = await response.Content.ReadAsStringAsync();
                
                // Try parsing as Result<AuthResponseDto>
                try
                {
                    var result = JsonSerializer.Deserialize<Result<AuthResponseDto>>(contentString, Serialization.CaseInsensitive);
                    if (result != null && !string.IsNullOrEmpty(result.ErrorMessage))
                    {
                        errorMessage = result.ErrorMessage;
                    }
                }
                catch
                {
                    // Ignore and fall back to checking validation errors
                }

                // If no errorMessage from Result, try parsing standard validation errors
                if (errorMessage == ResultMessages.RegistrationFailed)
                {
                    try
                    {
                        using var doc = JsonDocument.Parse(contentString);
                        var root = doc.RootElement;
                        if (root.TryGetProperty("errors", out var errorsProp) && errorsProp.ValueKind == JsonValueKind.Object)
                        {
                            var errorsList = new List<string>();
                            foreach (var prop in errorsProp.EnumerateObject())
                            {
                                foreach (var val in prop.Value.EnumerateArray())
                                {
                                    errorsList.Add(val.GetString() ?? "");
                                }
                            }
                            if (errorsList.Count > 0)
                            {
                                errorMessage = string.Join(" ", errorsList.Where(s => !string.IsNullOrEmpty(s)));
                            }
                        }
                        else if (root.TryGetProperty("errorMessage", out var errMsgProp))
                        {
                            errorMessage = errMsgProp.GetString() ?? errorMessage;
                        }
                    }
                    catch
                    {
                        // Ignore and keep fallback
                    }
                }
            }
            catch
            {
                // Fallback to default
            }
        }

        return Results.Redirect($"/register?error={Uri.EscapeDataString(errorMessage)}");
    }

    private static async Task<IResult> ResetPasswordAsync(
        HttpContext context,
        IHttpClientFactory httpClientFactory,
        [FromForm] ResetPasswordDto resetPasswordDto)
    {
        HttpResponseMessage response;
        try
        {
            var client = httpClientFactory.CreateClient("WebApi");
            response = await client.PostAsJsonAsync("Auth/reset-password", resetPasswordDto);
        }
        catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or TimeoutException)
        {
            return Results.Redirect($"/reset-password?error={Uri.EscapeDataString("Unable to reach the API server. Please ensure TaskTrackingSystem.WebApi is running.")}");
        }

        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadFromJsonAsync<Result>(Serialization.CaseInsensitive);
            if (result?.IsSuccess == true)
            {
                return Results.Redirect("/login?reset=true");
            }
        }

        var errorMessage = "Failed to reset password.";
        if (response.Content != null)
        {
            try
            {
                var contentString = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<Result>(contentString, Serialization.CaseInsensitive);
                if (result != null && !string.IsNullOrWhiteSpace(result.ErrorMessage))
                {
                    errorMessage = result.ErrorMessage;
                }
            }
            catch
            {
                // Keep default error message.
            }
        }

        return Results.Redirect($"/reset-password?error={Uri.EscapeDataString(errorMessage)}");
    }

    private static async Task<IResult> LogoutAsync(HttpContext context, UserSessionState sessionState)
    {
        await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        context.Response.Cookies.Delete(CookieAuthenticationDefaults.AuthenticationScheme);
        sessionState.ClearSession();
        return Results.Redirect("/login?loggedOut=true");
    }

    private static async Task SignInUserAsync(HttpContext context, AuthResponseDto authResult, bool rememberMe)
    {
        var claims = new List<Claim>
        {
            new(ClaimTypes.Name, authResult.Username),
            new(ClaimTypes.Email, authResult.Email)
        };

        if (!string.IsNullOrWhiteSpace(authResult.RoleName))
        {
            claims.Add(new Claim(ClaimTypes.Role, authResult.RoleName));
        }

        if (authResult.RoleId > 0)
        {
            claims.Add(new Claim("role_id", authResult.RoleId.ToString()));
        }

        var userId = TryGetUserIdFromJwt(authResult.Token);
        if (!string.IsNullOrWhiteSpace(userId))
        {
            claims.Add(new Claim(ClaimTypes.NameIdentifier, userId));
        }

        claims.Add(new Claim("jwt_token", authResult.Token));

        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var principal = new ClaimsPrincipal(identity);

        await context.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            principal,
            new AuthenticationProperties
            {
                IsPersistent = rememberMe,
                ExpiresUtc = rememberMe ? DateTimeOffset.UtcNow.AddDays(7) : DateTimeOffset.UtcNow.AddHours(8)
            });
    }

    private static string? TryGetUserIdFromJwt(string token)
    {
        if (string.IsNullOrWhiteSpace(token))
        {
            return null;
        }

        try
        {
            var parts = token.Split('.');
            if (parts.Length < 2)
            {
                return null;
            }

            var payload = parts[1];
            switch (payload.Length % 4)
            {
                case 2: payload += "=="; break;
                case 3: payload += "="; break;
            }

            var json = Convert.FromBase64String(payload);
            var data = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json);
            if (data == null)
            {
                return null;
            }

            if (data.TryGetValue("nameid", out var nameId))
            {
                return nameId.GetString();
            }

            if (data.TryGetValue(ClaimTypes.NameIdentifier, out var fullNameId))
            {
                return fullNameId.GetString();
            }
        }
        catch
        {
            return null;
        }

        return null;
    }

    private static IResult RedirectToLogin(string? returnUrl, string error)
    {
        var safeReturnUrl = string.IsNullOrWhiteSpace(returnUrl)
            ? string.Empty
            : $"&ReturnUrl={Uri.EscapeDataString(returnUrl)}";

        return Results.Redirect($"/login?error={error}{safeReturnUrl}");
    }

    private static string GetSafeReturnUrl(string? returnUrl, string landingPage)
    {
        if (string.IsNullOrWhiteSpace(returnUrl) || !returnUrl.StartsWith('/') || returnUrl.StartsWith("//"))
        {
            return landingPage;
        }

        return returnUrl;
    }

    private static async Task<string> ResolveLandingPageAsync(MenuAuthorizationService menuAuthorization, AuthResponseDto authResult)
    {
        var principal = BuildTemporaryPrincipal(authResult);
        var menus = await menuAuthorization.GetUserMenusAsync(principal);
        var dashboardMenu = FindFirstDashboardMenu(menus);
        return dashboardMenu ?? "/dashboard";
    }

    private static ClaimsPrincipal BuildTemporaryPrincipal(AuthResponseDto authResult)
    {
        var claims = new List<Claim>
        {
            new(ClaimTypes.Name, authResult.Username),
            new(ClaimTypes.Email, authResult.Email),
            new(ClaimTypes.Role, authResult.RoleName),
            new("role_id", authResult.RoleId.ToString()),
            new("jwt_token", authResult.Token)
        };

        return new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));
    }

    private static string? FindFirstDashboardMenu(IEnumerable<TaskTrackingSystem.Shared.Models.Menu.MenuDto> menus)
    {
        foreach (var menu in menus)
        {
            var found = FindFirstDashboardMenu(menu);
            if (!string.IsNullOrWhiteSpace(found))
            {
                return found;
            }
        }

        return null;
    }

    private static string? FindFirstDashboardMenu(TaskTrackingSystem.Shared.Models.Menu.MenuDto menu)
    {
        if (!string.IsNullOrWhiteSpace(menu.MenuUrl) &&
            menu.MenuUrl.StartsWith("/dashboard", StringComparison.OrdinalIgnoreCase))
        {
            return menu.MenuUrl;
        }

        foreach (var subMenu in menu.SubMenus)
        {
            var found = FindFirstDashboardMenu(subMenu);
            if (!string.IsNullOrWhiteSpace(found))
            {
                return found;
            }
        }

        return null;
    }
}