-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
96 lines (80 loc) · 2.77 KB
/
App.xaml.cs
File metadata and controls
96 lines (80 loc) · 2.77 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System.Text;
using Microsoft.Maui.Storage;
using System.Text.Json;
using UserManagementApp.Services;
namespace UserManagementApp
{
public partial class App : Application
{
private readonly IAuthService _authService;
public App(IAuthService authService)
{
InitializeComponent();
_authService = authService;
}
protected override Window CreateWindow(IActivationState activationState)
{
var window = new Window(new ContentPage()); // Temporary placeholder
_ = InitializeAppAsync(window);
return window;
}
private async Task InitializeAppAsync(Window window)
{
var shell = new AppShell();
window.Page = shell;
//await Task.Delay(100); // Give Shell time to initialize
var token = await SecureStorage.GetAsync("access_token");
if (!string.IsNullOrEmpty(token) && !IsTokenExpired(token))
{
await Shell.Current.GoToAsync("///HomePage");
}
else
{
var refreshed = await _authService.TryRefreshTokenAsync();
if (refreshed)
{
await Shell.Current.GoToAsync("///HomePage");
}
else
{
SecureStorage.Remove("access_token");
SecureStorage.Remove("refresh_token");
await Shell.Current.GoToAsync("///LoginPage",true);
}
}
}
private static bool IsTokenExpired(string token)
{
var parts = token.Split('.');
if (parts.Length != 3)
return true;
try
{
var payload = parts[1];
var jsonBytes = Convert.FromBase64String(PadBase64(payload));
var json = Encoding.UTF8.GetString(jsonBytes);
var claims = JsonSerializer.Deserialize<Dictionary<string, object>>(json);
if (claims != null && claims.TryGetValue("exp", out var expValue))
{
var exp = Convert.ToInt64(expValue);
var expiryDate = DateTimeOffset.FromUnixTimeSeconds(exp);
return expiryDate < DateTimeOffset.UtcNow;
}
}
catch
{
return true; // If decoding fails, assume expired
}
return true;
}
private static string PadBase64(string base64)
{
switch (base64.Length % 4)
{
case 2: return base64 + "==";
case 3: return base64 + "=";
default: return base64;
}
}
}
}