From fa5a83d8d34f156b73e464be4cbff2ffaab97756 Mon Sep 17 00:00:00 2001 From: mmrbnjd Date: Thu, 18 Apr 2024 00:33:46 +0330 Subject: [PATCH] ... --- Back/Back.csproj | 2 +- Back/Controllers/UserController.cs | 10 ++++- Back/Program.cs | 22 +++++++++++ Back/Services/servUser.cs | 32 ++++++++-------- TaxPayerFull/Pages/Register.razor | 4 ++ TaxPayerFull/Pages/Sign-in.razor | 61 +++++++++++++++++++++++------- TaxPayerFull/Program.cs | 6 ++- 7 files changed, 101 insertions(+), 36 deletions(-) diff --git a/Back/Back.csproj b/Back/Back.csproj index 2ec34d7..fe98d24 100644 --- a/Back/Back.csproj +++ b/Back/Back.csproj @@ -35,7 +35,7 @@ - ..\..\..\LocalGit\TaxPayerTools\Service\bin\Debug\Service.dll + ..\..\Dlls\Service.dll diff --git a/Back/Controllers/UserController.cs b/Back/Controllers/UserController.cs index dd96d6c..315d1e0 100644 --- a/Back/Controllers/UserController.cs +++ b/Back/Controllers/UserController.cs @@ -7,6 +7,7 @@ using Shared.DTOs; namespace Back.Controllers { [Route("api/[controller]")] + [Authorize] [ApiController] public class UserController : ControllerBase { @@ -19,12 +20,17 @@ namespace Back.Controllers } [HttpPost("authenticate")] [AllowAnonymous] - public async Task> Login(Authentication model) + public async Task> Login([FromBody]Authentication model) { - if (!ModelState.IsValid) return BadRequest(model); var result = await _servUser.UserAuthentication(model.Username, model.Password); if (result != null) return Ok(result); else return NotFound("کاربری با این مشخصات یافت نشد"); + } + [HttpGet("test")] + + public async Task test() + { + return Ok(); diff --git a/Back/Program.cs b/Back/Program.cs index 0d0ec22..3b3a30d 100644 --- a/Back/Program.cs +++ b/Back/Program.cs @@ -1,8 +1,11 @@ +using Back; using Back.Data.Contracts; using Back.Data.Infrastructure.Repository; using Back.Services; using Back.Validations; using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; +using System.Text; using TaxPayer.Infrastructure.Persistence; var builder = WebApplication.CreateBuilder(args); @@ -46,6 +49,24 @@ builder.Services.AddCors(options => }); }); +#region JWT +builder.Services.AddAuthentication("Bearer") + .AddJwtBearer(options => + { + options.TokenValidationParameters = new() + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateIssuerSigningKey = true, + ValidIssuer = Fixedvalues.Issuer, + ValidAudience = Fixedvalues.Audience, + IssuerSigningKey = new SymmetricSecurityKey( + Encoding.ASCII.GetBytes(Fixedvalues.SecretForKey)) + }; + } + ); +#endregion + var app = builder.Build(); // Configure the HTTP request pipeline. @@ -57,6 +78,7 @@ if (app.Environment.IsDevelopment()) app.UseHttpsRedirection(); app.UseCors(origins); +app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); diff --git a/Back/Services/servUser.cs b/Back/Services/servUser.cs index 48647ff..938cdad 100644 --- a/Back/Services/servUser.cs +++ b/Back/Services/servUser.cs @@ -13,18 +13,16 @@ namespace Back.Services public class servUser { private readonly IConfiguration _configuration; - private readonly CheckPermission _checkPermission; - private readonly servPermission _servPermission; + private readonly servNotification _servNotification; private readonly IAsyncRepository _RepoUser; private readonly IAsyncRepository _RepoPermissionPeriod; - public servUser(IConfiguration configuration, - CheckPermission checkPermission, servPermission servPermission - , servNotification servNotification, IAsyncRepository RepoUser, IAsyncRepository RepoPermissionPeriod) + public servUser(IConfiguration configuration + , servNotification servNotification + , IAsyncRepository RepoUser + , IAsyncRepository RepoPermissionPeriod) { _configuration = configuration; - _checkPermission = checkPermission; - _servPermission = servPermission; _servNotification = servNotification; _RepoUser = RepoUser; _RepoPermissionPeriod = RepoPermissionPeriod; @@ -32,16 +30,16 @@ namespace Back.Services public async Task GetUserByUserNameAndPassword(string UserName, string Password) { return await _RepoUser.Get(w => w.Username == UserName && w.Password == Password.encrypted() && w.IsActive) - .Include(i => i.RolUsers) - .ThenInclude(ti => ti.rolePermissions) - .Include(i => i.RolUsers) - .ThenInclude(ti=>ti.Company) - .ThenInclude(ti => ti.PermissionPeriods) - .ThenInclude(ti => ti.Permission) + // .Include(i => i.RolUsers) + // .ThenInclude(ti => ti.rolePermissions) + // .Include(i => i.RolUsers) + // .ThenInclude(ti=>ti.Company) + //.ThenInclude(ti => ti.PermissionPeriods) + // .ThenInclude(ti => ti.Permission) .Include(ti=>ti.RolUsers) .ThenInclude(ti => ti.Company) - .ThenInclude(ti => ti.PermissionPeriods) - .ThenInclude(ti => ti.CalculationType) + //.ThenInclude(ti => ti.PermissionPeriods) + // .ThenInclude(ti => ti.CalculationType) .FirstOrDefaultAsync(); } public async Task UserAuthentication(string UserNameORUserID, string Password="") @@ -158,7 +156,7 @@ namespace Back.Services { return await _RepoUser.Get(w => w.ID == UserID).FirstOrDefaultAsync(); } - public async void SetTokenAndDateLogininDB(int UserID,string Token) + public async Task SetTokenAndDateLogininDB(int UserID,string Token) { var user = await GetUserByUserID(UserID); if (user != null) @@ -274,7 +272,7 @@ namespace Back.Services string Token = new JwtSecurityTokenHandler() .WriteToken(jwtSecurityToke); - SetTokenAndDateLogininDB(UserId, Token); + await SetTokenAndDateLogininDB(UserId, Token); //_contextMongodb.InsertItem(new SysLog() //{ // TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier, diff --git a/TaxPayerFull/Pages/Register.razor b/TaxPayerFull/Pages/Register.razor index e520c62..69f6dd2 100644 --- a/TaxPayerFull/Pages/Register.razor +++ b/TaxPayerFull/Pages/Register.razor @@ -2,6 +2,7 @@ @using Shared.DTOs @inject HttpClient _hc @inject NavigationManager nav +@inject UserAuthenticationDTO userinfo ثبت نام
@@ -88,6 +89,9 @@ protected override async Task OnInitializedAsync() { + if (userinfo!=null) + nav.NavigateTo("/"); + editContext = new EditContext(model); messageStore = new(editContext); await base.OnInitializedAsync(); diff --git a/TaxPayerFull/Pages/Sign-in.razor b/TaxPayerFull/Pages/Sign-in.razor index d8207c4..3233951 100644 --- a/TaxPayerFull/Pages/Sign-in.razor +++ b/TaxPayerFull/Pages/Sign-in.razor @@ -1,6 +1,9 @@ @page "/Sign-in" @using Shared.DTOs +@inject HttpClient _hc +@inject NavigationManager nav +@inject UserAuthenticationDTO userinfo ورود
@@ -107,6 +110,15 @@ +
+ + + +
@@ -120,25 +132,46 @@ @code { [SupplyParameterFromForm] - public Authentication? Model { get; set; } + public Authentication? Model { get; set; } protected override void OnInitialized() => Model ??= new(); + // 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(); + // } } @functions { - + private void ShowDangerAlert(string msg) + { + Hidealert = false; + alertColor = AlertColor.Danger; + alertIconName = IconName.ExclamationTriangleFill; + alertMessage = msg; + } + private async Task EndForm() =>nav.NavigateTo("/"); + + private async Task OnLoginClick() { - var request = await _hc.PostAsJsonAsync("User/authenticate", Model); - // if (request.IsSuccessStatusCode) - // { - // messageStore?.Clear(); - // var VerificationID = await request.Content.ReadFromJsonAsync(); - // nav.NavigateTo($"Verification/{VerificationID}"); - // } - // else - // { - // var error = await request.Content.ReadFromJsonAsync>(); - // messageStore?.Add(() => model.Mobile, error); + var request = await _hc.PostAsJsonAsync("User/authenticate", Model); + if (request.IsSuccessStatusCode) + { + userinfo = await request.Content.ReadFromJsonAsync(); - // } + _hc.DefaultRequestHeaders.Add("Authorization", + $"Bearer {userinfo?.Token}"); + + } + else if (request.StatusCode==System.Net.HttpStatusCode.NotFound) + ShowDangerAlert("کاربری با این مشخصات یافت نشد"); + + else ShowDangerAlert("خطای سیستمی"); + } } \ No newline at end of file diff --git a/TaxPayerFull/Program.cs b/TaxPayerFull/Program.cs index 0d7c9f3..26bd7af 100644 --- a/TaxPayerFull/Program.cs +++ b/TaxPayerFull/Program.cs @@ -2,16 +2,18 @@ using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Front; using System.Globalization; +using Shared.DTOs; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); builder.Services.AddBlazorBootstrap(); +builder.Services.AddScoped(); -//builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7075/api/") }); +builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7075/api/") }); -builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("http://localhost:5271/api/") }); +//builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("http://localhost:5271/api/") }); CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("fa-Ir");