From c61e413ebb92ce1f07f130e7f9fed57daa61db2f Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 22 May 2024 10:36:45 +0200 Subject: [PATCH] Authorization added to admin and API, transferdetails, editmytransfer --- TIAM.Entities/Transfers/Transfer.cs | 5 +- TIAMMobileApp/Main.razor | 26 +- TIAMMobileApp/MauiProgram.cs | 3 + TIAMSharedUI/Pages/AppLaunchComponent.razor | 6 +- TIAMSharedUI/Pages/ChatPage.razor | 9 + TIAMSharedUI/Pages/EditTransfers.razor | 283 ++++++++++++++++++ TIAMSharedUI/Pages/Login.razor.cs | 12 +- TIAMSharedUI/Pages/TicTacToe.razor | 117 ++++++++ TIAMSharedUI/Pages/TicTacToe.razor.css | 25 ++ TIAMSharedUI/Pages/TransferOrderDetails.razor | 2 +- TIAMSharedUI/Shared/AdminLayout.razor | 2 + TIAMSharedUI/wwwroot/css/TourIAm.css | 4 +- TIAMWebApp/Client/App.razor | 25 +- TIAMWebApp/Client/Program.cs | 7 +- TIAMWebApp/Client/TIAMWebApp.Client.csproj | 1 + .../Controllers/TransferDataAPIController.cs | 21 +- TIAMWebApp/Server/Program.cs | 2 + TIAMWebApp/Server/Services/AuthService.cs | 26 ++ TIAMWebApp/Server/Services/GameHub.cs | 37 +++ .../Services/CustomAuthStateProvider.cs | 78 +++++ .../Shared/Services/TransferDataService.cs | 9 +- .../TIAMWebApp.Shared.Application.csproj | 1 + 22 files changed, 677 insertions(+), 24 deletions(-) create mode 100644 TIAMSharedUI/Pages/EditTransfers.razor create mode 100644 TIAMSharedUI/Pages/TicTacToe.razor create mode 100644 TIAMSharedUI/Pages/TicTacToe.razor.css create mode 100644 TIAMWebApp/Server/Services/AuthService.cs create mode 100644 TIAMWebApp/Server/Services/GameHub.cs create mode 100644 TIAMWebApp/Shared/Services/CustomAuthStateProvider.cs diff --git a/TIAM.Entities/Transfers/Transfer.cs b/TIAM.Entities/Transfers/Transfer.cs index 6238d728..ce362742 100644 --- a/TIAM.Entities/Transfers/Transfer.cs +++ b/TIAM.Entities/Transfers/Transfer.cs @@ -22,10 +22,7 @@ public class Transfer: IEntityGuid, IAcFullName, ITimeStampInfo, IProductForeign public Guid UserId { get; set; } public Guid? ProductId { get; set; } - //public Guid? UserProductMappingId { get; set; } - //public Guid? UserProductToCarId { get; set; } - - //public virtual UserProductMapping? UserProductMapping { get; set; } + public virtual List TransferToDrivers { get; set; } [Required] public TransferStatusType TransferStatusType { get; set; } = TransferStatusType.OrderSubmitted; diff --git a/TIAMMobileApp/Main.razor b/TIAMMobileApp/Main.razor index f75987b0..c76e8267 100644 --- a/TIAMMobileApp/Main.razor +++ b/TIAMMobileApp/Main.razor @@ -1,6 +1,7 @@ -@using TIAMSharedUI.Shared +@using Microsoft.AspNetCore.Components.Authorization +@using TIAMSharedUI.Shared - +@* @@ -10,4 +11,23 @@

Sorry, there's nothing at this address.

-
+
*@ + + + + + + +

Sorry dude, but you're not authorized!

+
+
+ +
+ + Not found + +

Sorry, there's nothing at this address.

