Merge pull request 'arthur_usercookies' (#19) from arthur_usercookies into master

Reviewed-on: #19
arthur_logs
Arthur VALIN 2 years ago
commit 3ba2cba88f

@ -2,17 +2,16 @@
<CascadingBlazoredModal>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(CraftLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(CraftLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<CascadingAuthenticationState>
<CascadingAuthenticationState>
<LayoutView Layout="@typeof(CraftLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</CascadingAuthenticationState>
</CascadingAuthenticationState>
</NotFound>
</Router>
</CascadingBlazoredModal>

@ -22,7 +22,8 @@ namespace CraftSharp.Controllers
this.HttpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(
new RequestCulture(culture)));
new RequestCulture(culture))
);
}
return this.LocalRedirect(redirectUri);

@ -0,0 +1,47 @@
using CraftSharp.Models;
using CraftSharp.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Globalization;
using System.Net;
namespace CraftSharp.Controllers
{
[Microsoft.AspNetCore.Mvc.Route("[controller]/[action]")]
public class UserController : Controller
{
[HttpPost]
public IActionResult SetUser([FromBody] String user)
{
if (user != null)
{
HttpContext.Response.Cookies.Append(
"CurrentUser", user
);
}
return Ok(new { result = "userCookieSet" });
}
[HttpDelete]
public IActionResult DeleteUser()
{
this.HttpContext.Response.Cookies.Delete(
"CurrentUser"
);
return Ok(new { result = "userCookieDeleted" });
}
[HttpGet]
public IActionResult GetUser()
{
var jsonUser = HttpContext.Request.Cookies["CurrentUser"];
return Ok(jsonUser);
}
}
}

@ -7,6 +7,9 @@ using CraftSharp.Models;
using CraftSharp.Services;
using Blazorise;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.Text;
namespace CraftSharp.Pages
{
@ -18,17 +21,30 @@ namespace CraftSharp.Pages
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public HttpClient httpClient { get; set; }
private string error { get; set; }
private ConnexionModel loginRequest { get; set; } = new ConnexionModel();
protected override async Task OnInitializedAsync()
{
if (AuthStateProvider.GetCurrentUser() != null && AuthStateProvider.GetCurrentUser().IsAuthenticated)
{
NavigationManager.NavigateTo("index");
}
}
private async Task OnSubmit()
{
error = null;
try
{
await AuthStateProvider.Login(loginRequest);
var stringified = JsonConvert.SerializeObject(loginRequest);
var response = await httpClient.PostAsJsonAsync($"{NavigationManager.BaseUri}User/SetUser", stringified);
NavigationManager.NavigateTo("index");
}
catch (Exception ex)
{

@ -5,6 +5,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Components;
using CraftSharp.Models;
using CraftSharp.Services;
using Newtonsoft.Json;
using System.Net.Http;
namespace CraftSharp.Pages
{
@ -16,14 +18,30 @@ namespace CraftSharp.Pages
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public HttpClient httpClient { get; set; }
private string error { get; set; }
private InscriptionModel registerRequest { get; set; } = new InscriptionModel();
protected override async Task OnInitializedAsync()
{
if (AuthStateProvider.GetCurrentUser() != null && AuthStateProvider.GetCurrentUser().IsAuthenticated)
{
NavigationManager.NavigateTo("index");
}
}
private async Task OnSubmit()
{
await AuthStateProvider.Register(registerRequest);
NavigationManager.NavigateTo("index");
await AuthStateProvider.Register(registerRequest);
var stringified = JsonConvert.SerializeObject(new ConnexionModel() {
Password=registerRequest.Password,
UserName=registerRequest.UserName}
);
var response = await httpClient.PostAsJsonAsync($"{NavigationManager.BaseUri}User/SetUser", stringified);
NavigationManager.NavigateTo("index");
}
}

@ -1,52 +1,59 @@
@page "/list"
@using CraftSharp.Models
<h3>@Localizer["Title"]</h3>
@if (AuthStateProvider.GetCurrentUser().Roles.Contains(UserRoles.Admin))
{
<div>
<NavLink class="btn btn-primary" href="Add" Match="NavLinkMatch.All">
<i class="fa fa-plus"></i> @Localizer["Add"]
</NavLink>
</div>
<h3>@Localizer["Title"]</h3>
<DataGrid TItem="Item"
Data="@items"
ReadData="@OnReadData"
TotalItems="@totalItem"
PageSize="10"
ShowPager
Responsive>
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="#" />
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="@Localizer["Image"]">
<DisplayTemplate>
@if (!string.IsNullOrWhiteSpace(context.ImageBase64))
{
<img src="data:image/png;base64, @(context.ImageBase64)" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="min-width: 50px; max-width: 150px" />
}
else
{
<img src="images/default.png" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="max-width: 150px"/>
}
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.DisplayName)" Caption="@Localizer["Display"]" />
<DataGridColumn TItem="Item" Field="@nameof(Item.StackSize)" Caption="@Localizer["Stack"]" />
<DataGridColumn TItem="Item" Field="@nameof(Item.MaxDurability)" Caption="@Localizer["Maximum"]" />
<DataGridColumn TItem="Item" Field="@nameof(Item.EnchantCategories)" Caption="@Localizer["Enchant"]">
<DisplayTemplate>
@(string.Join(", ", ((Item)context).EnchantCategories))
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.RepairWith)" Caption="@Localizer["Repair"]">
<DisplayTemplate>
@(string.Join(", ", ((Item)context).RepairWith))
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.CreatedDate)" Caption="@Localizer["Created"]" DisplayFormat="{0:d}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" />
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="@Localizer["Action"]">
<DisplayTemplate>
<a href="Edit/@(context.Id)" class="btn btn-primary"><i class="fa fa-edit"></i> @Localizer["Edit"]</a>
<button type="button" class="btn btn-primary" @onclick="() => OnDelete(context.Id)"><i class="fa fa-trash"></i> @Localizer["Supp"]</button>
</DisplayTemplate>
</DataGridColumn>
</DataGrid>
<div>
<NavLink class="btn btn-primary" href="Add" Match="NavLinkMatch.All">
<i class="fa fa-plus"></i> @Localizer["Add"]
</NavLink>
</div>
<DataGrid TItem="Item"
Data="@items"
ReadData="@OnReadData"
TotalItems="@totalItem"
PageSize="10"
ShowPager
Responsive>
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="#" />
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="@Localizer["Image"]">
<DisplayTemplate>
@if (!string.IsNullOrWhiteSpace(context.ImageBase64))
{
<img src="data:image/png;base64, @(context.ImageBase64)" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="min-width: 50px; max-width: 150px" />
}
else
{
<img src="images/default.png" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="max-width: 150px"/>
}
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.DisplayName)" Caption="@Localizer["Display"]" />
<DataGridColumn TItem="Item" Field="@nameof(Item.StackSize)" Caption="@Localizer["Stack"]" />
<DataGridColumn TItem="Item" Field="@nameof(Item.MaxDurability)" Caption="@Localizer["Maximum"]" />
<DataGridColumn TItem="Item" Field="@nameof(Item.EnchantCategories)" Caption="@Localizer["Enchant"]">
<DisplayTemplate>
@(string.Join(", ", ((Item)context).EnchantCategories))
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.RepairWith)" Caption="@Localizer["Repair"]">
<DisplayTemplate>
@(string.Join(", ", ((Item)context).RepairWith))
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.CreatedDate)" Caption="@Localizer["Created"]" DisplayFormat="{0:d}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" />
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="@Localizer["Action"]">
<DisplayTemplate>
<a href="Edit/@(context.Id)" class="btn btn-primary"><i class="fa fa-edit"></i> @Localizer["Edit"]</a>
<button type="button" class="btn btn-primary" @onclick="() => OnDelete(context.Id)"><i class="fa fa-trash"></i> @Localizer["Supp"]</button>
</DisplayTemplate>
</DataGridColumn>
</DataGrid>
}else{
<p>FORBIDDEN !!</p>
}

