Skip to content

Commit bfe6c13

Browse files
committed
More Code Refactoring
1 parent 60a1789 commit bfe6c13

File tree

17 files changed

+120
-81
lines changed

17 files changed

+120
-81
lines changed

samples/UAuthHub/CodeBeam.UltimateAuth.Sample.UAuthHub/Components/App.razor

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,9 @@
66
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
77
<base href="/" />
88
<ResourcePreloader />
9-
@* <link rel="stylesheet" href="@Assets["lib/bootstrap/dist/css/bootstrap.min.css"]" /> *@
109
<link rel="stylesheet" href="@Assets["app.css"]" />
11-
<link rel="stylesheet" href="@Assets["UltimateAuth.Sample.UAuthHub.styles.css"]" />
1210
<ImportMap />
13-
<link rel="icon" type="image/png" href="~/UltimateAuth-Logo.png" />
11+
<link rel="icon" type="image/png" href="UltimateAuth-Logo.png" />
1412

1513
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
1614
<link href="_content/MudBlazor/MudBlazor.min.css" rel="stylesheet" />

samples/UAuthHub/CodeBeam.UltimateAuth.Sample.UAuthHub/Components/Pages/Home.razor

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
@page "/"
22
@page "/login"
33
@attribute [UAuthLoginPage]
4-
@inherits UAuthFlowPageBase
4+
@inherits UAuthHubPageBase
55

66
@implements IDisposable
77
@using CodeBeam.UltimateAuth.Client.Infrastructure
@@ -16,7 +16,6 @@
1616
@inject IAuthStore AuthStore
1717
@inject IHubFlowService HubFlowService
1818
@inject IPkceService PkceService
19-
@inject IHubFlowReader HubFlowReader
2019
@inject IHubCredentialResolver HubCredentialResolver
2120
@inject IClientStorage BrowserStorage
2221
@inject ISnackbar Snackbar
@@ -25,7 +24,7 @@
2524
@inject IDialogService DialogService
2625
@inject IOptions<UAuthClientOptions> Options
2726

