using Blazored.LocalStorage; using HotelPms.Client.Blazor.Util; using HotelPms.Data; using Grpc.Net.Client; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Threading.Channels; using System.Threading.Tasks; using HotelPms.DataAccessGrpc.Client; namespace HotelPms.Client.Blazor.Services { internal class AuthService : IAuthService { private readonly GrpcChannel Channel; private readonly AuthenticationStateProvider _authenticationStateProvider; private readonly ILocalStorageService _localStorage; public AuthService(GrpcChannel channel, AuthenticationStateProvider authenticationStateProvider, ILocalStorageService localStorage) { Channel = channel; _authenticationStateProvider = authenticationStateProvider; _localStorage = localStorage; } public async Task Login(string loginID, string passwordl) { using (AuthAccess access = new AuthAccess(Channel)) { LoginResult result = await access.LoginAsync(loginID, passwordl); var options = new JsonSerializerOptions { WriteIndented = true }; if (result.ErrNo != 0) { return result; } await _localStorage.SetItemAsync("authToken", result.AccessToKen); ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(result.AccessToKen); ApiAuthenticationStateProvider.AccessToken = result.AccessToKen; return result; } } public async Task Logout(string loginID) { using (AuthAccess access = new AuthAccess(Channel)) { LoginResult result = await access.LogoutAsync(loginID); var options = new JsonSerializerOptions { WriteIndented = true }; if (result.ErrNo != 0) { return result; } await _localStorage.RemoveItemAsync("authToken"); ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsLoggedOut(); ApiAuthenticationStateProvider.AccessToken = null; return result; } } } }