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,9 @@
using Shared.DTOs;
namespace Front
{
public static class Fixedvalues
{
public static UserAuthenticationDTO Userinfo=new UserAuthenticationDTO();
}
}

View File

@@ -1,8 +1,9 @@
@page "/Register"
@using Front.Services
@using Shared.DTOs
@inject HttpClient _hc
@inject NavigationManager nav
@inject UserAuthenticationDTO userinfo
@inject localService localserv;
<PageTitle>ثبت نام</PageTitle>
<main>
@@ -89,11 +90,13 @@
protected override async Task OnInitializedAsync()
{
if (userinfo!=null)
nav.NavigateTo("/");
editContext = new EditContext(model);
messageStore = new(editContext);
if (await localserv.OnlineUser())
nav.NavigateTo("/");
await base.OnInitializedAsync();
}
}

View File

@@ -1,9 +1,11 @@
@page "/Sign-in"
@using Front.Services
@using Shared.DTOs
@inject ILocalStorageService Storage;
@inject UserAuthenticationDTO userinfo
@inject localService localserv;
@inject HttpClient _hc
@inject NavigationManager nav
@inject UserAuthenticationDTO userinfo
<PageTitle>ورود</PageTitle>
<main>
@@ -41,7 +43,7 @@
<div class="signin-banner-title-box">
<h4 class="signin-banner-from-title">ورود به سیستم</h4>
</div>
<div class="signin-banner-from-box">
<EditForm Model="Model" OnValidSubmit="OnLoginClick">
<DataAnnotationsValidator />
@@ -54,7 +56,7 @@
<div class="col-12">
<div class="postbox__comment-input mb-30">
<InputText @bind-Value="Model.Username" id="Username" type="text" class="inputText" required="" />
<span class="floating-label">نام کاربری</span>
</div>
</div>
@@ -86,29 +88,29 @@
</div>
</div>
</div>
<div class="signin-banner-form-remember">
<div class="row">
<div class="col-6">
<div class="postbox__comment-agree">
<div class="form-check">
<div class="signin-banner-form-remember">
<div class="row">
<div class="col-6">
<div class="postbox__comment-agree">
<div class="form-check">
<InputCheckbox @bind-Value="Model.Remember" id="Remember" class="form-check-input" type="checkbox" />
<label class="form-check-label" for="flexCheckDefault">
مرا به یاد داشته باش
</label>
<label class="form-check-label" for="flexCheckDefault">
مرا به یاد داشته باش
</label>
</div>
</div>
</div>
<div class="col-6">
<div class="postbox__forget text-end">
<a href="#">رمز عبور را فراموش کرده اید؟</a>
</div>
</div>
</div>
<div class="col-6">
<div class="postbox__forget text-end">
<a href="#">رمز عبور را فراموش کرده اید؟</a>
</div>
</div>
</div>
</div>
<div class="signin-banner-from-btn mb-20">
<button class="signin-btn ">ورود</button>
</div>
<div class="signin-banner-from-btn mb-20">
<button class="signin-btn ">ورود</button>
</div>
</EditForm>
<div class="row">
<Alert hidden="@Hidealert" Color="@alertColor" Dismissable="false">
@@ -132,19 +134,21 @@
@code {
[SupplyParameterFromForm]
public Authentication? Model { get; set; }
protected override void OnInitialized() => Model ??= new();
public Authentication? Model { get; set; }
// alert
AlertColor alertColor = AlertColor.Primary;
IconName alertIconName = IconName.CheckCircleFill;
bool Hidealert = true;
string alertMessage = "";
// protected override async Task OnInitializedAsync()
// {
// var t1 = userinfo;
// var t2 = _hc;
// await base.OnInitializedAsync();
// }
protected override async Task OnInitializedAsync()
{
if (await localserv.OnlineUser())
nav.NavigateTo("/");
Model ??= new();
await base.OnInitializedAsync();
}
}
@functions {
private void ShowDangerAlert(string msg)
@@ -154,24 +158,38 @@
alertIconName = IconName.ExclamationTriangleFill;
alertMessage = msg;
}
private async Task EndForm() =>nav.NavigateTo("/");
private async Task EndForm() => nav.NavigateTo("/");
private async Task OnLoginClick()
{
var request = await _hc.PostAsJsonAsync("User/authenticate", Model);
var request = await _hc.PostAsJsonAsync("User/authenticate", Model);
if (request.IsSuccessStatusCode)
{
userinfo = await request.Content.ReadFromJsonAsync<UserAuthenticationDTO>();
var userinfomodel = await request.Content.ReadFromJsonAsync<UserAuthenticationDTO>();
_hc.DefaultRequestHeaders.Clear();
_hc.DefaultRequestHeaders.Add("Authorization",
$"Bearer {userinfo?.Token}");
$"Bearer {userinfomodel?.Token}");
if (Model.Remember)
Storage.SetItem("token", userinfomodel?.Token);
userinfo.Token = userinfomodel?.Token;
userinfo.Company = userinfomodel?.Company;
userinfo.FullName = userinfomodel.FullName;
userinfo.Photo = userinfomodel.Photo;
userinfo.exitDate = userinfomodel.exitDate;
userinfo.enterDate = userinfomodel.enterDate;
nav.NavigateTo("/");
}
else if (request.StatusCode==System.Net.HttpStatusCode.NotFound)
ShowDangerAlert("کاربری با این مشخصات یافت نشد");
else if (request.StatusCode == System.Net.HttpStatusCode.NotFound)
ShowDangerAlert("کاربری با این مشخصات یافت نشد");
else ShowDangerAlert("خطای سیستمی");
}
}

View File

@@ -3,12 +3,17 @@ using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Front;
using System.Globalization;
using Shared.DTOs;
using Front.Services;
using System.ComponentModel.Design;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddBlazorBootstrap();
builder.Services.AddScoped<UserAuthenticationDTO>();
builder.Services.AddScoped<ILocalStorageService, LocalStorageService>();
builder.Services.AddScoped<localService>();
builder.Services.AddScoped(sp => new UserAuthenticationDTO());
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7075/api/") });
@@ -17,5 +22,14 @@ builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https:/
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("fa-Ir");
await builder.Build().RunAsync();
var host = builder.Build();
await new MidLevel(
host.Services.GetRequiredService<ILocalStorageService>(),
host.Services.GetRequiredService<UserAuthenticationDTO>(),
host.Services.GetRequiredService<HttpClient>()
).InitAsync();
await host.RunAsync();

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;
}
}
}