28-
@if (_state == null || !_state.IsActive)
27+
@if (!IsHubAuthorized)
2928
{
3029
<MudPage Class="d-flex align-center justify-center" FullScreen="FullScreen.FullWithoutAppbar" Column="1" Row="1">
3130
<MudPaper Class="pa-8" Elevation="4" Style="max-width: 520px; width: 100%;">
@@ -115,11 +114,12 @@
115114
<MudText Style="color: var(--mud-palette-text-secondary)" Typo="Typo.subtitle2" Align="Align.Center">Login programmatically as admin/admin.</MudText>
116115
</MudStack>
117116

118-
<MudDivider Class="my-2" />
117+
@* <MudDivider Class="my-2" /> *@
119118

120119
<MudStack>
120+
@* TODO: Enhance sample *@
121121
@* <MudText Align="Align.Center" Typo="Typo.subtitle2"><MudLink Class="cursor-pointer" OnClick="OpenResetDialog">Forgot Password</MudLink></MudText> *@
122-
<MudText Align="Align.Center" Typo="Typo.subtitle2">Don't have an account? <MudLink Class="cursor-pointer" Href="/register">SignUp</MudLink></MudText>
122+
@* <MudText Align="Align.Center" Typo="Typo.subtitle2">Don't have an account? <MudLink Class="cursor-pointer" Href="/register">SignUp</MudLink></MudText> *@
123123
</MudStack>
124124
</MudPaper>
125125
</MudItem>

samples/UAuthHub/CodeBeam.UltimateAuth.Sample.UAuthHub/Components/Pages/Home.razor.cs

Lines changed: 13 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,15 @@
44
using CodeBeam.UltimateAuth.Core.Contracts;
55
using CodeBeam.UltimateAuth.Core.Domain;
66
using CodeBeam.UltimateAuth.Server.Stores;
7-
using Microsoft.AspNetCore.Components;
87
using MudBlazor;
98

109
namespace CodeBeam.UltimateAuth.Sample.UAuthHub.Components.Pages;
1110

1211
public partial class Home
1312
{
14-
[SupplyParameterFromQuery(Name = "hub")]
15-
public string? HubKey { get; set; }
16-
1713
private string? _username;
1814
private string? _password;
1915

20-
private HubFlowState? _state;
21-
2216
private UAuthClientProductInfo? _productInfo;
2317
private UAuthLoginForm _loginForm = null!;
2418

@@ -38,51 +32,35 @@ protected override async Task OnInitializedAsync()
3832
_productInfo = ClientProductInfoProvider.Get();
3933
}
4034

41-
protected override async Task OnParametersSetAsync()
42-
{
43-
if (string.IsNullOrWhiteSpace(HubKey))
44-
{
45-
_state = null;
46-
return;
47-
}
48-
49-
if (HubSessionId.TryParse(HubKey, out var hubSessionId))
50-
_state = await HubFlowReader.GetStateAsync(hubSessionId);
51-
}
52-
5335
protected override async Task OnAfterRenderAsync(bool firstRender)
5436
{
5537
if (string.IsNullOrWhiteSpace(HubKey))
5638
return;
5739

58-
if (_state is null || !_state.Exists)
40+
if (HubState is null || !HubState.Exists)
5941
{
6042
await StartNewPkceAsync();
6143
return;
6244
}
6345

64-
if (_state.IsExpired)
46+
if (HubState.IsExpired)
6547
{
6648
await StartNewPkceAsync();
6749
return;
6850
}
6951

70-
if (_state.Error != null && !_errorHandled)
52+
if (HubState.Error != null && !_errorHandled)
7153
{
7254
_errorHandled = true;
73-
74-
Snackbar.Add(ResolveErrorMessage(_state.Error), Severity.Error);
75-
//_state = _state.ClearError();
76-
77-
//await Task.Delay(200);
55+
Snackbar.Add(ResolveErrorMessage(HubState.Error), Severity.Error);
7856
await ContinuePkceAsync();
7957

8058
if (HubSessionId.TryParse(HubKey, out var hubSessionId))
8159
{
82-
_state = await HubFlowReader.GetStateAsync(hubSessionId);
60+
await ReloadState();
8361
}
8462

85-
await _loginForm.RefreshAsync();
63+
await _loginForm.ReloadAsync();
8664

8765
StateHasChanged();
8866
}
@@ -91,7 +69,7 @@ protected override async Task OnAfterRenderAsync(bool firstRender)
9169
// For testing & debugging
9270
private async Task ProgrammaticPkceLogin()
9371
{
94-
var hub = _state;
72+
var hub = HubState;
9573

9674
if (hub is null)
9775
return;
@@ -107,8 +85,8 @@ private async Task ProgrammaticPkceLogin()
10785
Secret = "admin",
10886
AuthorizationCode = credentials?.AuthorizationCode ?? string.Empty,
10987
CodeVerifier = credentials?.CodeVerifier ?? string.Empty,
110-
ReturnUrl = _state?.ReturnUrl ?? string.Empty,
111-
HubSessionId = _state?.HubSessionId.Value ?? hubSessionId.Value,
88+
ReturnUrl = HubState?.ReturnUrl ?? string.Empty,
89+
HubSessionId = HubState?.HubSessionId.Value ?? hubSessionId.Value,
11290
};
11391

11492
await UAuthClient.Flows.TryCompletePkceLoginAsync(request, UAuthSubmitMode.TryAndCommit);
@@ -159,7 +137,7 @@ private async Task StartNewPkceAsync()
159137

160138
private async Task<string> ResolveReturnUrlAsync()
161139
{
162-
var fromContext = _state?.ReturnUrl;
140+
var fromContext = HubState?.ReturnUrl;
163141
if (!string.IsNullOrWhiteSpace(fromContext))
164142
return fromContext;
165143

@@ -275,11 +253,11 @@ AuthFailureReason.InvalidCredentials when remainingAttempts is > 0
275253
Snackbar.Add(message, Severity.Error);
276254
}
277255

278-
private string ResolveErrorMessage(string? errorKey)
256+
private string ResolveErrorMessage(HubErrorCode? errorCode)
279257
{
280-
if (errorKey == "invalid")
258+
if (errorCode == HubErrorCode.InvalidCredentials)
281259
{
282-
return "Login failed.";
260+
return "Invalid credentials.";
283261
}
284262

285263
return "Failed attempt.";

samples/UAuthHub/CodeBeam.UltimateAuth.Sample.UAuthHub/Program.cs

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212

1313
var builder = WebApplication.CreateBuilder(args);
1414

15-
// Add services to the container.
1615
builder.Services.AddRazorComponents()
1716
.AddInteractiveServerComponents()
1817
.AddCircuitOptions(options =>
@@ -27,7 +26,6 @@
2726

2827
builder.Services.AddScoped<DarkModeManager>();
2928

30-
3129
builder.Services.AddUltimateAuthServer(o => {
3230
o.Diagnostics.EnableRefreshDetails = true;
3331
//o.Session.MaxLifetime = TimeSpan.FromSeconds(32);
@@ -41,33 +39,19 @@
4139
o.Identifiers.AllowMultipleUsernames = true;
4240
})
4341
.AddUltimateAuthInMemory()
44-
.AddUAuthHub(o => o.AllowedClientOrigins.Add("https://localhost:6130"));
42+
.AddUAuthHub(o => o.AllowedClientOrigins.Add("https://localhost:6130")); // Client sample's URL
4543

4644
builder.Services.AddUltimateAuthClientBlazor(o =>
4745
{
4846
//o.Refresh.Interval = TimeSpan.FromSeconds(5);
4947
o.Reauth.Behavior = ReauthBehavior.RaiseEvent;
5048
});
5149

52-
//builder.Services.AddCors(options =>
53-
//{
54-
// options.AddPolicy("UAuthHub", policy =>
55-
// {
56-
// policy
57-
// .WithOrigins("https://localhost:6130")
58-
// .AllowAnyHeader()
59-
// .AllowAnyMethod()
60-
// .AllowCredentials()
61-
// .WithExposedHeaders("X-UAuth-Refresh"); // TODO: Add exposed headers globally
62-
// });
63-
//});
64-
6550
var app = builder.Build();
6651

6752
if (!app.Environment.IsDevelopment())
6853
{
6954
app.UseExceptionHandler("/Error", createScopeForErrors: true);
70-
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
7155
app.UseHsts();
7256
}
7357
else
@@ -81,7 +65,6 @@
8165
}
8266

8367
app.UseHttpsRedirection();
84-
app.UseCors("UAuthHub");
8568

8669
app.UseUltimateAuthWithAspNetCore();
8770
app.UseAntiforgery();
@@ -94,13 +77,4 @@
9477
.AddInteractiveServerRenderMode()
9578
.AddUltimateAuthRoutes(UAuthAssemblies.BlazorClient());
9679

97-
app.MapGet("/health", () =>
98-
{
99-
return Results.Ok(new
100-
{
101-
service = "UAuthHub",
102-
status = "ok"
103-
});
104-
});
105-
10680
app.Run();

samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Components/Pages/Login.razor

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373

7474
<MudItem Class="order-0 order-sm-1" xs="12" sm="6">
7575
<MudPaper Class="uauth-login-paper pa-8" Elevation="3">
76-
<UAuthLoginForm Identifier="@_username" Secret="@_password" SubmitMode="UAuthSubmitMode.TryAndCommit" OnTryResult="@HandleTry" ReturnUrl="@(ReturnUrl ?? "/home")">
76+
<UAuthLoginForm Identifier="@_username" Secret="@_password" OnTryResult="@HandleTry" ReturnUrl="@(ReturnUrl ?? "/home")">
7777
<MudStack Class="mud-width-full">
7878
<MudStack Row="true" AlignItems="AlignItems.Center">
7979
<UAuthLogo Size="48" ShieldColor="var(--mud-palette-primary)" KeyColor="white" />

samples/blazor-standalone-wasm/CodeBeam.UltimateAuth.Sample.BlazorStandaloneWasm/Pages/Login.razor

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@
8686
Instead of use PKCE flow.
8787
This section only demonstrates that direct login flow is working, but not suggested.
8888
</MudAlert>
89-
<UAuthLoginForm Identifier="@_username" Secret="@_password" ReturnUrl="@(ReturnUrl ?? "/home")">
89+
<UAuthLoginForm Identifier="@_username" Secret="@_password" ReturnUrl="@(ReturnUrl ?? "/home")" OnTryResult="HandleLoginResult">
9090
<MudStack Class="mud-width-full">
9191
<MudTextField @ref="@_usernameField" @bind-Value="@_username" Variant="Variant.Outlined" Label="Username" Required="true" Immediate="true" HelperText="@(_remainingAttempts != null ? $"Remaining Attempts: {_remainingAttempts}" : null)" />
9292
<MudPasswordField @bind-Value="@_password" Variant="Variant.Outlined" Label="Password" Required="true" Immediate="true" />

samples/blazor-standalone-wasm/CodeBeam.UltimateAuth.Sample.BlazorStandaloneWasm/Pages/Login.razor.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,21 @@ private async Task ProgrammaticLogin()
9999
await UAuthClient.Flows.LoginAsync(request, ReturnUrl ?? "/home");
100100
}
101101

102+
private async Task HandleLoginResult(IUAuthTryResult result)
103+
{
104+
if (!result.Success)
105+
{
106+
if (result.Reason == AuthFailureReason.LockedOut && result.LockoutUntilUtc is { } until)
107+
{
108+
_lockoutUntil = until;
109+
StartCountdown();
110+
}
111+
112+
_remainingAttempts = result.RemainingAttempts;
113+
ShowLoginError(result.Reason, result.RemainingAttempts);
114+
}
115+
}
116+
102117
private async void StartCountdown()
103118
{
104119
if (_lockoutUntil is null)
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace CodeBeam.UltimateAuth.Core.Domain;
2+
3+
public enum HubErrorCode
4+
{
5+
None = 0,
6+
InvalidCredentials,
7+
LockedOut,
8+
RequiresMfa,
9+
Unknown
10+
}

src/CodeBeam.UltimateAuth.Core/Domain/Hub/HubFlowArtifact.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public sealed class HubFlowArtifact : AuthArtifact
1414

1515
public HubFlowPayload Payload { get; }
1616

17-
public string? Error { get; private set; }
17+
public HubErrorCode? Error { get; private set; }
1818

1919
public HubFlowArtifact(
2020
HubSessionId hubSessionId,
@@ -34,7 +34,7 @@ public HubFlowArtifact(
3434
Payload = payload;
3535
}
3636

37-
public void SetError(string error)
37+
public void SetError(HubErrorCode error)
3838
{
3939
Error = error;
4040
RegisterAttempt();

src/CodeBeam.UltimateAuth.Core/Domain/Hub/HubFlowState.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public sealed class HubFlowState
88
public HubFlowType FlowType { get; init; }
99
public UAuthClientProfile ClientProfile { get; init; }
1010
public string? ReturnUrl { get; init; }
11-
public string? Error { get; init; }
11+
public HubErrorCode? Error { get; init; }
1212
public int AttemptCount { get; init; }
1313

1414
public bool IsActive { get; init; }

0 commit comments

Comments
 (0)