Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions backend/src/Fastasys.ApiService/Controllers/ProfileController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Text;
using Fastasys.ApiService.Data;
using Fastasys.ApiService.Data.Entities;
using Fastasys.ApiService.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Fastasys.ApiService.Controllers;

public record UserProfileDto(string FirstName, string LastName, [Required, EmailAddress] string Email);

public record ChangePasswordDto([Required] string CurrentPassword, [Required] string NewPassword);

[ApiController]
[Authorize]
[Route("api/profile")]
public class ProfileController(InfosysDbContext db) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<UserProfileDto>> Get(CancellationToken cancellationToken)
{
var user = await GetCurrentUser(cancellationToken);
if (user is null)
return Unauthorized();

return new UserProfileDto(user.FirstName, user.LastName, user.Email);
}

[HttpPut]
public async Task<ActionResult<UserProfileDto>> Update(UserProfileDto profile, CancellationToken cancellationToken)
{
var user = await GetCurrentUser(cancellationToken);
if (user is null)
return Unauthorized();

user.FirstName = profile.FirstName.Trim();
user.LastName = profile.LastName.Trim();
user.Email = profile.Email.Trim();
await db.SaveChangesAsync(cancellationToken);

return new UserProfileDto(user.FirstName, user.LastName, user.Email);
}

[HttpPut("password")]
public async Task<IActionResult> ChangePassword(ChangePasswordDto passwords, CancellationToken cancellationToken)
{
var user = await GetCurrentUser(cancellationToken);
if (user is null)
return Unauthorized();

if (Encoding.UTF8.GetByteCount(passwords.NewPassword) > 72)
return BadRequest(new { code = "newPasswordTooLong" });

var (isValid, _) = AuthService.VerifyPassword(passwords.CurrentPassword, user.PasswordHash);
if (!isValid)
return BadRequest(new { code = "wrongCurrentPassword" });

user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(passwords.NewPassword);
await db.SaveChangesAsync(cancellationToken);

return NoContent();
}

private async Task<User?> GetCurrentUser(CancellationToken cancellationToken)
{
if (!int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var userId))
return null;

return await db.Users.SingleOrDefaultAsync(user => user.Id == userId && user.IsActive, cancellationToken);
}
}
13 changes: 5 additions & 8 deletions backend/src/Fastasys.ApiService/Services/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private AuthResponseDto GenerateAuthResponse(User user)
return new AuthResponseDto(tokenString, refreshToken, expiresAt, userInfo);
}

