App login is working
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
@@ -5,90 +6,153 @@ namespace DiunaBI.UI.Shared.Services;
|
||||
|
||||
public class UserInfo
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string FullName { get; set; } = string.Empty;
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string AvatarUrl { get; set; } = string.Empty;
|
||||
}
|
||||
public class AuthService
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly IJSRuntime _jsRuntime;
|
||||
private bool? _isAuthenticated;
|
||||
private UserInfo? _userInfo = null;
|
||||
private string? _apiToken;
|
||||
|
||||
public event Action<bool>? AuthenticationStateChanged;
|
||||
|
||||
public AuthService(IJSRuntime jsRuntime)
|
||||
public AuthService(HttpClient httpClient, IJSRuntime jsRuntime)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_jsRuntime = jsRuntime;
|
||||
}
|
||||
|
||||
public bool IsAuthenticated => _isAuthenticated ?? false;
|
||||
public UserInfo? CurrentUser => _userInfo;
|
||||
|
||||
public async Task<(bool success, string? errorMessage)> ValidateWithBackendAsync(string googleCredential, string fullName, string email, string avatarUrl)
|
||||
{
|
||||
try
|
||||
{
|
||||
Console.WriteLine($"=== ValidateWithBackend: Sending Google credential for {email} ===");
|
||||
|
||||
// Wyślij Google credential do backendu
|
||||
var response = await _httpClient.PostAsJsonAsync("/api/Auth/apiToken", googleCredential);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadFromJsonAsync<ApiTokenResponse>();
|
||||
if (result != null)
|
||||
{
|
||||
_apiToken = result.Token;
|
||||
_userInfo = new UserInfo
|
||||
{
|
||||
Id = result.Id,
|
||||
FullName = fullName,
|
||||
Email = email,
|
||||
AvatarUrl = avatarUrl
|
||||
};
|
||||
|
||||
// Zapisz do localStorage
|
||||
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "api_token", _apiToken);
|
||||
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "user_info", JsonSerializer.Serialize(_userInfo));
|
||||
|
||||
// Ustaw header dla przyszłych requestów
|
||||
_httpClient.DefaultRequestHeaders.Authorization =
|
||||
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _apiToken);
|
||||
|
||||
_isAuthenticated = true;
|
||||
Console.WriteLine($"✅ Backend validation successful. UserId={result.Id}");
|
||||
AuthenticationStateChanged?.Invoke(true);
|
||||
|
||||
return (true, null);
|
||||
}
|
||||
}
|
||||
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
Console.WriteLine("❌ User not found in DiunaBI database");
|
||||
return (false, "Użytkownik nie istnieje w bazie DiunaBI.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"❌ Backend error: {response.StatusCode}");
|
||||
return (false, "Błąd serwera DiunaBI. Spróbuj ponownie.");
|
||||
}
|
||||
|
||||
return (false, "Nieoczekiwany błąd.");
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
Console.WriteLine($"❌ Network error: {ex.Message}");
|
||||
return (false, "Nie można połączyć się z serwerem DiunaBI.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"❌ Validation error: {ex.Message}");
|
||||
return (false, "Błąd podczas weryfikacji użytkownika.");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> CheckAuthenticationAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var token = await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", "google_token");
|
||||
Console.WriteLine("=== AuthService.CheckAuthenticationAsync START ===");
|
||||
|
||||
var token = await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", "api_token");
|
||||
var userInfoJson = await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", "user_info");
|
||||
|
||||
_isAuthenticated = !string.IsNullOrEmpty(token);
|
||||
|
||||
if (_isAuthenticated.Value && !string.IsNullOrEmpty(userInfoJson))
|
||||
{
|
||||
_apiToken = token;
|
||||
_userInfo = JsonSerializer.Deserialize<UserInfo>(userInfoJson);
|
||||
|
||||
// Przywróć header
|
||||
_httpClient.DefaultRequestHeaders.Authorization =
|
||||
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _apiToken);
|
||||
|
||||
Console.WriteLine($"✅ Session restored: {_userInfo?.Email}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("❌ No valid session");
|
||||
}
|
||||
|
||||
Console.WriteLine($"AuthService.CheckAuthentication: token={(!string.IsNullOrEmpty(token) ? "EXISTS" : "NULL")}, isAuth={_isAuthenticated}");
|
||||
Console.WriteLine($"=== AuthService.CheckAuthenticationAsync END (authenticated={_isAuthenticated}) ===");
|
||||
|
||||
return _isAuthenticated.Value;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"AuthService.CheckAuthentication ERROR: {ex.Message}");
|
||||
Console.WriteLine($"❌ CheckAuthentication ERROR: {ex.Message}");
|
||||
_isAuthenticated = false;
|
||||
_userInfo = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SetAuthenticationAsync(string token, UserInfo? userInfo = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "google_token", token);
|
||||
|
||||
if (userInfo != null)
|
||||
{
|
||||
_userInfo = userInfo;
|
||||
var userInfoJson = JsonSerializer.Serialize(userInfo);
|
||||
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "user_info", userInfoJson);
|
||||
}
|
||||
|
||||
_isAuthenticated = true;
|
||||
Console.WriteLine($"AuthService.SetAuthentication: token saved, user={_userInfo?.Email}");
|
||||
AuthenticationStateChanged?.Invoke(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"AuthService.SetAuthentication ERROR: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ClearAuthenticationAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "google_token");
|
||||
Console.WriteLine("=== AuthService.ClearAuthenticationAsync ===");
|
||||
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "api_token");
|
||||
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "user_info");
|
||||
|
||||
_apiToken = null;
|
||||
_isAuthenticated = false;
|
||||
_userInfo = null;
|
||||
Console.WriteLine($"AuthService.ClearAuthentication: token and user ingfo removed");
|
||||
|
||||
_httpClient.DefaultRequestHeaders.Authorization = null;
|
||||
|
||||
Console.WriteLine("✅ Authentication cleared");
|
||||
AuthenticationStateChanged?.Invoke(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"AuthService.ClearAuthentication ERROR: {ex.Message}");
|
||||
Console.WriteLine($"❌ ClearAuthentication ERROR: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,15 +163,13 @@ public class AuthService
|
||||
await CheckAuthenticationAsync();
|
||||
}
|
||||
|
||||
if (_isAuthenticated != true) return null;
|
||||
|
||||
try
|
||||
{
|
||||
return await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", "google_token");
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return _apiToken;
|
||||
}
|
||||
|
||||
private class ApiTokenResponse
|
||||
{
|
||||
public string Token { get; set; } = string.Empty;
|
||||
public Guid Id { get; set; }
|
||||
public DateTime ExpirationTime { get; set; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user