Updating auth

This commit is contained in:
max 2024-11-02 01:58:30 +01:00
parent 6e928ba4e3
commit 661fb2d1d3
9 changed files with 56 additions and 59 deletions

@ -1 +1 @@
Subproject commit d98634d8887e0bab7add7f2181c2cdd5db77e1d2
Subproject commit 8531079a16df9bd10c305d22075d7a135f8f8878

View File

@ -1,40 +0,0 @@
using Blazored.LocalStorage;
using DotBased;
using DotBased.ASP.Auth;
using DotBased.Extensions;
using DotBased.Logging;
using Serilog;
using ILogger = DotBased.Logging.ILogger;
namespace SharpRSS.Blazor.Auth;
public class LocalStorageSessionStateProvider : ISessionStateProvider
{
public LocalStorageSessionStateProvider(ILocalStorageService localStorage)
{
_localStorage = localStorage;
_logger = LogService.RegisterLogger(typeof(LocalStorageSessionStateProvider));
}
private readonly ILocalStorageService _localStorage;
private readonly ILogger _logger;
public async Task<Result<string>> GetSessionStateAsync()
{
var localStorageValue = await _localStorage.GetItemAsync<string>(ISessionStateProvider.SessionStateName);
if (localStorageValue != null && !localStorageValue.IsNullOrWhiteSpace())
return Result<string>.Ok(localStorageValue);
_logger.Warning("Failed to get session token from local storage!");
return Result<string>.Failed("Local storage returned null or empty on session token.");
}
public async Task<Result> SetSessionStateAsync(string state)
{
if (state.IsNullOrWhiteSpace())
{
Log.Warning("Tried to save empty or null session state to local storage!");
return Result.Failed("Could not set session state to local storage, value is empty or null!");
}
await _localStorage.SetItemAsync(ISessionStateProvider.SessionStateName, state);
return Result.Ok();
}
}

View File

@ -12,12 +12,12 @@
@*MudBlazor*@
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
<link href="_content/MudBlazor/MudBlazor.min.css" rel="stylesheet" />
<HeadOutlet/>
<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)"/>
</head>
<body>
@*Rendermode to 'InteractiveServer' or else MudBlazor will not work with interactivity*@
<Routes @rendermode="InteractiveServer"/>
<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)"/>
<script src="_framework/blazor.web.js"></script>
@*MudBlazor*@
<script src="_content/MudBlazor/MudBlazor.min.js"></script>

View File

@ -1,17 +1,56 @@
@page "/Auth/Login"
@using DotBased.ASP.Auth.Domains
@using DotBased.ASP.Auth.Services
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@using SharpRSS.Blazor.Extensions
@using SharpRSS.Data.Domains.Auth
@inject ProtectedLocalStorage LocalStorage
@inject NavigationManager NavigationManager
@inject SecurityService SecurityService
@inject ISnackbar Snackbar
<PageTitle>Login | SharpRSS</PageTitle>
<EditForm Model="@model" OnValidSubmit="ValidSubmit">
<DataAnnotationsValidator/>
<MudGrid>
<MudItem>
<MudCard>
<MudCardContent>
<MudTextField Label="UserName" @bind-Value="model.UserName" For="@(() => model.UserName)"/>
<MudTextField Label="Password" @bind-Value="model.Password" For="@(() => model.Password)" InputType="InputType.Password"/>
</MudCardContent>
<MudCardActions>
<MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary">Login</MudButton>
</MudCardActions>
</MudCard>
</MudItem>
</MudGrid>
</EditForm>
@code {
private string RedirectAfterLogin { get; set; } = string.Empty;
LoginModel model = new();
protected override Task OnInitializedAsync()
{
RedirectAfterLogin = NavigationManager.GetQueryParameters().TryGetValue("RedirectUrl", out var redirectUrl) ? redirectUrl.ToString() : string.Empty;
RedirectAfterLogin = NavigationManager.GetQueryParameters().TryGetValue("RedirectUrl", out var redirectUrl) ? redirectUrl.ToString() : "/";
//TODO: Checking based auth or external (OIDC, etc.)
return base.OnInitializedAsync();
}
private async void ValidSubmit(EditContext obj)
{
var loginResult = await SecurityService.LoginAsync(model);
if (loginResult.Success && loginResult.Value != null)
{
await LocalStorage.SetAsync("dotbased_session", loginResult.Value.Id);
NavigationManager.NavigateTo(RedirectAfterLogin);
}
Snackbar.Add(loginResult.Message, Severity.Error);
}
}

View File

@ -3,6 +3,11 @@
<PageTitle>Home</PageTitle>
<MudText Typo="Typo.h4">Mud text!</MudText>
<AuthorizeView>
<Authorized>
<span>Welcome: @context.User.Identity.Name</span>
</Authorized>
</AuthorizeView>
<AuthorizeView Roles="test">
<NotAuthorized>

View File

@ -1,10 +1,8 @@
using Blazored.LocalStorage;
using DotBased.ASP.Auth;
using DotBased.ASP.Auth.Domains.Auth;
using DotBased.ASP.Auth.Domains.Identity;
using Microsoft.EntityFrameworkCore;
using MudBlazor.Services;
using SharpRSS.Blazor.Auth;
using SharpRSS.Blazor.Components;
using SharpRSS.Business;
using SharpRSS.Data;
@ -13,23 +11,21 @@ using SharpRSS.Data.Domains.Configuration;
var builder = WebApplication.CreateBuilder(args);
builder.AddSRSS();
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddBasedServerAuth(options =>
{
options.AllowRegistration = false;
options.AuthenticationStateMaxAgeBeforeExpire = TimeSpan.FromDays(7);
options.LoginPath = "/auth/login";
options.LogoutPath = "/auth/logout";
options.LoggedOutPath = "/auth/loggedOut";
options.SeedData = service =>
{
service.CreateUserAsync(new UserModel() { UserName = "Admin", Email = "admin@example.com", Enabled = true, PasswordHash = "password", Roles =
[new RoleModel { Name = "Admin", Description = "Administration role." }]
service.CreateUserAsync(new UserModel() { UserName = "Admin", Name = "Administrator", FamilyName = "admin", Email = "admin@example.com", Enabled = true, PasswordHash = "password",
Roles = [new RoleModel { Name = "Admin", Description = "Administration role." }]
});
service.CreateUserAsync(new UserModel() { UserName = "User", Email = "user@example.com", Enabled = true, PasswordHash = "password"});
};
options.SetDataRepositoryType<MemoryAuthDataRepository>();
options.SetSessionStateProviderType<LocalStorageSessionStateProvider>();
});
// Add services to the container.

View File

@ -12,7 +12,6 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="4.5.0" />
<PackageReference Include="MudBlazor" Version="6.20.0" />
</ItemGroup>
@ -31,4 +30,8 @@
</Compile>
</ItemGroup>
<ItemGroup>
<Folder Include="Auth\" />
</ItemGroup>
</Project>

View File

@ -1,4 +1,5 @@
using DotBased;
using DotBased.ASP.Auth.Domains;
using DotBased.Logging;
using SharpRSS.Data.Domains.Auth;

View File

@ -1,7 +0,0 @@
namespace SharpRSS.Data.Domains.Auth;
public class LoginModel
{
public string UserName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}