@ -16,6 +16,9 @@ namespace CraftSharp.Pages
private int totalItem;
[Inject]
public CustomStateProvider AuthStateProvider { get; set; }
[Inject]
public IStringLocalizer<List> Localizer { get; set; }

@ -6,12 +6,11 @@
<Authorized>
<div class="numberOfKeys">
<ValueIndicator IconPath="/Images/opening_icon.png"
Value="@NumberOfKeys">
Value="@AuthStateProvider.GetCurrentUser().NumberOfKeys">
</ValueIndicator>
</div>
</Authorized>
</AuthorizeView>
<div class="openingPanel">
<img src="/Images/chestBottom.png" class="chest chestOpenBottom @openAnim" />
<img src="/Images/chest.png" class="chest chestOpen @openAnim" />

@ -23,13 +23,7 @@ namespace CraftSharp.Pages
[Inject]
public IDataService DataService { get; set; }
[Inject]
public CustomStateProvider AuthService { get; set; }
[Inject]
public CustomStateProvider AuthStateProvider { get; set; }
[CascadingParameter]
public Task<AuthenticationState> Context { get; set; }
int NumberOfKeys { get; set; } = 0;
int CostInKeys { get; set; } = 1;
[Inject]
@ -43,13 +37,11 @@ namespace CraftSharp.Pages
totalItem = await DataService.Count();
items = await DataService.List(0, totalItem);
NumberOfKeys = AuthService.GetCurrentUser().NumberOfKeys;
}
bool canOpen()
{
return isChestClosed && NumberOfKeys >= CostInKeys;
return isChestClosed && AuthStateProvider.GetCurrentUser().NumberOfKeys >= CostInKeys;
}
async void selectRandom()
@ -57,7 +49,7 @@ namespace CraftSharp.Pages
if (canOpen())
{
NumberOfKeys=NumberOfKeys-CostInKeys;
AuthStateProvider.GetCurrentUser().NumberOfKeys -= CostInKeys;
randomItem = ItemFactory.GetRandomItem(items);
if (AuthStateProvider.GetCurrentUser().getSizeInventory() <= 64)
{

@ -6,7 +6,7 @@
<Authorized>
<div class="NumberOfEmeralds">
<ValueIndicator IconPath="/Images/shop_icon.png"
Value="@NumberOfEmeralds">
Value="@AuthService.GetCurrentUser().numberOfEmeralds">
</ValueIndicator>
</div>
</Authorized>

@ -15,10 +15,6 @@ namespace CraftSharp.Pages
[Inject]
public IStringLocalizer<Shop> Localizer { get; set; }
[Inject]
public IJSRuntime JsRuntime { get; set; }
int NumberOfEmeralds { get; set; } = 0;
List<ShopOfferModel> offers = new List<ShopOfferModel>()
{
new ShopOfferModel()
@ -48,7 +44,6 @@ namespace CraftSharp.Pages
protected override async Task OnInitializedAsync()
{
NumberOfEmeralds = AuthService.GetCurrentUser().numberOfEmeralds;
foreach(ShopOfferModel offer in offers)
{
animation[offer] = "";
@ -57,9 +52,9 @@ namespace CraftSharp.Pages
private async void buyKeys(ShopOfferModel offer)
{
if (offer.InputAmount <= NumberOfEmeralds)
if (offer.InputAmount <= AuthService.GetCurrentUser().numberOfEmeralds)
{
NumberOfEmeralds -= offer.InputAmount;
AuthService.GetCurrentUser().numberOfEmeralds -= offer.InputAmount;
AuthService.GetCurrentUser().NumberOfKeys += offer.OutputAmount;
}
else

@ -1,8 +1,24 @@
@page "/"
@namespace CraftSharp.Pages
@using CraftSharp.Models;
@using CraftSharp.Services;
@using Microsoft.AspNetCore.Components;
@using Newtonsoft.Json;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject CustomStateProvider authService;
@inject HttpClient httpClient;
@{
Layout = "_Layout";
Console.WriteLine("==============START==============");
var response = await httpClient.GetAsync($"https://localhost:7139/User/GetUser");
string jsonUser = await response.Content.ReadAsStringAsync();
var user = new ConnexionModel();
if (jsonUser != null && jsonUser.Length != 0)
{
user = JsonConvert.DeserializeObject<ConnexionModel>(jsonUser);
await authService.Login(user);
}
}
<component type="typeof(App)" render-mode="ServerPrerendered"/>

@ -18,6 +18,7 @@ using CraftSharp;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using System;
using Microsoft.JSInterop;
using CraftSharp.Controllers;
var builder = WebApplication.CreateBuilder(args);
@ -27,16 +28,16 @@ builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddOptions();
builder.Services.AddAuthorizationCore();
builder.Services.AddScoped<CustomStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(s => s.GetRequiredService<CustomStateProvider>());
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddSingleton<CustomStateProvider>();
builder.Services.AddSingleton<AuthenticationStateProvider>(s => s.GetRequiredService<CustomStateProvider>());
builder.Services.AddSingleton<IAuthService, AuthService>();
// Add the controller of the app
builder.Services.AddControllers();
// Add the localization to the app and specify the resources path
builder.Services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
builder.Services.AddScoped<UserController>();
builder.Services.AddHttpClient();
builder.Services.AddBlazoredModal();

@ -41,10 +41,13 @@ namespace CraftSharp.Services
public void Login(ConnexionModel loginRequest)
{
Console.WriteLine("LOGIN : " + loginRequest.UserName);
var user = CurrentUser.FirstOrDefault(w => w.UserName == loginRequest.UserName && w.Password == loginRequest.Password);
if (user == null)
{
Console.WriteLine("LOGINFAILED");
throw new Exception("User name or password invalid !");
}
}

@ -70,12 +70,14 @@ namespace CraftSharp.Services
public CurrentUser GetCurrentUser()
{
CurrentUser cacheUser;
if (_currentUser != null && _currentUser.IsAuthenticated)
{
Console.WriteLine("GETUSER: " + _currentUser.UserName);
return _currentUser;
}
Console.WriteLine("GETUSER: FAIL");
return new CurrentUser();
}
}

@ -3,6 +3,7 @@ using CraftSharp.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Localization;
using System.Net.Http;
namespace CraftSharp.Shared
@ -18,6 +19,9 @@ namespace CraftSharp.Shared
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public HttpClient httpClient { get; set; }
[CascadingParameter]
private Task<AuthenticationState> AuthenticationState { get; set; }
@ -25,6 +29,10 @@ namespace CraftSharp.Shared
protected override async Task OnInitializedAsync()
{
if (AuthStateProvider.GetCurrentUser() == null || !AuthStateProvider.GetCurrentUser().IsAuthenticated)
{
NavigationManager.NavigateTo("/");
}
isAdmin();
}
@ -46,6 +54,8 @@ namespace CraftSharp.Shared
private async Task LogoutClick()
{
await AuthStateProvider.Logout();
await httpClient.DeleteAsync($"{NavigationManager.BaseUri}User/DeleteUser");
NavigationManager.NavigateTo("/inscription");
}
}

Loading…
Cancel
Save