arthur_usercookies #19

Merged
arthur.valin merged 6 commits from arthur_usercookies into master 2 years ago

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

@ -22,7 +22,8 @@ namespace CraftSharp.Controllers
this.HttpContext.Response.Cookies.Append( this.HttpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue( CookieRequestCultureProvider.MakeCookieValue(
new RequestCulture(culture))); new RequestCulture(culture))
);
} }
return this.LocalRedirect(redirectUri); 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 CraftSharp.Services;
using Blazorise; using Blazorise;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.Text;
namespace CraftSharp.Pages namespace CraftSharp.Pages
{ {
@ -18,17 +21,30 @@ namespace CraftSharp.Pages
[Inject] [Inject]
public NavigationManager NavigationManager { get; set; } public NavigationManager NavigationManager { get; set; }
[Inject]
public HttpClient httpClient { get; set; }
private string error { get; set; } private string error { get; set; }
private ConnexionModel loginRequest { get; set; } = new ConnexionModel(); 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() private async Task OnSubmit()
{ {
error = null; error = null;
try try
{ {
await AuthStateProvider.Login(loginRequest); await AuthStateProvider.Login(loginRequest);
var stringified = JsonConvert.SerializeObject(loginRequest);
var response = await httpClient.PostAsJsonAsync($"{NavigationManager.BaseUri}User/SetUser", stringified);
NavigationManager.NavigateTo("index"); NavigationManager.NavigateTo("index");
} }
catch (Exception ex) catch (Exception ex)
{ {

@ -5,6 +5,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using CraftSharp.Models; using CraftSharp.Models;
using CraftSharp.Services; using CraftSharp.Services;
using Newtonsoft.Json;
using System.Net.Http;
namespace CraftSharp.Pages namespace CraftSharp.Pages
{ {
@ -16,14 +18,30 @@ namespace CraftSharp.Pages
[Inject] [Inject]
public NavigationManager NavigationManager { get; set; } public NavigationManager NavigationManager { get; set; }
[Inject]
public HttpClient httpClient { get; set; }
private string error { get; set; } private string error { get; set; }
private InscriptionModel registerRequest { get; set; } = new InscriptionModel(); 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() private async Task OnSubmit()
{ {
await AuthStateProvider.Register(registerRequest); await AuthStateProvider.Register(registerRequest);
NavigationManager.NavigateTo("index"); 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" @page "/list"
@using CraftSharp.Models @using CraftSharp.Models
<h3>@Localizer["Title"]</h3> @if (AuthStateProvider.GetCurrentUser().Roles.Contains(UserRoles.Admin))
{
<div> <h3>@Localizer["Title"]</h3>
<NavLink class="btn btn-primary" href="Add" Match="NavLinkMatch.All">
<i class="fa fa-plus"></i> @Localizer["Add"]
</NavLink>
</div>
<DataGrid TItem="Item" <div>
Data="@items" <NavLink class="btn btn-primary" href="Add" Match="NavLinkMatch.All">
ReadData="@OnReadData" <i class="fa fa-plus"></i> @Localizer["Add"]
TotalItems="@totalItem" </NavLink>
PageSize="10" </div>
ShowPager
Responsive> <DataGrid TItem="Item"
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="#" /> Data="@items"
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="@Localizer["Image"]"> ReadData="@OnReadData"
<DisplayTemplate> TotalItems="@totalItem"
@if (!string.IsNullOrWhiteSpace(context.ImageBase64)) PageSize="10"
{ ShowPager
<img src="data:image/png;base64, @(context.ImageBase64)" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="min-width: 50px; max-width: 150px" /> Responsive>
} <DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="#" />
else <DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="@Localizer["Image"]">
{ <DisplayTemplate>
<img src="images/default.png" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="max-width: 150px"/> @if (!string.IsNullOrWhiteSpace(context.ImageBase64))
} {
</DisplayTemplate> <img src="data:image/png;base64, @(context.ImageBase64)" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="min-width: 50px; max-width: 150px" />
</DataGridColumn> }
<DataGridColumn TItem="Item" Field="@nameof(Item.DisplayName)" Caption="@Localizer["Display"]" /> else
<DataGridColumn TItem="Item" Field="@nameof(Item.StackSize)" Caption="@Localizer["Stack"]" /> {
<DataGridColumn TItem="Item" Field="@nameof(Item.MaxDurability)" Caption="@Localizer["Maximum"]" /> <img src="images/default.png" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="max-width: 150px"/>
<DataGridColumn TItem="Item" Field="@nameof(Item.EnchantCategories)" Caption="@Localizer["Enchant"]"> }
<DisplayTemplate> </DisplayTemplate>
@(string.Join(", ", ((Item)context).EnchantCategories)) </DataGridColumn>
</DisplayTemplate> <DataGridColumn TItem="Item" Field="@nameof(Item.DisplayName)" Caption="@Localizer["Display"]" />
</DataGridColumn> <DataGridColumn TItem="Item" Field="@nameof(Item.StackSize)" Caption="@Localizer["Stack"]" />
<DataGridColumn TItem="Item" Field="@nameof(Item.RepairWith)" Caption="@Localizer["Repair"]"> <DataGridColumn TItem="Item" Field="@nameof(Item.MaxDurability)" Caption="@Localizer["Maximum"]" />
<DisplayTemplate> <DataGridColumn TItem="Item" Field="@nameof(Item.EnchantCategories)" Caption="@Localizer["Enchant"]">
@(string.Join(", ", ((Item)context).RepairWith)) <DisplayTemplate>
</DisplayTemplate> @(string.Join(", ", ((Item)context).EnchantCategories))
</DataGridColumn> </DisplayTemplate>
<DataGridColumn TItem="Item" Field="@nameof(Item.CreatedDate)" Caption="@Localizer["Created"]" DisplayFormat="{0:d}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" /> </DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="@Localizer["Action"]"> <DataGridColumn TItem="Item" Field="@nameof(Item.RepairWith)" Caption="@Localizer["Repair"]">
<DisplayTemplate> <DisplayTemplate>
<a href="Edit/@(context.Id)" class="btn btn-primary"><i class="fa fa-edit"></i> @Localizer["Edit"]</a> @(string.Join(", ", ((Item)context).RepairWith))
<button type="button" class="btn btn-primary" @onclick="() => OnDelete(context.Id)"><i class="fa fa-trash"></i> @Localizer["Supp"]</button> </DisplayTemplate>
</DisplayTemplate> </DataGridColumn>
</DataGridColumn> <DataGridColumn TItem="Item" Field="@nameof(Item.CreatedDate)" Caption="@Localizer["Created"]" DisplayFormat="{0:d}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" />
</DataGrid> <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; private int totalItem;
[Inject]
public CustomStateProvider AuthStateProvider { get; set; }
[Inject] [Inject]
public IStringLocalizer<List> Localizer { get; set; } public IStringLocalizer<List> Localizer { get; set; }

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

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

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

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

@ -1,8 +1,24 @@
@page "/" @page "/"
@namespace CraftSharp.Pages @namespace CraftSharp.Pages
@using CraftSharp.Models;
@using CraftSharp.Services;
@using Microsoft.AspNetCore.Components;
@using Newtonsoft.Json;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject CustomStateProvider authService;
@inject HttpClient httpClient;
@{ @{
Layout = "_Layout"; 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"/> <component type="typeof(App)" render-mode="ServerPrerendered"/>

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

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

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

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

Loading…
Cancel
Save