feat: security and auditing

This commit is contained in:
2026-02-04 16:48:08 -08:00
parent 11be34cd21
commit 0a654f423a
42 changed files with 2195 additions and 160 deletions
+8
View File
@@ -29,6 +29,14 @@ export const appRoutes: Route[] = [
path: 'manga',
loadComponent: () => import('./components/manga/manga-list.component').then(m => m.MangaListComponent)
},
{
path: 'admin/users',
loadComponent: () => import('./components/admin/admin-users.component').then(m => m.AdminUsersComponent)
},
{
path: 'admin/audit',
loadComponent: () => import('./components/admin/admin-audit.component').then(m => m.AdminAuditComponent)
},
{
path: '**',
redirectTo: ''
@@ -0,0 +1,373 @@
import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AuditLogService } from '../../services/audit.service';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import type { AuditLog, AuditAction, AuditCategory } from '@library/shared-types';
@Component({
selector: 'app-admin-audit',
standalone: true,
imports: [CommonModule, FormsModule],
template: `
<div class="audit-container">
<h1>Audit Logs</h1>
@if (!authService.isAuthenticated() || !authService.user()?.isAdmin) {
<div class="unauthorized">
<p>You must be an admin to view this page.</p>
</div>
} @else {
<div class="filters">
<div class="filter-group">
<label for="category-filter">Category:</label>
<select
id="category-filter"
[(ngModel)]="selectedCategory"
(change)="loadLogs()"
>
<option value="">All Categories</option>
<option value="AUTH">Authentication</option>
<option value="CONTENT">Content</option>
<option value="ADMIN">Administration</option>
<option value="SECURITY">Security</option>
</select>
</div>
<div class="filter-group">
<label for="action-filter">Action:</label>
<select
id="action-filter"
[(ngModel)]="selectedAction"
(change)="loadLogs()"
>
<option value="">All Actions</option>
<option value="LOGIN">Login</option>
<option value="LOGOUT">Logout</option>
<option value="LOGIN_FAILED">Login Failed</option>
<option value="COMMENT_CREATE">Comment Created</option>
<option value="COMMENT_DELETE">Comment Deleted</option>
<option value="ENTRY_CREATE">Entry Created</option>
<option value="ENTRY_UPDATE">Entry Updated</option>
<option value="ENTRY_DELETE">Entry Deleted</option>
<option value="USER_BAN">User Banned</option>
<option value="USER_UNBAN">User Unbanned</option>
<option value="RATE_LIMIT_EXCEEDED">Rate Limit Exceeded</option>
<option value="CSRF_VALIDATION_FAILED">CSRF Failed</option>
<option value="UNAUTHORIZED_ACCESS">Unauthorized Access</option>
</select>
</div>
<div class="filter-group">
<label for="success-filter">Status:</label>
<select
id="success-filter"
[(ngModel)]="selectedSuccess"
(change)="loadLogs()"
>
<option value="">All</option>
<option value="true">Success</option>
<option value="false">Failed</option>
</select>
</div>
<button class="refresh-btn" (click)="loadLogs()">Refresh</button>
</div>
@if (loading()) {
<div class="loading">Loading audit logs...</div>
} @else if (logs().length === 0) {
<div class="no-logs">No audit logs found.</div>
} @else {
<div class="logs-table-container">
<table class="logs-table">
<thead>
<tr>
<th>Time</th>
<th>Category</th>
<th>Action</th>
<th>Details</th>
<th>Status</th>
</tr>
</thead>
<tbody>
@for (log of logs(); track log.id) {
<tr [class.failed]="!log.success">
<td class="time">{{ formatDate(log.createdAt) }}</td>
<td>
<span
class="category-badge"
[style.background-color]="auditService.getCategoryColor(log.category)"
>
{{ auditService.getCategoryLabel(log.category) }}
</span>
</td>
<td>{{ auditService.getActionLabel(log.action) }}</td>
<td class="details">{{ log.details ?? '-' }}</td>
<td>
<span class="status-badge" [class.success]="log.success" [class.failed]="!log.success">
{{ log.success ? '✓' : '✗' }}
</span>
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="pagination">
<button
[disabled]="currentPage() <= 1"
(click)="goToPage(currentPage() - 1)"
>
Previous
</button>
<span>Page {{ currentPage() }} of {{ totalPages() }}</span>
<button
[disabled]="currentPage() >= totalPages()"
(click)="goToPage(currentPage() + 1)"
>
Next
</button>
</div>
}
}
</div>
`,
styles: [`
.audit-container {
max-width: 1400px;
margin: 0 auto;
padding: 2rem;
}
h1 {
color: #2d1b4e;
margin-bottom: 1.5rem;
}
.unauthorized {
text-align: center;
padding: 2rem;
background: #fef2f2;
border-radius: 8px;
color: #991b1b;
}
.filters {
display: flex;
gap: 1rem;
margin-bottom: 1.5rem;
flex-wrap: wrap;
align-items: flex-end;
background: rgba(255, 255, 255, 0.8);
padding: 1rem;
border-radius: 8px;
border: 1px solid #e5e7eb;
}
.filter-group {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.filter-group label {
font-size: 0.85rem;
color: #6b7280;
}
.filter-group select {
padding: 0.5rem;
border: 1px solid #d1d5db;
border-radius: 4px;
min-width: 150px;
}
.refresh-btn {
padding: 0.5rem 1rem;
background: #8b5cf6;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.refresh-btn:hover {
background: #7c3aed;
}
.loading, .no-logs {
text-align: center;
padding: 2rem;
color: #6b7280;
}
.logs-table-container {
overflow-x: auto;
background: white;
border-radius: 8px;
border: 1px solid #e5e7eb;
}
.logs-table {
width: 100%;
border-collapse: collapse;
}
.logs-table th,
.logs-table td {
padding: 0.75rem 1rem;
text-align: left;
border-bottom: 1px solid #e5e7eb;
}
.logs-table th {
background: #f9fafb;
font-weight: 600;
color: #374151;
}
.logs-table tr:hover {
background: #f9fafb;
}
.logs-table tr.failed {
background: #fef2f2;
}
.logs-table tr.failed:hover {
background: #fee2e2;
}
.time {
white-space: nowrap;
font-size: 0.85rem;
color: #6b7280;
}
.category-badge {
display: inline-block;
padding: 0.25rem 0.5rem;
border-radius: 4px;
color: white;
font-size: 0.75rem;
font-weight: 500;
}
.details {
max-width: 400px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.status-badge {
display: inline-block;
width: 24px;
height: 24px;
border-radius: 50%;
text-align: center;
line-height: 24px;
font-weight: bold;
}
.status-badge.success {
background: #dcfce7;
color: #16a34a;
}
.status-badge.failed {
background: #fee2e2;
color: #dc2626;
}
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 1rem;
margin-top: 1rem;
padding: 1rem;
}
.pagination button {
padding: 0.5rem 1rem;
background: #8b5cf6;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.pagination button:disabled {
background: #d1d5db;
cursor: not-allowed;
}
.pagination button:not(:disabled):hover {
background: #7c3aed;
}
`],
})
export class AdminAuditComponent implements OnInit {
authService = inject(AuthService);
auditService = inject(AuditLogService);
private router = inject(Router);
logs = signal<AuditLog[]>([]);
loading = signal(true);
currentPage = signal(1);
totalPages = signal(1);
selectedCategory = '';
selectedAction = '';
selectedSuccess = '';
ngOnInit() {
if (!this.authService.isAuthenticated() || !this.authService.user()?.isAdmin) {
this.router.navigate(['/']);
return;
}
this.loadLogs();
}
async loadLogs() {
this.loading.set(true);
try {
const filters: Record<string, unknown> = {
page: this.currentPage(),
limit: 50,
};
if (this.selectedCategory) {
filters['category'] = this.selectedCategory as AuditCategory;
}
if (this.selectedAction) {
filters['action'] = this.selectedAction as AuditAction;
}
if (this.selectedSuccess !== '') {
filters['success'] = this.selectedSuccess === 'true';
}
const response = await this.auditService.getLogs(filters);
this.logs.set(response.logs);
this.totalPages.set(response.totalPages);
} catch (error) {
console.error('Failed to load audit logs:', error);
} finally {
this.loading.set(false);
}
}
goToPage(page: number) {
this.currentPage.set(page);
this.loadLogs();
}
formatDate(date: Date | string): string {
const d = new Date(date);
return d.toLocaleString();
}
}
@@ -0,0 +1,268 @@
/**
* @copyright 2026 NHCarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
import { UserService } from '../../services/user.service';
import { AuthService } from '../../services/auth.service';
import { User } from '@library/shared-types';
@Component({
selector: 'app-admin-users',
standalone: true,
imports: [CommonModule],
template: `
<div class="admin-container">
<h2>User Management</h2>
@if (loading()) {
<p class="loading">Loading users...</p>
} @else if (error()) {
<p class="error">{{ error() }}</p>
} @else {
<div class="users-list">
@for (user of users(); track user.id) {
<div class="user-card" [class.banned]="user.isBanned">
<div class="user-info">
@if (user.avatarUrl) {
<img [src]="user.avatarUrl" [alt]="user.username" class="avatar" />
} @else {
<div class="avatar-placeholder">{{ user.username.charAt(0).toUpperCase() }}</div>
}
<div class="user-details">
<span class="username">{{ user.username }}</span>
<span class="email">{{ user.email }}</span>
@if (user.isAdmin) {
<span class="admin-badge">Admin</span>
}
@if (user.isBanned) {
<span class="banned-badge">Banned</span>
}
</div>
</div>
<div class="user-actions">
@if (!user.isAdmin) {
@if (user.isBanned) {
<button (click)="unbanUser(user.id)" class="btn btn-unban">Unban</button>
} @else {
<button (click)="banUser(user.id)" class="btn btn-ban">Ban</button>
}
}
</div>
</div>
} @empty {
<p class="no-users">No users found.</p>
}
</div>
}
</div>
`,
styles: [`
.admin-container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
h2 {
color: var(--witch-purple);
margin-bottom: 2rem;
}
.loading, .error, .no-users {
text-align: center;
padding: 2rem;
color: var(--witch-mauve);
}
.error {
color: var(--witch-rose);
}
.users-list {
display: flex;
flex-direction: column;
gap: 1rem;
}
.user-card {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 1.5rem;
background: var(--witch-moon);
border-radius: 8px;
box-shadow: 0 2px 8px var(--witch-shadow);
transition: all 0.3s;
}
.user-card.banned {
opacity: 0.7;
background: var(--witch-lavender);
}
.user-info {
display: flex;
align-items: center;
gap: 1rem;
}
.avatar {
width: 48px;
height: 48px;
border-radius: 50%;
object-fit: cover;
}
.avatar-placeholder {
width: 48px;
height: 48px;
border-radius: 50%;
background: var(--witch-purple);
color: var(--witch-moon);
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-size: 1.2rem;
}
.user-details {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.username {
font-weight: 600;
color: var(--witch-purple);
}
.email {
font-size: 0.85rem;
color: var(--witch-mauve);
}
.admin-badge {
display: inline-block;
background: var(--witch-rose);
color: var(--witch-moon);
padding: 0.15rem 0.5rem;
border-radius: 4px;
font-size: 0.75rem;
width: fit-content;
}
.banned-badge {
display: inline-block;
background: var(--witch-plum);
color: var(--witch-moon);
padding: 0.15rem 0.5rem;
border-radius: 4px;
font-size: 0.75rem;
width: fit-content;
}
.user-actions {
display: flex;
gap: 0.5rem;
}
.btn {
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 0.9rem;
transition: all 0.3s;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px var(--witch-shadow);
}
.btn-ban {
background: var(--witch-rose);
color: var(--witch-moon);
}
.btn-ban:hover {
background: var(--witch-plum);
}
.btn-unban {
background: var(--witch-purple);
color: var(--witch-moon);
}
.btn-unban:hover {
background: var(--witch-mauve);
color: var(--witch-purple);
}
`]
})
export class AdminUsersComponent implements OnInit {
private userService = inject(UserService);
private authService = inject(AuthService);
private router = inject(Router);
users = signal<User[]>([]);
loading = signal(true);
error = signal<string | null>(null);
ngOnInit(): void {
if (!this.authService.isAdmin()) {
this.router.navigate(['/']);
return;
}
this.loadUsers();
}
private loadUsers(): void {
this.loading.set(true);
this.error.set(null);
this.userService.getAllUsers().subscribe({
next: (users) => {
this.users.set(users);
this.loading.set(false);
},
error: (err) => {
this.error.set(err.message ?? 'Failed to load users');
this.loading.set(false);
}
});
}
banUser(userId: string): void {
this.userService.banUser(userId).subscribe({
next: (updatedUser) => {
this.users.update(users =>
users.map(u => u.id === userId ? updatedUser : u)
);
},
error: (err) => {
this.error.set(err.message ?? 'Failed to ban user');
}
});
}
unbanUser(userId: string): void {
this.userService.unbanUser(userId).subscribe({
next: (updatedUser) => {
this.users.update(users =>
users.map(u => u.id === userId ? updatedUser : u)
);
},
error: (err) => {
this.error.set(err.message ?? 'Failed to unban user');
}
});
}
}
@@ -10,6 +10,7 @@ import { FormsModule } from '@angular/forms';
import { ArtService } from '../../services/art.service';
import { AuthService } from '../../services/auth.service';
import { CommentsService } from '../../services/comments.service';
import { SanitizeService } from '../../services/sanitize.service';
import { Art, CreateArtDto, UpdateArtDto, Comment } from '@library/shared-types';
@Component({
@@ -210,15 +211,21 @@ import { Art, CreateArtDto, UpdateArtDto, Comment } from '@library/shared-types'
@if (expandedComments()[art.id]) {
<div class="comments-container">
@if (authService.isAuthenticated()) {
<form (ngSubmit)="addComment(art.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[art.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
@if (authService.user()?.isBanned) {
<div class="banned-notice">
You have been banned from commenting.
</div>
} @else {
<form (ngSubmit)="addComment(art.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[art.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
}
}
@if (commentsLoading()[art.id]) {
@@ -236,7 +243,7 @@ import { Art, CreateArtDto, UpdateArtDto, Comment } from '@library/shared-types'
<button (click)="deleteComment(art.id, comment.id)" class="btn btn-danger btn-xs">Delete</button>
}
</div>
<div class="comment-content" [innerHTML]="comment.content"></div>
<div class="comment-content" [innerHTML]="sanitizeService.sanitizeHtml(comment.content)"></div>
</div>
} @empty {
<div class="no-comments">No comments yet. Be the first to comment!</div>
@@ -621,12 +628,24 @@ import { Art, CreateArtDto, UpdateArtDto, Comment } from '@library/shared-types'
color: var(--witch-mauve);
font-size: 0.9rem;
}
.banned-notice {
background: #fef2f2;
border: 1px solid #fecaca;
color: #991b1b;
padding: 0.75rem 1rem;
border-radius: 4px;
text-align: center;
margin-bottom: 1rem;
font-size: 0.9rem;
}
`]
})
export class ArtGalleryComponent implements OnInit {
artService = inject(ArtService);
authService = inject(AuthService);
commentsService = inject(CommentsService);
sanitizeService = inject(SanitizeService);
artPieces = signal<Art[]>([]);
loading = signal(true);
@@ -10,6 +10,7 @@ import { FormsModule } from '@angular/forms';
import { BooksService } from '../../services/books.service';
import { AuthService } from '../../services/auth.service';
import { CommentsService } from '../../services/comments.service';
import { SanitizeService } from '../../services/sanitize.service';
import { Book, BookStatus, CreateBookDto, UpdateBookDto, Comment } from '@library/shared-types';
@Component({
@@ -317,15 +318,21 @@ import { Book, BookStatus, CreateBookDto, UpdateBookDto, Comment } from '@librar
@if (expandedComments()[book.id]) {
<div class="comments-container">
@if (authService.isAuthenticated()) {
<form (ngSubmit)="addComment(book.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[book.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
@if (authService.user()?.isBanned) {
<div class="banned-notice">
You have been banned from commenting.
</div>
} @else {
<form (ngSubmit)="addComment(book.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[book.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
}
}
@if (commentsLoading()[book.id]) {
@@ -343,7 +350,7 @@ import { Book, BookStatus, CreateBookDto, UpdateBookDto, Comment } from '@librar
<button (click)="deleteComment(book.id, comment.id)" class="btn btn-danger btn-xs">Delete</button>
}
</div>
<div class="comment-content" [innerHTML]="comment.content"></div>
<div class="comment-content" [innerHTML]="sanitizeService.sanitizeHtml(comment.content)"></div>
</div>
} @empty {
<div class="no-comments">No comments yet. Be the first to comment!</div>
@@ -703,6 +710,17 @@ import { Book, BookStatus, CreateBookDto, UpdateBookDto, Comment } from '@librar
font-size: 0.9rem;
}
.banned-notice {
background: #fef2f2;
border: 1px solid #fecaca;
color: #991b1b;
padding: 0.75rem 1rem;
border-radius: 4px;
text-align: center;
margin-bottom: 1rem;
font-size: 0.9rem;
}
.image-preview {
margin-top: 0.5rem;
display: flex;
@@ -741,6 +759,7 @@ export class BooksListComponent implements OnInit {
booksService = inject(BooksService);
authService = inject(AuthService);
commentsService = inject(CommentsService);
sanitizeService = inject(SanitizeService);
books = signal<Book[]>([]);
loading = signal(true);
@@ -10,6 +10,7 @@ import { FormsModule } from '@angular/forms';
import { GamesService } from '../../services/games.service';
import { AuthService } from '../../services/auth.service';
import { CommentsService } from '../../services/comments.service';
import { SanitizeService } from '../../services/sanitize.service';
import { Game, GameStatus, CreateGameDto, UpdateGameDto, Comment } from '@library/shared-types';
@Component({
@@ -282,15 +283,21 @@ import { Game, GameStatus, CreateGameDto, UpdateGameDto, Comment } from '@librar
@if (expandedComments()[game.id]) {
<div class="comments-container">
@if (authService.isAuthenticated()) {
<form (ngSubmit)="addComment(game.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[game.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
@if (authService.user()?.isBanned) {
<div class="banned-notice">
You have been banned from commenting.
</div>
} @else {
<form (ngSubmit)="addComment(game.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[game.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
}
}
@if (commentsLoading()[game.id]) {
@@ -308,7 +315,7 @@ import { Game, GameStatus, CreateGameDto, UpdateGameDto, Comment } from '@librar
<button (click)="deleteComment(game.id, comment.id)" class="btn btn-danger btn-xs">Delete</button>
}
</div>
<div class="comment-content" [innerHTML]="comment.content"></div>
<div class="comment-content" [innerHTML]="sanitizeService.sanitizeHtml(comment.content)"></div>
</div>
} @empty {
<div class="no-comments">No comments yet. Be the first to comment!</div>
@@ -582,6 +589,17 @@ import { Game, GameStatus, CreateGameDto, UpdateGameDto, Comment } from '@librar
font-size: 0.9rem;
}
.banned-notice {
background: #fef2f2;
border: 1px solid #fecaca;
color: #991b1b;
padding: 0.75rem 1rem;
border-radius: 4px;
text-align: center;
margin-bottom: 1rem;
font-size: 0.9rem;
}
.image-preview {
margin-top: 0.5rem;
display: flex;
@@ -620,6 +638,7 @@ export class GamesListComponent implements OnInit {
gamesService = inject(GamesService);
authService = inject(AuthService);
commentsService = inject(CommentsService);
sanitizeService = inject(SanitizeService);
games = signal<Game[]>([]);
loading = signal(true);
@@ -33,7 +33,8 @@ import { AuthService } from '../../services/auth.service';
@if (authService.user(); as user) {
<span class="welcome">Welcome, {{ user.username }}!</span>
@if (user.isAdmin) {
<span class="admin-badge">Admin</span>
<a routerLink="/admin/users" class="admin-badge">Users</a>
<a routerLink="/admin/audit" class="admin-badge">Audit</a>
}
<button (click)="logout()" class="btn btn-secondary">Logout</button>
} @else {
@@ -111,6 +112,14 @@ import { AuthService } from '../../services/auth.service';
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 0.8rem;
text-decoration: none;
cursor: pointer;
transition: all 0.3s;
}
.admin-badge:hover {
background-color: var(--witch-plum);
transform: translateY(-2px);
}
.btn {
@@ -10,6 +10,7 @@ import { FormsModule } from '@angular/forms';
import { MangaService } from '../../services/manga.service';
import { AuthService } from '../../services/auth.service';
import { CommentsService } from '../../services/comments.service';
import { SanitizeService } from '../../services/sanitize.service';
import { Manga, MangaStatus, CreateMangaDto, UpdateMangaDto, Comment } from '@library/shared-types';
@Component({
@@ -282,15 +283,21 @@ import { Manga, MangaStatus, CreateMangaDto, UpdateMangaDto, Comment } from '@li
@if (expandedComments()[manga.id]) {
<div class="comments-container">
@if (authService.isAuthenticated()) {
<form (ngSubmit)="addComment(manga.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[manga.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
@if (authService.user()?.isBanned) {
<div class="banned-notice">
You have been banned from commenting.
</div>
} @else {
<form (ngSubmit)="addComment(manga.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[manga.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
}
}
@if (commentsLoading()[manga.id]) {
@@ -308,7 +315,7 @@ import { Manga, MangaStatus, CreateMangaDto, UpdateMangaDto, Comment } from '@li
<button (click)="deleteComment(manga.id, comment.id)" class="btn btn-danger btn-xs">Delete</button>
}
</div>
<div class="comment-content" [innerHTML]="comment.content"></div>
<div class="comment-content" [innerHTML]="sanitizeService.sanitizeHtml(comment.content)"></div>
</div>
} @empty {
<div class="no-comments">No comments yet. Be the first to comment!</div>
@@ -584,6 +591,17 @@ import { Manga, MangaStatus, CreateMangaDto, UpdateMangaDto, Comment } from '@li
font-size: 0.9rem;
}
.banned-notice {
background: #fef2f2;
border: 1px solid #fecaca;
color: #991b1b;
padding: 0.75rem 1rem;
border-radius: 4px;
text-align: center;
margin-bottom: 1rem;
font-size: 0.9rem;
}
.image-preview {
margin-top: 0.5rem;
display: flex;
@@ -622,6 +640,7 @@ export class MangaListComponent implements OnInit {
mangaService = inject(MangaService);
authService = inject(AuthService);
commentsService = inject(CommentsService);
sanitizeService = inject(SanitizeService);
mangaList = signal<Manga[]>([]);
loading = signal(true);
@@ -10,6 +10,7 @@ import { FormsModule } from '@angular/forms';
import { MusicService } from '../../services/music.service';
import { AuthService } from '../../services/auth.service';
import { CommentsService } from '../../services/comments.service';
import { SanitizeService } from '../../services/sanitize.service';
import { Music, MusicStatus, MusicType, CreateMusicDto, UpdateMusicDto, Comment } from '@library/shared-types';
@Component({
@@ -355,15 +356,21 @@ import { Music, MusicStatus, MusicType, CreateMusicDto, UpdateMusicDto, Comment
@if (expandedComments()[music.id]) {
<div class="comments-container">
@if (authService.isAuthenticated()) {
<form (ngSubmit)="addComment(music.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[music.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
@if (authService.user()?.isBanned) {
<div class="banned-notice">
You have been banned from commenting.
</div>
} @else {
<form (ngSubmit)="addComment(music.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[music.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
}
}
@if (commentsLoading()[music.id]) {
@@ -381,7 +388,7 @@ import { Music, MusicStatus, MusicType, CreateMusicDto, UpdateMusicDto, Comment
<button (click)="deleteComment(music.id, comment.id)" class="btn btn-danger btn-xs">Delete</button>
}
</div>
<div class="comment-content" [innerHTML]="comment.content"></div>
<div class="comment-content" [innerHTML]="sanitizeService.sanitizeHtml(comment.content)"></div>
</div>
} @empty {
<div class="no-comments">No comments yet. Be the first to comment!</div>
@@ -775,6 +782,17 @@ import { Music, MusicStatus, MusicType, CreateMusicDto, UpdateMusicDto, Comment
font-size: 0.9rem;
}
.banned-notice {
background: #fef2f2;
border: 1px solid #fecaca;
color: #991b1b;
padding: 0.75rem 1rem;
border-radius: 4px;
text-align: center;
margin-bottom: 1rem;
font-size: 0.9rem;
}
.image-preview {
margin-top: 0.5rem;
display: flex;
@@ -813,6 +831,7 @@ export class MusicListComponent implements OnInit {
musicService = inject(MusicService);
authService = inject(AuthService);
commentsService = inject(CommentsService);
sanitizeService = inject(SanitizeService);
music = signal<Music[]>([]);
loading = signal(true);
@@ -10,6 +10,7 @@ import { FormsModule } from '@angular/forms';
import { ShowsService } from '../../services/shows.service';
import { AuthService } from '../../services/auth.service';
import { CommentsService } from '../../services/comments.service';
import { SanitizeService } from '../../services/sanitize.service';
import { Show, ShowStatus, ShowType, CreateShowDto, UpdateShowDto, Comment } from '@library/shared-types';
@Component({
@@ -278,15 +279,21 @@ import { Show, ShowStatus, ShowType, CreateShowDto, UpdateShowDto, Comment } fro
@if (expandedComments()[show.id]) {
<div class="comments-container">
@if (authService.isAuthenticated()) {
<form (ngSubmit)="addComment(show.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[show.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
@if (authService.user()?.isBanned) {
<div class="banned-notice">
You have been banned from commenting.
</div>
} @else {
<form (ngSubmit)="addComment(show.id)" class="comment-form">
<textarea
[(ngModel)]="newCommentContent[show.id]"
name="comment"
placeholder="Add a comment (Markdown supported)..."
rows="2"
></textarea>
<button type="submit" class="btn btn-primary btn-sm">Post Comment</button>
</form>
}
}
@if (commentsLoading()[show.id]) {
@@ -304,7 +311,7 @@ import { Show, ShowStatus, ShowType, CreateShowDto, UpdateShowDto, Comment } fro
<button (click)="deleteComment(show.id, comment.id)" class="btn btn-danger btn-xs">Delete</button>
}
</div>
<div class="comment-content" [innerHTML]="comment.content"></div>
<div class="comment-content" [innerHTML]="sanitizeService.sanitizeHtml(comment.content)"></div>
</div>
} @empty {
<div class="no-comments">No comments yet. Be the first to comment!</div>
@@ -579,6 +586,17 @@ import { Show, ShowStatus, ShowType, CreateShowDto, UpdateShowDto, Comment } fro
font-size: 0.9rem;
}
.banned-notice {
background: #fef2f2;
border: 1px solid #fecaca;
color: #991b1b;
padding: 0.75rem 1rem;
border-radius: 4px;
text-align: center;
margin-bottom: 1rem;
font-size: 0.9rem;
}
.image-preview {
margin-top: 0.5rem;
display: flex;
@@ -617,6 +635,7 @@ export class ShowsListComponent implements OnInit {
showsService = inject(ShowsService);
authService = inject(AuthService);
commentsService = inject(CommentsService);
sanitizeService = inject(SanitizeService);
shows = signal<Show[]>([]);
loading = signal(true);
+58 -23
View File
@@ -4,50 +4,85 @@
* @author Naomi Carrigan
*/
import { Injectable } from '@angular/core';
import { Injectable, signal, inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Observable, switchMap, tap, of } from 'rxjs';
import { environment } from '../../environments/environment';
interface CsrfTokenResponse {
csrfToken: string;
}
@Injectable({
providedIn: 'root'
})
export class ApiService {
private http = inject(HttpClient);
private readonly apiUrl = environment.apiUrl;
constructor(private http: HttpClient) {}
private csrfToken = signal<string | null>(null);
private getHeaders(): HttpHeaders {
// Auth token is sent as httpOnly cookie, no need to add manually
return new HttpHeaders({
const headers: Record<string, string> = {
'Content-Type': 'application/json'
});
};
const token = this.csrfToken();
if (token) {
headers['X-CSRF-Token'] = token;
}
return new HttpHeaders(headers);
}
private ensureCsrfToken(): Observable<string> {
const existingToken = this.csrfToken();
if (existingToken) {
return of(existingToken);
}
return this.http.get<CsrfTokenResponse>(`${this.apiUrl}/auth/csrf-token`, {
withCredentials: true
}).pipe(
tap(response => this.csrfToken.set(response.csrfToken)),
switchMap(response => of(response.csrfToken))
);
}
get<T>(endpoint: string): Observable<T> {
return this.http.get<T>(`${this.apiUrl}${endpoint}`, {
headers: this.getHeaders(),
withCredentials: true // Important for cookies
});
}
post<T>(endpoint: string, body: any): Observable<T> {
return this.http.post<T>(`${this.apiUrl}${endpoint}`, body, {
headers: this.getHeaders(),
withCredentials: true
});
}
put<T>(endpoint: string, body: any): Observable<T> {
return this.http.put<T>(`${this.apiUrl}${endpoint}`, body, {
headers: this.getHeaders(),
withCredentials: true
});
post<T>(endpoint: string, body: unknown): Observable<T> {
return this.ensureCsrfToken().pipe(
switchMap(() => this.http.post<T>(`${this.apiUrl}${endpoint}`, body, {
headers: this.getHeaders(),
withCredentials: true
}))
);
}
put<T>(endpoint: string, body: unknown): Observable<T> {
return this.ensureCsrfToken().pipe(
switchMap(() => this.http.put<T>(`${this.apiUrl}${endpoint}`, body, {
headers: this.getHeaders(),
withCredentials: true
}))
);
}
delete<T>(endpoint: string): Observable<T> {
return this.http.delete<T>(`${this.apiUrl}${endpoint}`, {
withCredentials: true
});
return this.ensureCsrfToken().pipe(
switchMap(() => this.http.delete<T>(`${this.apiUrl}${endpoint}`, {
headers: this.getHeaders(),
withCredentials: true
}))
);
}
}
clearCsrfToken(): void {
this.csrfToken.set(null);
}
}
@@ -0,0 +1,84 @@
import { Injectable, inject } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { ApiService } from './api.service';
import type { AuditLog, AuditLogFilters, AuditAction, AuditCategory } from '@library/shared-types';
interface AuditLogResponse {
logs: AuditLog[];
total: number;
page: number;
limit: number;
totalPages: number;
}
@Injectable({
providedIn: 'root',
})
export class AuditLogService {
private api = inject(ApiService);
async getLogs(filters: AuditLogFilters = {}): Promise<AuditLogResponse> {
const params = new URLSearchParams();
if (filters.action) params.set('action', filters.action);
if (filters.category) params.set('category', filters.category);
if (filters.userId) params.set('userId', filters.userId);
if (filters.success !== undefined) params.set('success', String(filters.success));
if (filters.startDate) params.set('startDate', filters.startDate.toISOString());
if (filters.endDate) params.set('endDate', filters.endDate.toISOString());
if (filters.page) params.set('page', String(filters.page));
if (filters.limit) params.set('limit', String(filters.limit));
const queryString = params.toString();
const url = queryString ? `/audit?${queryString}` : '/audit';
return firstValueFrom(this.api.get<AuditLogResponse>(url));
}
async getSecurityLogs(page = 1, limit = 50): Promise<AuditLogResponse> {
return firstValueFrom(this.api.get<AuditLogResponse>(`/audit/security?page=${page}&limit=${limit}`));
}
async getUserLogs(userId: string, page = 1, limit = 50): Promise<AuditLogResponse> {
return firstValueFrom(this.api.get<AuditLogResponse>(`/audit/user/${userId}?page=${page}&limit=${limit}`));
}
getActionLabel(action: AuditAction): string {
const labels: Record<string, string> = {
LOGIN: 'Login',
LOGOUT: 'Logout',
LOGIN_FAILED: 'Login Failed',
COMMENT_CREATE: 'Comment Created',
COMMENT_DELETE: 'Comment Deleted',
ENTRY_CREATE: 'Entry Created',
ENTRY_UPDATE: 'Entry Updated',
ENTRY_DELETE: 'Entry Deleted',
USER_BAN: 'User Banned',
USER_UNBAN: 'User Unbanned',
RATE_LIMIT_EXCEEDED: 'Rate Limit Exceeded',
CSRF_VALIDATION_FAILED: 'CSRF Validation Failed',
UNAUTHORIZED_ACCESS: 'Unauthorized Access',
};
return labels[action] ?? action;
}
getCategoryLabel(category: AuditCategory): string {
const labels: Record<string, string> = {
AUTH: 'Authentication',
CONTENT: 'Content',
ADMIN: 'Administration',
SECURITY: 'Security',
};
return labels[category] ?? category;
}
getCategoryColor(category: AuditCategory): string {
const colors: Record<string, string> = {
AUTH: '#3b82f6', // blue
CONTENT: '#10b981', // green
ADMIN: '#8b5cf6', // purple
SECURITY: '#ef4444', // red
};
return colors[category] ?? '#6b7280';
}
}
@@ -40,6 +40,7 @@ export class AuthService {
return this.api.post<{ message: string }>('/auth/logout', {}).pipe(
tap(() => {
this.currentUser.set(null);
this.api.clearCsrfToken();
this.router.navigate(['/']);
})
);
@@ -0,0 +1,28 @@
/**
* @copyright 2026 NHCarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { Injectable, SecurityContext, inject } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
/**
* Service for sanitizing HTML content on the frontend.
* Provides defence-in-depth XSS protection alongside backend sanitization.
*/
@Injectable({
providedIn: 'root'
})
export class SanitizeService {
private sanitizer = inject(DomSanitizer);
/**
* Sanitizes HTML content for safe rendering.
* This provides a second layer of protection after backend sanitization.
*/
sanitizeHtml(html: string): SafeHtml {
const sanitized = this.sanitizer.sanitize(SecurityContext.HTML, html);
return this.sanitizer.bypassSecurityTrustHtml(sanitized ?? '');
}
}
@@ -0,0 +1,29 @@
/**
* @copyright 2026 NHCarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from './api.service';
import { User } from '@library/shared-types';
@Injectable({
providedIn: 'root'
})
export class UserService {
private api = inject(ApiService);
getAllUsers(): Observable<User[]> {
return this.api.get<User[]>('/users');
}
banUser(userId: string): Observable<User> {
return this.api.post<User>(`/users/${userId}/ban`, {});
}
unbanUser(userId: string): Observable<User> {
return this.api.post<User>(`/users/${userId}/unban`, {});
}
}