Ajout models et page

j'en suis a CascadingAuthenticationState
pull/11/head
rahassou 2 years ago
parent 54a6d4f9c4
commit 7255cd2aed

@ -1,14 +1,15 @@
<CascadingBlazoredModal>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(CraftLayout)" />
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(CraftLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(CraftLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
<CascadingAuthenticationState>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</CascadingAuthenticationState>
</NotFound>
</Router>
</CascadingBlazoredModal>

@ -0,0 +1,9 @@
namespace CraftSharp.Models
{
public class AppUser
{
public string Password { get; set; }
public List<string> Roles { get; set; }
public string UserName { get; set; }
}
}

@ -5,11 +5,11 @@ namespace CraftSharp.Models
public class ConnexionModel
{
[Required(ErrorMessage = "Le pseudo est obligatoire.")]
[StringLength(50, ErrorMessage = "Le pseudo est trop long")]
public string? Name { get; set; }
[MinLength(4, ErrorMessage = "Le pseudo est trop court")]
public string? UserName { get; set; }
[Required(ErrorMessage = "Le mot de passe est obligatoire.")]
[StringLength(50, ErrorMessage = "Le mot de passe est trop long")]
[MinLength(6, ErrorMessage = "Le mot de passe est trop court")]
public string? Password { get; set; }
}
}

@ -0,0 +1,9 @@
namespace CraftSharp.Models
{
public class CurrentUser
{
public Dictionary<string, string> Claims { get; set; }
public bool IsAuthenticated { get; set; }
public string UserName { get; set; }
}
}

@ -6,11 +6,10 @@ namespace CraftSharp.Models
{
[Required(ErrorMessage = "Le pseudo est obligatoire.")]
[StringLength(50, ErrorMessage = "Le pseudo est trop long")]
public string? Pseudo { get; set; }
[MinLength(4, ErrorMessage = "Le pseudo est trop long")]
public string? UserName { get; set; }
[Required(ErrorMessage = "L'email est obligatoire.")]
[StringLength(50, ErrorMessage = "Le nom ne doit pas dépasser 50 caractères.")]
[RegularExpression(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$", ErrorMessage = "Le format de l'email n'est pas correcte.")]
public string? Email { get; set; }
@ -19,7 +18,7 @@ namespace CraftSharp.Models
public string? Password { get; set; }
[Required(ErrorMessage = "Vous devez confirmer votre mot de passe")]
[StringLength(50, ErrorMessage = "Le pseudo est trop long")]
public string? ConfirmPasswd { get; set; }
[Compare(nameof(Password), ErrorMessage = "Les mot de passe ne correspondent pas!")]
public string? PasswordConfirm { get; set; }
}
}

@ -5,27 +5,26 @@
<div class="option">
<h1>Connexion</h1>
<div>
<EditForm Model="@connexion" OnValidSubmit="@seConnecter">
<EditForm class="form-signin" OnValidSubmit="OnSubmit" Model="loginRequest">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="editForm">
<p>
<label for="display-name">
Pseudonyme:
<InputText id="name" @bind-Value="@connexion.Name" />
</label>
</p>
<p>
<label for="name">
Mot de passe:
<InputText id="password" type="password" @bind-Value="@connexion.Password" />
</label>
</p>
</div>
<div class="choix">
<button classtype="submit"> Se connecter </button>
</div>
<label for="inputUsername" class="sr-only">Pseudonyme</label>
<InputText id="inputUsername" class="form-control" @bind-Value="loginRequest.UserName" autofocus placeholder="Entrez votre pseudonyme" />
<ValidationMessage For="@(() => loginRequest.UserName)" />
<br />
<label for="inputPassword" class="sr-only">Mot de passe</label>
<InputText type="password" id="inputPassword" class="form-control" placeholder="Entrez votre mot de passe" @bind-Value="loginRequest.Password" />
<ValidationMessage For="@(() => loginRequest.Password)" />
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<br />
<label class="text-danger">@error</label>
<NavLink href="register">
<h6 class="font-weight-normal text-center">Creer un compte</h6>
</NavLink>
</EditForm>
</div>
</div>

@ -4,21 +4,32 @@ using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Components;
using CraftSharp.Models;
using CraftSharp.Services;
namespace CraftSharp.Pages
{
public partial class Connexion
{
private readonly ConnexionModel connexion = new();
[Inject]
public CustomStateProvider AuthStateProvider { get; set; }
private string _connexionId = "test";
private string _connexionPasswrd = "test";
[Inject]
public NavigationManager NavigationManager { get; set; }
private void seConnecter()
private string error { get; set; }
private ConnexionModel loginRequest { get; set; } = new ConnexionModel();
private async Task OnSubmit()
{
error = null;
try
{
if (connexion.Name == _connexionId && connexion.Password == _connexionPasswrd)
await AuthStateProvider.Login(loginRequest);
NavigationManager.NavigateTo("");
}
catch (Exception ex)
{
NavManager.NavigateTo("/counter");
error = ex.Message;
}
}
}

@ -5,39 +5,30 @@
<div class="option">
<h1>Inscription</h1>
<div>
<EditForm Model="@inscription" OnValidSubmit="@inscrire">
<EditForm class="form-signin" OnValidSubmit="OnSubmit" Model="registerRequest">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="editForm">
<p>
<label for="email">
Email:
<InputText id="email" @bind-Value="@inscription.Email" />
</label>
</p>
<p>
<label for="pseudo">
Pseudonyme:
<InputText id="pseudo" @bind-Value="@inscription.Pseudo" />
</label>
</p>
<p>
<label for="password">
Mot de passe:
<InputText id="password" type="password" @bind-Value="@inscription.Password" />
</label>
</p>
<p>
<label for="confimPasswd">
Mot de passe:
<InputText id="confimPasswd" type="password" @bind-Value="@inscription.ConfirmPasswd" />
</label>
</p>
</div>
<div class="choix">
<button classtype="submit"> Valider </button>
</div>
<label for="inputUsername" class="sr-only">Pseudonyme</label>
<InputText id="inputUsername" class="form-control" placeholder="Username" autofocus @bind-Value="@registerRequest.UserName" />
<ValidationMessage For="@(() => registerRequest.UserName)" />
<br />
<label for="inputPassword" class="sr-only">Mot de passe</label>
<InputText type="password" id="inputPassword" class="form-control" placeholder="Entrez votre mot de passe" @bind-Value="@registerRequest.Password" />
<ValidationMessage For="@(() => registerRequest.Password)" />
<br />
<label for="inputPasswordConfirm" class="sr-only">Confirmation</label>
<InputText type="password" id="inputPasswordConfirm" class="form-control" placeholder="Confirmez votre mot de passe" @bind-Value="@registerRequest.PasswordConfirm" />
<ValidationMessage For="@(() => registerRequest.PasswordConfirm)" />
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">S'inscrire'</button>
<label class="text-danger">@error</label>
<NavLink href="login">
<h6 class="font-weight-normal text-center">Vous avez un compte ? Connectez vous</h6>
</NavLink>
</EditForm>
</div>

@ -4,15 +4,33 @@ using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Components;
using CraftSharp.Models;
using CraftSharp.Services;
namespace CraftSharp.Pages
{
public partial class Inscription
{
private readonly InscriptionModel inscription = new();
[Inject]
public CustomStateProvider AuthStateProvider { get; set; }
private void inscrire()
[Inject]
public NavigationManager NavigationManager { get; set; }
private string error { get; set; }
private InscriptionModel registerRequest { get; set; } = new InscriptionModel();
private async Task OnSubmit()
{
error = null;
try
{
await AuthStateProvider.Register(registerRequest);
NavigationManager.NavigateTo("");
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
}

@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Options;
using System.Globalization;
using Microsoft.AspNetCore.Components.Authorization;
var builder = WebApplication.CreateBuilder(args);
@ -17,6 +18,11 @@ var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
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>();
// Add the controller of the app
builder.Services.AddControllers();

@ -0,0 +1,53 @@
using CraftSharp.Models;
using System.Security.Claims;
namespace CraftSharp.Services
{
public class AuthService : IAuthService
{
private static readonly List<AppUser> CurrentUser;
static AuthService()
{
CurrentUser = new List<AppUser>
{
new AppUser { UserName = "Admin", Password = "123456", Roles = new List<string> { "admin" } }
};
}
public CurrentUser GetUser(string userName)
{
var user = CurrentUser.FirstOrDefault(w => w.UserName == userName);
if (user == null)
{
throw new Exception("User name or password invalid !");
}
var claims = new List<Claim>();
claims.AddRange(user.Roles.Select(s => new Claim(ClaimTypes.Role, s)));
return new CurrentUser
{
IsAuthenticated = true,
UserName = user.UserName,
Claims = claims.ToDictionary(c => c.Type, c => c.Value)
};
}
public void Login(ConnexionModel loginRequest)
{
var user = CurrentUser.FirstOrDefault(w => w.UserName == loginRequest.UserName && w.Password == loginRequest.Password);
if (user == null)
{
throw new Exception("User name or password invalid !");
}
}
public void Register(InscriptionModel registerRequest)
{
CurrentUser.Add(new AppUser { UserName = registerRequest.UserName, Password = registerRequest.Password, Roles = new List<string> { "guest" } });
}
}
}

@ -0,0 +1,75 @@
using CraftSharp.Models;
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
namespace CraftSharp.Services
{
public class CustomStateProvider : AuthenticationStateProvider
{
private readonly IAuthService _authService;
private CurrentUser _currentUser;
public CustomStateProvider(IAuthService authService)
{
this._authService = authService;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity();
try
{
var userInfo = GetCurrentUser();
if (userInfo.IsAuthenticated)
{
var claims = new[] { new Claim(ClaimTypes.Name, _currentUser.UserName) }.Concat(_currentUser.Claims.Select(c => new Claim(c.Key, c.Value)));
identity = new ClaimsIdentity(claims, "Server authentication");
}
}
catch (HttpRequestException ex)
{
Console.WriteLine("Request failed:" + ex);
}
return new AuthenticationState(new ClaimsPrincipal(identity));
}
public async Task Login(ConnexionModel loginParameters)
{
_authService.Login(loginParameters);
// No error - Login the user
var user = _authService.GetUser(loginParameters.UserName);
_currentUser = user;
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public async Task Logout()
{
_currentUser = null;
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public async Task Register(InscriptionModel registerParameters)
{
_authService.Register(registerParameters);
// No error - Login the user
var user = _authService.GetUser(registerParameters.UserName);
_currentUser = user;
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
private CurrentUser GetCurrentUser()
{
if (_currentUser != null && _currentUser.IsAuthenticated)
{
return _currentUser;
}
return new CurrentUser();
}
}
}

@ -0,0 +1,13 @@
using CraftSharp.Models;
namespace CraftSharp.Services
{
public interface IAuthService
{
CurrentUser GetUser(string userName);
void Login(ConnexionModel loginRequest);
void Register(InscriptionModel registerRequest);
}
}
Loading…
Cancel
Save