login service by localstorg

This commit is contained in:
mmrbnjd
2024-04-18 18:26:12 +03:30
parent fa5a83d8d3
commit 77e004d090
11 changed files with 241 additions and 58 deletions

View File

@@ -0,0 +1,44 @@
using Microsoft.JSInterop;
using System.Text.Json;
namespace Front.Services
{
public interface ILocalStorageService
{
Task<T> GetItem<T>(string key);
Task SetItem<T>(string key, T value);
Task RemoveItem(string key);
}
public class LocalStorageService : ILocalStorageService
{
private IJSRuntime _jsRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task<T> GetItem<T>(string key)
{
var json = await _jsRuntime.InvokeAsync<string>("localStorage.getItem", key);
if (json == null)
return default;
return JsonSerializer.Deserialize<T>(json);
}
public async Task SetItem<T>(string key, T value)
{
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, JsonSerializer.Serialize(value));
}
public async Task RemoveItem(string key)
{
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", key);
}
}
}

View File

@@ -0,0 +1,39 @@
using Shared.DTOs;
using System.Net.Http.Json;
namespace Front.Services
{
public class MidLevel
{
private readonly ILocalStorageService _localStorage;
private readonly UserAuthenticationDTO _user;
private readonly HttpClient _httpClient;
public MidLevel(ILocalStorageService localStorage, UserAuthenticationDTO user, HttpClient httpClient)
{
_localStorage = localStorage;
_user = user;
_httpClient = httpClient;
}
public async Task InitAsync()
{
var token = await _localStorage.GetItem<string>("token");
if (!string.IsNullOrEmpty(token))
{
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
var request = await _httpClient.GetAsync("User/CheckAuthenticate");
if (request.IsSuccessStatusCode)
{
var userinfomodel = await request.Content.ReadFromJsonAsync<UserAuthenticationDTO>();
_user.Token = token;
_user.Company = userinfomodel?.Company;
_user.FullName = userinfomodel.FullName;
_user.Photo = userinfomodel.Photo;
_user.exitDate = userinfomodel.exitDate;
_user.enterDate = userinfomodel.enterDate;
}
}
}
}
}

View File

@@ -0,0 +1,19 @@
using Shared.DTOs;
namespace Front.Services
{
public class localService
{
private readonly UserAuthenticationDTO _user;
public localService(UserAuthenticationDTO user)
{
_user = user;
}
public async Task<bool> OnlineUser()
{
if (_user != null && !string.IsNullOrEmpty(_user.Token) && _user.exitDate.AddMinutes(-5) > DateTime.Now)
return true;
return false;
}
}
}