+
+
+
+
diff --git a/TIAMMobileApp/MauiProgram.cs b/TIAMMobileApp/MauiProgram.cs index 4e1a597d..f3620ab2 100644 --- a/TIAMMobileApp/MauiProgram.cs +++ b/TIAMMobileApp/MauiProgram.cs @@ -9,6 +9,7 @@ using TIAMWebApp.Shared.Application.Services; using BlazorAnimation; using AyCode.Core.Loggers; using AyCode.Services.Loggers; +using Microsoft.AspNetCore.Components.Authorization; namespace TIAMMobileApp { @@ -64,6 +65,8 @@ namespace TIAMMobileApp builder.Services.AddSingleton(x => new ResourceManager("TIAMWebApp.Shared.Application.Resources", typeof(Main).Assembly)); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddScoped(); + builder.Services.AddAuthorizationCore(); builder.Services.Configure(Guid.NewGuid().ToString(), c => { }); return builder.Build(); } diff --git a/TIAMSharedUI/Pages/AppLaunchComponent.razor b/TIAMSharedUI/Pages/AppLaunchComponent.razor index 8ba65f5b..d35aa380 100644 --- a/TIAMSharedUI/Pages/AppLaunchComponent.razor +++ b/TIAMSharedUI/Pages/AppLaunchComponent.razor @@ -1,4 +1,5 @@ @* @page "/"; *@ +@using Microsoft.AspNetCore.Components.Authorization @using TIAMWebApp.Shared.Application.Interfaces @using TIAMWebApp.Shared.Application.Models @using TIAMWebApp.Shared.Application.Utility @@ -19,6 +20,7 @@ @inject ISessionService sessionService; @inject HttpClient http; @inject IComponentUpdateService ComponentUpdateService +@inject AuthenticationStateProvider AuthStateProvider @{ if (string.IsNullOrWhiteSpace(TrackingId)) @@ -83,7 +85,9 @@ if (isTokenRefreshed) { + await AuthStateProvider.GetAuthenticationStateAsync(); _logger.Info("Token refreshed"); + } else { @@ -97,7 +101,7 @@ else { _logger.Info("Valid token found"); - + await AuthStateProvider.GetAuthenticationStateAsync(); } string _userId = jsontoken.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value; diff --git a/TIAMSharedUI/Pages/ChatPage.razor b/TIAMSharedUI/Pages/ChatPage.razor index a54b6fd5..9d633a21 100644 --- a/TIAMSharedUI/Pages/ChatPage.razor +++ b/TIAMSharedUI/Pages/ChatPage.razor @@ -30,14 +30,23 @@ + + TicTacToe + + Create Payment + + My trasnfers + + @code { private string userName; private string newMessage; private List messages = new List(); + //private string hrefString = "mytransfers/" + "108E5A63-AA9E-47BE-ACFA-00306FFC5215"; protected override async Task OnInitializedAsync() { diff --git a/TIAMSharedUI/Pages/EditTransfers.razor b/TIAMSharedUI/Pages/EditTransfers.razor new file mode 100644 index 00000000..ef9085b1 --- /dev/null +++ b/TIAMSharedUI/Pages/EditTransfers.razor @@ -0,0 +1,283 @@ +@page "/mytransfers/{transferId:guid}" +@using TIAM.Entities.Transfers +@using TIAMWebApp.Shared.Application.Interfaces +@using AyCode.Core.Loggers +@using AyCode.Services.Loggers +@using TIAM.Core.Loggers +@using TIAM.Core.Enums +@using TIAMWebApp.Shared.Application.Utility +@inject HttpClient Http +@inject NavigationManager navManager +@inject IEnumerable LogWriters +@inject ITransferDataService transferDataService +Transfer details +
+

Transfer details

+

Manage your transfer here

+
+ +@if (isLoading) +{ +
+ +
+ +} +else if (!string.IsNullOrEmpty(errorMessage)) +{ +
@errorMessage
+} +else +{ +
+ + @if (!editMode) + { +
+
+
+
+
+
+
+
+ Transfer identifier: @transfer.Id +

@transfer.ContactPhone

+
+
+
+
+
+
+

Passenger: @transfer.FullName

+

E-mail address: @transfer.ContactEmail

+
From: @transfer.FromAddress
+
To: @transfer.ToAddress
+
@transfer.Appointment.ToString("MMMM dd, yyyy")
+
@transfer.Appointment.ToString("hh:mm tt")
+

Passengers: @transfer.PassengerCount

+

Luggage: @transfer.LuggageCount

+

Flight number (optional): @transfer.FlightNumber

+
+

License plate: POX-382

+

Car looks: Silver, Toyota, Prius

+
+

Status on: @DateTime.Now.ToString("hh:mm tt"), @DateTime.Today.ToString("MMMM dd, yyyy")

+
+
+
+

EUR @transfer.Price

+
+
+ +
+
+
+
+
+ + } + + else + { + + +
+
+
+
+ +
+
+
+
+ Transfer identifier: @transfer.Id +

+ + + +

+
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

License plate: POX-382

+

Car looks: Silver, Toyota, Prius

+
+

Status on: @DateTime.Now.TimeOfDay, @DateTime.Today.Date

+
+ + +
+ + +
+

EUR @transfer.Price via (COD)

+
+
+ + + +
+
+ +
+
+
+
+
+
+ + + } + +
+} + +@code { + [Parameter] + public Guid transferId { get; set; } = Guid.Empty; + + private Transfer transfer = new Transfer(); + private bool isLoading = true; + private string errorMessage = string.Empty; + + private LoggerClient _logger; + + List StatusTypes = new List(); + private bool editMode = false; + + protected override async Task OnInitializedAsync() + { + foreach (var t in Enum.GetValues(typeof(TransferStatusType)).OfType().ToList()) + StatusTypes.Add(t.ToString()); + + _logger = new LoggerClient(LogWriters.ToArray()); + _logger.Info($"parameter: {transferId.ToString()}"); + await LoadTransfer(); + } + + protected override async Task OnParametersSetAsync() + { + _logger.Info($"on parameter set: {transferId.ToString()}"); + base.OnParametersSet(); + } + + private void SetEditMode() + { + editMode = true; + } + + private async Task LoadTransfer() + { + try + { + var response = await transferDataService.GetTransferByIdAsync(transferId); + + if (response != null) + { + transfer = response; + } + + else + { + errorMessage = $"Error loading transfer: {transfer.Id}"; + } + } + catch (Exception ex) + { + errorMessage = $"Exception: {ex.Message}"; + } + isLoading = false; + } + + private async Task UpdateTransfer() + { + try + { + var result = await transferDataService.UpdateTransferAsync(transfer); + if (result) + { + navManager.NavigateTo("/mytransfers"); // Redirect to a list or another page after successful update + } + else + { + errorMessage = $"Error updating transfer: {result.ToString()}"; + } + } + catch (Exception ex) + { + errorMessage = $"Exception: {ex.Message}"; + } + } +} diff --git a/TIAMSharedUI/Pages/Login.razor.cs b/TIAMSharedUI/Pages/Login.razor.cs index d0fdbbfb..55074c72 100644 --- a/TIAMSharedUI/Pages/Login.razor.cs +++ b/TIAMSharedUI/Pages/Login.razor.cs @@ -15,6 +15,7 @@ using AyCode.Blazor.Components; using AyCode.Core.Loggers; using AyCode.Services.Loggers; using Azure.Core; +using Microsoft.AspNetCore.Components.Authorization; namespace TIAMSharedUI.Pages { @@ -35,9 +36,12 @@ namespace TIAMSharedUI.Pages public IStringLocalizer localizer { get; set; } [Inject] public ISessionService sessionService { get; set; } - + + [Inject] + public AuthenticationStateProvider AuthStateProvider { get; set; } + //fill loginmodel with fake but valid data - + //LoginModel loginModel = new(); //[Display(Name = "LoginTitleText", ResourceType = typeof(MyResources))] @@ -101,8 +105,8 @@ namespace TIAMSharedUI.Pages //save to local storage await secureStorageHandler.SaveToSecureStorageAsync(nameof(Setting.UserBasicDetails), userBasicDetailsJson); - - + await AuthStateProvider.GetAuthenticationStateAsync(); + if (!mainResponse.IsSuccess) { diff --git a/TIAMSharedUI/Pages/TicTacToe.razor b/TIAMSharedUI/Pages/TicTacToe.razor new file mode 100644 index 00000000..558a6ff1 --- /dev/null +++ b/TIAMSharedUI/Pages/TicTacToe.razor @@ -0,0 +1,117 @@ +@page "/tictactoe" +@using Microsoft.AspNetCore.SignalR.Client +@using AyCode.Core.Loggers +@using AyCode.Services.Loggers +@using TIAM.Core.Loggers +@using TIAMWebApp.Shared.Application.Utility +@inject NavigationManager Navigation +@inject IEnumerable LogWriters + +

Tic Tac Toe

+ +
+ @for (int i = 0; i < 3; i++) + { +
+ @for (int j = 0; j < 3; j++) + { + + } +
+ } +
+ +
+ @if (!string.IsNullOrEmpty(winner)) + { +

@winner wins!

+ } + else if (board.Cast().All(cell => cell != null)) + { +

It's a draw!

+ } + else + { +

Next player: @currentPlayer

+ } +
+ +@code { + private string[,] board = new string[3, 3]; + private string currentPlayer = "X"; + private string winner; + private HubConnection hubConnection; + private string groupName = "tictactoe"; + private LoggerClient _logger; + + protected override async Task OnInitializedAsync() + { + _logger = new LoggerClient(LogWriters.ToArray()); + hubConnection = new HubConnectionBuilder() + .WithUrl(Navigation.ToAbsoluteUri("/gamehub")) + .Build(); + + hubConnection.On("ReceiveMove", (row, col, player) => + { + if (row >= 0 && row < 3 && col >= 0 && col < 3) + { + board[row, col] = player; + if (CheckWinner()) + { + winner = player; + } + StateHasChanged(); + } + }); + + await hubConnection.StartAsync(); + await JoinGameGroup(); + } + + private async Task JoinGameGroup() + { + await hubConnection.SendAsync("JoinGame", groupName); + } + + private async Task MakeMove(int row, int col) + { + _logger.DetailConditional($"row: {row}, col: {col}"); + if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row, col] == null && winner == null) + { + board[row, col] = currentPlayer; + if (CheckWinner()) + { + winner = currentPlayer; + } + await hubConnection.SendAsync("MakeMove", groupName, row, col, currentPlayer); + currentPlayer = currentPlayer == "X" ? "O" : "X"; + } + } + + private bool CheckWinner() + { + // Check rows, columns and diagonals for a win + for (int i = 0; i < 3; i++) + { + if (board[i, 0] != null && board[i, 0] == board[i, 1] && board[i, 1] == board[i, 2]) + { + return true; + } + if (board[0, i] != null && board[0, i] == board[1, i] && board[1, i] == board[2, i]) + { + return true; + } + } + if (board[0, 0] != null && board[0, 0] == board[1, 1] && board[1, 1] == board[2, 2]) + { + return true; + } + if (board[0, 2] != null && board[0, 2] == board[1, 1] && board[1, 1] == board[2, 0]) + { + return true; + } + return false; + } +} diff --git a/TIAMSharedUI/Pages/TicTacToe.razor.css b/TIAMSharedUI/Pages/TicTacToe.razor.css new file mode 100644 index 00000000..cb1c7c1e --- /dev/null +++ b/TIAMSharedUI/Pages/TicTacToe.razor.css @@ -0,0 +1,25 @@ +.game-board { + display: grid; + grid-template-columns: repeat(3, 100px); + gap: 10px; + margin-bottom: 20px; +} + +.board-row { + display: contents; +} + +.square { + width: 100px; + height: 100px; + font-size: 2rem; + text-align: center; + vertical-align: middle; + line-height: 100px; + border: 1px solid #000; +} + +.status { + margin-top: 20px; + font-size: 1.2rem; +} diff --git a/TIAMSharedUI/Pages/TransferOrderDetails.razor b/TIAMSharedUI/Pages/TransferOrderDetails.razor index 08c63f1e..d407073e 100644 --- a/TIAMSharedUI/Pages/TransferOrderDetails.razor +++ b/TIAMSharedUI/Pages/TransferOrderDetails.razor @@ -1,4 +1,4 @@ -@page "/mytransfer" +@page "/mytransfers" Transferdetails diff --git a/TIAMSharedUI/Shared/AdminLayout.razor b/TIAMSharedUI/Shared/AdminLayout.razor index b9eabd01..cc5b8c87 100644 --- a/TIAMSharedUI/Shared/AdminLayout.razor +++ b/TIAMSharedUI/Shared/AdminLayout.razor @@ -1,5 +1,6 @@ @inherits LayoutComponentBase +@using Microsoft.AspNetCore.Authorization @using TIAMSharedUI.Shared.Users @using AyCode.Core.Extensions @using AyCode.Interfaces.StorageHandlers; @@ -23,6 +24,7 @@ @inject ISessionService sessionService @inject IEnumerable LogWriters @inject IUserDataService userDataService +@attribute [Authorize]
diff --git a/TIAMSharedUI/wwwroot/css/TourIAm.css b/TIAMSharedUI/wwwroot/css/TourIAm.css index f66f8436..3878a143 100644 --- a/TIAMSharedUI/wwwroot/css/TourIAm.css +++ b/TIAMSharedUI/wwwroot/css/TourIAm.css @@ -395,9 +395,9 @@ select:focus-visible { border: none; outline: none; background: none; - font-size: 1.2rem; + /*font-size: 1.2rem;*/ color: #666; - padding: 10px 15px 10px 10px; + /*padding: 10px 15px 10px 10px;*/ /* border: 1px solid red; */ } diff --git a/TIAMWebApp/Client/App.razor b/TIAMWebApp/Client/App.razor index 0309b495..c97a5c8b 100644 --- a/TIAMWebApp/Client/App.razor +++ b/TIAMWebApp/Client/App.razor @@ -1,5 +1,6 @@ -@using TIAMSharedUI.Shared - +@using Microsoft.AspNetCore.Components.Authorization +@using TIAMSharedUI.Shared +@* @@ -10,4 +11,22 @@

Sorry, there's nothing at this address.

-
+
*@ + + + + + +

Sorry dude, but you're not authorized!

+
+
+ +
+ + Not found + +

Sorry, there's nothing at this address.

+
+
+
+
diff --git a/TIAMWebApp/Client/Program.cs b/TIAMWebApp/Client/Program.cs index f8dee3a1..baff2339 100644 --- a/TIAMWebApp/Client/Program.cs +++ b/TIAMWebApp/Client/Program.cs @@ -4,7 +4,7 @@ using Blazored.LocalStorage; using DevExpress.Blazor; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; -using Microsoft.JSInterop; +using Microsoft.AspNetCore.Components.WebAssembly.Authentication; using System.Reflection; using System.Resources; using AyCode.Core.Loggers; @@ -15,6 +15,8 @@ using TIAMWebApp.Shared.Application.Services; using TIAMWebApp.Shared.Application.Utility; using AyCode.Services.Loggers; using System.Net; +using Microsoft.AspNetCore.Components.Authorization; + var builder = WebAssemblyHostBuilder.CreateDefault(args); @@ -43,7 +45,8 @@ builder.Services.AddSingleton() builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); - +builder.Services.AddScoped(); +builder.Services.AddAuthorizationCore(); //builder.Services.AddScoped(); //WebSpecific end diff --git a/TIAMWebApp/Client/TIAMWebApp.Client.csproj b/TIAMWebApp/Client/TIAMWebApp.Client.csproj index af06138e..cd9fc6a6 100644 --- a/TIAMWebApp/Client/TIAMWebApp.Client.csproj +++ b/TIAMWebApp/Client/TIAMWebApp.Client.csproj @@ -12,6 +12,7 @@ + diff --git a/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs b/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs index 946531ee..1595fef0 100644 --- a/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs +++ b/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs @@ -15,6 +15,7 @@ using TIAM.Services.Server; using TIAMWebApp.Shared.Application.Models; using TIAMWebApp.Shared.Application.Models.ClientSide.Messages; using TIAMWebApp.Shared.Application.Services; +using TIAMWebApp.Server.Services; namespace TIAMWebApp.Server.Controllers { @@ -39,14 +40,16 @@ namespace TIAMWebApp.Server.Controllers private readonly TIAM.Core.Loggers.ILogger _logger; private readonly TransferBackendService _transferBackendService; private readonly IMessageSenderService _messageSenderService; + private readonly AuthService _authService; - public TransferDataAPIController(AdminDal adminDal, TransferBackendService transferBackendService, IMessageSenderService messageSenderService, IEnumerable logWriters) + public TransferDataAPIController(AdminDal adminDal, TransferBackendService transferBackendService, IMessageSenderService messageSenderService, IEnumerable logWriters, AuthService authService) { _adminDal = adminDal; _transferBackendService = transferBackendService; _logger = new TIAM.Core.Loggers.Logger(logWriters.ToArray()); _messageSenderService = messageSenderService; + _authService = authService; } @@ -371,16 +374,30 @@ namespace TIAMWebApp.Server.Controllers } } - [AllowAnonymous] + [Authorize] [HttpGet] [Route(APIUrls.GetTransfersRouteName)] public async Task GetTransfers() { + var token = _authService.GetAuthTokenFromRequest(Request); + _logger.Detail(token); var result = await _adminDal.GetTransfersJsonAsync(); return result; } + [AllowAnonymous] + [HttpPost] + [Route(APIUrls.GetTransferByIdRouteName)] + public async Task GetTransferById([FromBody] Guid transferID) + { + _logger.Info(@"Get transfer by id called"); + _logger.Info($"transferId: {transferID.ToString()}"); + var result = _adminDal.GetTransferById(transferID); + + //TODO: Implementálni a Logout-ot kliens és szerver oldalon is! - J. + return Ok(result); + } [AllowAnonymous] [HttpPost] diff --git a/TIAMWebApp/Server/Program.cs b/TIAMWebApp/Server/Program.cs index 888355ac..099556ee 100644 --- a/TIAMWebApp/Server/Program.cs +++ b/TIAMWebApp/Server/Program.cs @@ -39,6 +39,7 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddSingleton(); builder.Services.AddSignalR(); @@ -174,6 +175,7 @@ app.MapControllers(); app.MapBlazorHub(); app.MapHub("/myhub"); app.MapHub("/adminhub"); +app.MapHub("/gamehub"); app.MapFallbackToFile("index.html"); app.Run(); diff --git a/TIAMWebApp/Server/Services/AuthService.cs b/TIAMWebApp/Server/Services/AuthService.cs new file mode 100644 index 00000000..7f3a1691 --- /dev/null +++ b/TIAMWebApp/Server/Services/AuthService.cs @@ -0,0 +1,26 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authorization; + +namespace TIAMWebApp.Server.Services +{ + public class AuthService + { + public string GetAuthTokenFromRequest(HttpRequest request) + { + // Check if the Authorization header is present + if (request.Headers.ContainsKey("Authorization")) + { + // Extract the token from the Authorization header + var authHeader = request.Headers["Authorization"].ToString(); + if (authHeader.StartsWith("Bearer ", System.StringComparison.OrdinalIgnoreCase)) + { + return authHeader.Substring("Bearer ".Length).Trim(); + } + } + + return null; + } + + } +} diff --git a/TIAMWebApp/Server/Services/GameHub.cs b/TIAMWebApp/Server/Services/GameHub.cs new file mode 100644 index 00000000..938c25fd --- /dev/null +++ b/TIAMWebApp/Server/Services/GameHub.cs @@ -0,0 +1,37 @@ +using AyCode.Core.Loggers; +using Microsoft.AspNetCore.SignalR; +using System.Net.Http; +using TIAM.Core.Loggers; + +namespace TIAMWebApp.Server.Services; +public class GameHub : Hub +{ + + private readonly TIAM.Core.Loggers.ILogger _logger; + public GameHub(IEnumerable logWriters) + { + + _logger = new TIAM.Core.Loggers.Logger(logWriters.ToArray()); + } + + public async Task MakeMove(string groupName, int row, int col, string player) + { + _logger.Detail($"{groupName}, {row}, {col}, {player}"); + await Clients.Group(groupName).SendAsync("ReceiveMove", row, col, player); + } + + public async Task JoinGame(string groupName) + { + _logger.Detail(groupName); + await Groups.AddToGroupAsync(Context.ConnectionId, groupName); + await Clients.Group(groupName).SendAsync("PlayerJoined", Context.ConnectionId); + } + + + public async Task LeaveGame(string groupName) + { + await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName); + await Clients.Group(groupName).SendAsync("PlayerLeft", Context.ConnectionId); + } +} + diff --git a/TIAMWebApp/Shared/Services/CustomAuthStateProvider.cs b/TIAMWebApp/Shared/Services/CustomAuthStateProvider.cs new file mode 100644 index 00000000..8fa8fb83 --- /dev/null +++ b/TIAMWebApp/Shared/Services/CustomAuthStateProvider.cs @@ -0,0 +1,78 @@ +using AyCode.Interfaces.StorageHandlers; +using Microsoft.AspNetCore.Components.Authorization; +using Newtonsoft.Json; +using System.IdentityModel.Tokens.Jwt; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text.Json; +using TIAMWebApp.Shared.Application.Models.ClientSide; + +namespace TIAMWebApp.Shared.Application.Services +{ + public class CustomAuthStateProvider : AuthenticationStateProvider + { + private readonly ISecureStorageHandler _localStorage; + private readonly HttpClient _http; + + + + public CustomAuthStateProvider(ISecureStorageHandler localStorage, HttpClient http) + { + _localStorage = localStorage; + _http = http; + } + + public override async Task GetAuthenticationStateAsync() + { + string userDetailsStr = await _localStorage.GetFromSecureStorageAsync(nameof(Setting.UserBasicDetails)); + AuthenticationState state = null; + if (!string.IsNullOrEmpty(userDetailsStr)) + { + + var userBasicDetail = JsonConvert.DeserializeObject(userDetailsStr); + + //var handler = new JwtSecurityTokenHandler(); + //var jsontoken = handler.ReadToken(userBasicDetail?.AccessToken) as JwtSecurityToken; + var token = userBasicDetail?.AccessToken; + var identity = new ClaimsIdentity(); + _http.DefaultRequestHeaders.Authorization = null; + + if (!string.IsNullOrEmpty(token)) + { + identity = new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt"); + _http.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", token.Replace("\"", "")); + } + + var user = new ClaimsPrincipal(identity); + state = new AuthenticationState(user); + + NotifyAuthenticationStateChanged(Task.FromResult(state)); + } + else + { + state = new AuthenticationState(new ClaimsPrincipal()); + } + + return state; + } + + public static IEnumerable ParseClaimsFromJwt(string jwt) + { + var payload = jwt.Split('.')[1]; + var jsonBytes = ParseBase64WithoutPadding(payload); + var keyValuePairs = System.Text.Json.JsonSerializer.Deserialize>(jsonBytes); + return keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString())); + } + + private static byte[] ParseBase64WithoutPadding(string base64) + { + switch (base64.Length % 4) + { + case 2: base64 += "=="; break; + case 3: base64 += "="; break; + } + return Convert.FromBase64String(base64); + } + } +} \ No newline at end of file diff --git a/TIAMWebApp/Shared/Services/TransferDataService.cs b/TIAMWebApp/Shared/Services/TransferDataService.cs index b035480c..da98b4d7 100644 --- a/TIAMWebApp/Shared/Services/TransferDataService.cs +++ b/TIAMWebApp/Shared/Services/TransferDataService.cs @@ -152,13 +152,18 @@ namespace TIAMWebApp.Shared.Application.Services public async Task GetTransferByIdAsync(Guid id) { + Transfer resultTransfer; var url = $"{Setting.ApiBaseUrl}/{APIUrls.GetTransferById}"; //var url = $"{APIUrls.GetTransferDestinations}"; _logger.Info(url); - Transfer? response = await _http.GetFromJsonAsync(url); + var response = await _http.PostAsJsonAsync(url, id); if (response == null) return new Transfer(); - return response; + else + { + resultTransfer = (Transfer)(await response.Content.ReadFromJsonAsync(typeof(Transfer))); + } + return resultTransfer; } public async Task> GetTransfersAsync() diff --git a/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj b/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj index 1dd158de..6daefebf 100644 --- a/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj +++ b/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj @@ -22,6 +22,7 @@ +