forked from microsoft/github-copilot-vibe-coding-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthService.cs
More file actions
72 lines (61 loc) · 1.88 KB
/
Copy pathAuthService.cs
File metadata and controls
72 lines (61 loc) · 1.88 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
using System.Text.Json;
using Contoso.BlazorApp.Models;
using Microsoft.JSInterop;
namespace Contoso.BlazorApp.Services;
public class AuthService
{
private readonly IJSRuntime _jsRuntime;
private AuthState _authState = new();
public event Action? OnAuthStateChanged;
public AuthService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public AuthState AuthState => _authState;
public async Task InitializeAsync()
{
try
{
var userJson = await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", "user");
if (!string.IsNullOrEmpty(userJson))
{
var user = JsonSerializer.Deserialize<User>(userJson);
_authState.User = user;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error initializing auth: {ex.Message}");
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "user");
}
finally
{
_authState.IsLoading = false;
OnAuthStateChanged?.Invoke();
}
}
public async Task<User> LoginAsync(string username)
{
_authState.IsLoading = true;
OnAuthStateChanged?.Invoke();
try
{
var userData = new User { Username = username.Trim() };
_authState.User = userData;
var userJson = JsonSerializer.Serialize(userData);
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "user", userJson);
return userData;
}
finally
{
_authState.IsLoading = false;
OnAuthStateChanged?.Invoke();
}
}
public async Task LogoutAsync()
{
_authState.User = null;
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "user");
OnAuthStateChanged?.Invoke();
}
}