private static (bool IsValid, bool NeedsUpgrade) VerifyPassword(string inputPassword, string passwordHash)
internal static (bool IsValid, bool NeedsUpgrade) VerifyPassword(string inputPassword, string passwordHash)
{
if (string.IsNullOrEmpty(passwordHash))
return (false, false);
Expand All @@ -149,14 +149,11 @@ private static (bool IsValid, bool NeedsUpgrade) VerifyPassword(string inputPass
}

// 2. Check legacy MD5 hash (32 hex characters) from Infosys PHP
using var md5 = System.Security.Cryptography.MD5.Create();
var bytes = System.Text.Encoding.UTF8.GetBytes(inputPassword);
var hashBytes = md5.ComputeHash(bytes);
var md5String = Convert.ToHexString(hashBytes).ToLowerInvariant();

if (passwordHash.Equals(md5String, StringComparison.OrdinalIgnoreCase))
if (passwordHash.Length == 32 && passwordHash.All(Uri.IsHexDigit))
{
return (true, true); // Match! Signal to upgrade to BCrypt.
var hashBytes = System.Security.Cryptography.MD5.HashData(Encoding.UTF8.GetBytes(inputPassword));
var matches = passwordHash.Equals(Convert.ToHexString(hashBytes), StringComparison.OrdinalIgnoreCase);
return (matches, matches);
}

// 3. Dev plaintext fallback (e.g., initial seed "admin123")
Expand Down
63 changes: 63 additions & 0 deletions backend/tests/Fastasys.Tests/ProfileAuthorizationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Net.Http.Json;
using System.Text.Json;
using Fastasys.ApiService.Controllers;
using Fastasys.ApiService.Services;
using Fastasys.Tests.testHelpers;

namespace Fastasys.Tests;

public class ProfileAuthorizationTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
{
[Fact]
public async Task ProfileRequiresSignIn()
{
using var client = factory.CreateClient();
var ct = TestContext.Current.CancellationToken;

Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/profile", ct)).StatusCode);
var response = await client.PutAsJsonAsync("/api/profile", new UserProfileDto("Ada", "Lovelace", "ada@example.com"), ct);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
var passwordResponse = await client.PutAsJsonAsync("/api/profile/password", new ChangePasswordDto("old", "new"), ct);
Assert.Equal(HttpStatusCode.Unauthorized, passwordResponse.StatusCode);
}

[Fact]
public async Task UpdatesOnlyTheSignedInUsersProfile()
{
var helper = new TestHelper(factory);
using var client = await helper.CreateClientWithPrivilegeAsync([]);
using var otherClient = await helper.CreateClientWithPrivilegeAsync([]);
var ct = TestContext.Current.CancellationToken;
var otherProfile = await otherClient.GetFromJsonAsync<UserProfileDto>("/api/profile", ct);
var profile = new UserProfileDto("Ada", "Lovelace", "ada@example.com");

var response = await client.PutAsJsonAsync("/api/profile", profile, ct);

Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(profile, await client.GetFromJsonAsync<UserProfileDto>("/api/profile", ct));
Assert.Equal(otherProfile, await otherClient.GetFromJsonAsync<UserProfileDto>("/api/profile", ct));
}

[Fact]
public async Task ChangingPasswordRequiresTheCurrentPasswordAndUpdatesTheNextLogin()
{
var helper = new TestHelper(factory);
using var client = await helper.CreateClientWithPrivilegeAsync([]);
var ct = TestContext.Current.CancellationToken;
var identity = await client.GetFromJsonAsync<JsonElement>("/api/auth/me", ct);
var username = identity.GetProperty("username").GetString()!;
const string currentPassword = "test-password";
const string newPassword = "new-password";

var rejected = await client.PutAsJsonAsync("/api/profile/password", new ChangePasswordDto("incorrect", newPassword), ct);
Assert.Equal(HttpStatusCode.BadRequest, rejected.StatusCode);

var changed = await client.PutAsJsonAsync("/api/profile/password", new ChangePasswordDto(currentPassword, newPassword), ct);
Assert.Equal(HttpStatusCode.NoContent, changed.StatusCode);

var oldLogin = await client.PostAsJsonAsync("/api/auth/login", new LoginDto(username, currentPassword), ct);
Assert.Equal(HttpStatusCode.Unauthorized, oldLogin.StatusCode);
var newLogin = await client.PostAsJsonAsync("/api/auth/login", new LoginDto(username, newPassword), ct);
Assert.Equal(HttpStatusCode.OK, newLogin.StatusCode);
}
}
15 changes: 15 additions & 0 deletions frontend/public/assets/i18n/da.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@
"Sunday": "Søn"
}
},
"profile": {
"accountMenu": "Kontomenu",
"edit": "Redigér profil",
"loading": "Henter profil …",
"loadFailed": "Profilen kunne ikke hentes.",
"saveFailed": "Profilen kunne ikke gemmes.",
"saved": "Profilen er gemt.",
"changePassword": "Skift adgangskode",
"currentPassword": "Nuværende adgangskode",
"newPassword": "Ny adgangskode",
"wrongCurrentPassword": "Den nuværende adgangskode er forkert.",
"newPasswordTooLong": "Den nye adgangskode er for lang. Vælg en kortere adgangskode.",
"passwordChangeFailed": "Adgangskoden kunne ikke ændres.",
"passwordChanged": "Adgangskoden er ændret."
},
"users": {
"title": "Brugerkonti",
"subtitle": "Administrer brugerkonti, tildelte roller og status i FastaSys.",
Expand Down
15 changes: 15 additions & 0 deletions frontend/public/assets/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@
"Sunday": "Sun"
}
},
"profile": {
"accountMenu": "Account menu",
"edit": "Edit profile",
"loading": "Loading profile…",
"loadFailed": "The profile could not be loaded.",
"saveFailed": "The profile could not be saved.",
"saved": "Your profile has been saved.",
"changePassword": "Change password",
"currentPassword": "Current password",
"newPassword": "New password",
"wrongCurrentPassword": "The current password is incorrect.",
"newPasswordTooLong": "The new password is too long. Choose a shorter password.",
"passwordChangeFailed": "The password could not be changed.",
"passwordChanged": "Your password has been changed."
},
"users": {
"title": "User Accounts",
"subtitle": "Manage user accounts, assigned roles, and access status for FastaSys.",
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/app/app.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { BoardgamesComponent } from './features/boardgames/boardgames';
import { CommunicationsComponent } from './features/communications/communications';
import { HeroForceComponent } from './features/hero-force/hero-force';
import { LoginComponent } from './features/login/login';
import { ProfileComponent } from './features/profile/profile';
import { ParticipantsComponent } from './features/participants/participants';
import { ActivitySettingsComponent } from './features/management/activity-settings/activity-settings';
import { ParticipantDetailComponent } from './features/participants/participant-detail/participant-detail';
Expand All @@ -32,6 +33,7 @@ export const routes: Routes = [
{ path: '', redirectTo: 'participants', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [authGuard] },
{ path: 'participants', component: ParticipantsComponent, canActivate: [authGuard] },
{ path: 'management/activity-settings', component: ActivitySettingsComponent, canActivate: [authGuard] },
{ path: 'participants/new', component: ParticipantFormComponent, canActivate: [authGuard] },
Expand Down
40 changes: 40 additions & 0 deletions frontend/src/app/features/profile/change-password-dialog.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<h2 mat-dialog-title>{{ 'profile.changePassword' | translate }}</h2>

<form #passwordForm="ngForm" (ngSubmit)="changePassword()">
<mat-dialog-content>
<mat-form-field appearance="outline">
<mat-label>{{ 'profile.currentPassword' | translate }}</mat-label>
<input
matInput
type="password"
name="currentPassword"
autocomplete="current-password"
required
[(ngModel)]="currentPassword"
[readonly]="saving()"
/>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>{{ 'profile.newPassword' | translate }}</mat-label>
<input
matInput
type="password"
name="newPassword"
autocomplete="new-password"
required
[(ngModel)]="newPassword"
[readonly]="saving()"
/>
</mat-form-field>
@if (error(); as error) {
<p role="alert">{{ 'profile.' + error | translate }}</p>
}
</mat-dialog-content>

<mat-dialog-actions align="end">
<button mat-button mat-dialog-close type="button" [disabled]="saving()">{{ 'common.cancel' | translate }}</button>
<button mat-flat-button type="submit" [disabled]="passwordForm.invalid || saving() || !newPassword.trim()">
{{ 'profile.changePassword' | translate }}
</button>
</mat-dialog-actions>
</form>
50 changes: 50 additions & 0 deletions frontend/src/app/features/profile/change-password-dialog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { TranslatePipe } from '@shared/pipes';

@Component({
selector: 'app-change-password-dialog',
imports: [FormsModule, MatButtonModule, MatDialogModule, MatFormFieldModule, MatInputModule, TranslatePipe],
templateUrl: './change-password-dialog.html',
styles: `
mat-dialog-content {
display: grid;
gap: 0.5rem;
}
`,
})
export class ChangePasswordDialog {
private readonly http = inject(HttpClient);
private readonly dialogRef = inject(MatDialogRef<ChangePasswordDialog, boolean>);

public currentPassword = '';
public newPassword = '';
readonly saving = signal(false);
readonly error = signal<'wrongCurrentPassword' | 'newPasswordTooLong' | 'passwordChangeFailed' | null>(null);

public changePassword(): void {
if (this.saving() || !this.currentPassword || !this.newPassword.trim()) return;

this.error.set(null);
this.saving.set(true);
this.dialogRef.disableClose = true;
this.http
.put<null>('/api/profile/password', { currentPassword: this.currentPassword, newPassword: this.newPassword })
.subscribe({
next: () => this.dialogRef.close(true),
error: (error: HttpErrorResponse) => {
this.saving.set(false);
this.dialogRef.disableClose = false;
const code: unknown = error.status === 400 ? error.error?.code : null;
this.error.set(
code === 'wrongCurrentPassword' || code === 'newPasswordTooLong' ? code : 'passwordChangeFailed',
);
},
});
}
}
66 changes: 66 additions & 0 deletions frontend/src/app/features/profile/profile.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<div class="page-container">
<header class="page-header">
<h1>{{ 'profile.edit' | translate }}</h1>
@if (profile()) {
<button mat-stroked-button type="button" (click)="openPasswordDialog()">
{{ 'profile.changePassword' | translate }}
</button>
}
</header>

@if (passwordChanged()) {
<p role="status">{{ 'profile.passwordChanged' | translate }}</p>
} @if (error(); as error) {
<p role="alert">{{ 'profile.' + error | translate }}</p>
} @if (profile(); as fields) {
<app-card>
<form #profileForm="ngForm" (ngSubmit)="profileForm.valid && save(fields)">
<mat-form-field appearance="outline">
<mat-label>{{ 'users.firstName' | translate }}</mat-label>
<input
matInput
name="firstName"
autocomplete="given-name"
[(ngModel)]="fields.firstName"
[readonly]="saving()"
(ngModelChange)="saved.set(false)"
/>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>{{ 'users.lastName' | translate }}</mat-label>
<input
matInput
name="lastName"
autocomplete="family-name"
[(ngModel)]="fields.lastName"
[readonly]="saving()"
(ngModelChange)="saved.set(false)"
/>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>{{ 'users.email' | translate }}</mat-label>
<input
matInput
name="email"
type="email"
autocomplete="email"
required
email
[(ngModel)]="fields.email"
[readonly]="saving()"
(ngModelChange)="saved.set(false)"
/>
</mat-form-field>

<button mat-flat-button type="submit" [disabled]="profileForm.invalid || saving()">
{{ 'common.save' | translate }}
</button>
@if (saved()) {
<p role="status">{{ 'profile.saved' | translate }}</p>
}
</form>
</app-card>
} @else if (!error()) {
<p role="status">{{ 'profile.loading' | translate }}</p>
}
</div>
Loading