master #1

Open
binhdeptrai wants to merge 0 commits from master into main
30 changed files with 205 additions and 1335 deletions

View File

@@ -51,13 +51,6 @@ $ npm run dev
# build,deploy # build,deploy
$ npm run build $ npm run build
```
### if using both github and git tea
```
git add .
git commit -m "Your commit message"
git push
``` ```
# Deploy # Deploy

View File

@@ -12,7 +12,6 @@ import { CsrfMiddleware } from './common/middleware/csrf.middleware';
import { AuthModule } from './auth/auth.module'; import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module'; import { UsersModule } from './users/users.module';
import { BlogPostsModule } from './blog-posts/blog-posts.module'; import { BlogPostsModule } from './blog-posts/blog-posts.module';
import { PagesModule } from './pages/pages.module';
import { TokensModule } from './tokens/tokens.module'; import { TokensModule } from './tokens/tokens.module';
import { User } from './users/entities/user.entity'; import { User } from './users/entities/user.entity';
@@ -58,7 +57,6 @@ import { OAuthAccount } from './tokens/entities/oauth-account.entity';
AuthModule, AuthModule,
UsersModule, UsersModule,
BlogPostsModule, BlogPostsModule,
PagesModule,
TokensModule, TokensModule,
], ],
providers: [ providers: [

View File

@@ -17,33 +17,45 @@ import { PasswordResetConfirmDto } from './dto/password-reset-confirm.dto';
import { PasswordResetRequestDto } from './dto/password-reset-request.dto'; import { PasswordResetRequestDto } from './dto/password-reset-request.dto';
import { RegisterDto } from './dto/register.dto'; import { RegisterDto } from './dto/register.dto';
import { Public } from '../common/decorators/public.decorator'; import { Public } from '../common/decorators/public.decorator';
import { CurrentUser } from '../common/decorators/current-user.decorator';
@Controller('auth') @Controller('auth')
@Public()
export class AuthController { export class AuthController {
constructor(private readonly authService: AuthService) {} constructor(private readonly authService: AuthService) {}
/** Returns the JWT payload of the currently logged-in user.
* Used by the frontend to restore auth state (e.g. after Google OAuth redirect). */
@Get('me')
me(@CurrentUser() user: any) {
return { success: true, user };
}
@Post('register') @Post('register')
@Public()
register(@Body() dto: RegisterDto, @Req() req: Request, @Res() res: Response) { register(@Body() dto: RegisterDto, @Req() req: Request, @Res() res: Response) {
return this.authService.register(dto, req, res); return this.authService.register(dto, req, res);
} }
@Post('login') @Post('login')
@Public()
login(@Body() dto: LoginDto, @Req() req: Request, @Res() res: Response) { login(@Body() dto: LoginDto, @Req() req: Request, @Res() res: Response) {
return this.authService.login(dto, req, res); return this.authService.login(dto, req, res);
} }
@Post('refresh') @Post('refresh')
@Public()
refresh(@Req() req: Request, @Res() res: Response) { refresh(@Req() req: Request, @Res() res: Response) {
return this.authService.refresh(req, res); return this.authService.refresh(req, res);
} }
@Post('logout') @Post('logout')
@Public()
logout(@Req() req: Request, @Res() res: Response) { logout(@Req() req: Request, @Res() res: Response) {
return this.authService.logout(req, res); return this.authService.logout(req, res);
} }
@Post('magic-link') @Post('magic-link')
@Public()
requestMagicLink( requestMagicLink(
@Body() dto: MagicLinkRequestDto, @Body() dto: MagicLinkRequestDto,
@Req() req: Request, @Req() req: Request,
@@ -53,6 +65,7 @@ export class AuthController {
} }
@Get('magic-link/verify') @Get('magic-link/verify')
@Public()
verifyMagicLink( verifyMagicLink(
@Query('token') token: string, @Query('token') token: string,
@Req() req: Request, @Req() req: Request,
@@ -62,6 +75,7 @@ export class AuthController {
} }
@Post('password-reset/request') @Post('password-reset/request')
@Public()
requestPasswordReset( requestPasswordReset(
@Body() dto: PasswordResetRequestDto, @Body() dto: PasswordResetRequestDto,
@Req() req: Request, @Req() req: Request,
@@ -71,6 +85,7 @@ export class AuthController {
} }
@Post('password-reset/confirm') @Post('password-reset/confirm')
@Public()
confirmPasswordReset( confirmPasswordReset(
@Body() dto: PasswordResetConfirmDto, @Body() dto: PasswordResetConfirmDto,
@Req() req: Request, @Req() req: Request,
@@ -80,12 +95,14 @@ export class AuthController {
} }
@Get('google') @Get('google')
@Public()
@UseGuards(AuthGuard('google')) @UseGuards(AuthGuard('google'))
googleAuth() { googleAuth() {
// Passport redirects to Google // Passport redirects to Google
} }
@Get('google/callback') @Get('google/callback')
@Public()
@UseGuards(AuthGuard('google')) @UseGuards(AuthGuard('google'))
googleCallback(@Req() req: Request, @Res() res: Response) { googleCallback(@Req() req: Request, @Res() res: Response) {
return this.authService.handleGoogleCallback((req as any).user, req, res); return this.authService.handleGoogleCallback((req as any).user, req, res);

View File

@@ -6,7 +6,7 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { IsNull, LessThan, Repository } from 'typeorm'; import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt'; import * as bcrypt from 'bcrypt';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import { User, UserRole } from '../users/entities/user.entity'; import { User, UserRole } from '../users/entities/user.entity';
@@ -64,14 +64,21 @@ export class AuthService {
private cookieOptions(res: any, accessToken: string, refreshToken: string) { private cookieOptions(res: any, accessToken: string, refreshToken: string) {
const secure = this.configService.get<string>('COOKIE_SECURE') === 'true'; const secure = this.configService.get<string>('COOKIE_SECURE') === 'true';
const domain = this.configService.get<string>('COOKIE_DOMAIN') || undefined; const domain = this.configService.get<string>('COOKIE_DOMAIN') || undefined;
const opts = { httpOnly: true, sameSite: 'lax' as const, secure, domain }; // SameSite=none required for cross-subdomain requests (frontend ↔ backend on different subdomains)
// SameSite=none requires Secure=true
const sameSite = secure ? ('none' as const) : ('lax' as const);
const opts = { httpOnly: true, sameSite, secure, domain };
res.cookie('accessToken', accessToken, { ...opts, maxAge: 15 * 60 * 1000 }); res.cookie('accessToken', accessToken, { ...opts, maxAge: 15 * 60 * 1000 });
res.cookie('refreshToken', refreshToken, { ...opts, maxAge: 7 * 24 * 60 * 60 * 1000 }); res.cookie('refreshToken', refreshToken, { ...opts, maxAge: 7 * 24 * 60 * 60 * 1000 });
} }
private clearCookies(res: any) { private clearCookies(res: any) {
res.clearCookie('accessToken'); const secure = this.configService.get<string>('COOKIE_SECURE') === 'true';
res.clearCookie('refreshToken'); const domain = this.configService.get<string>('COOKIE_DOMAIN') || undefined;
const sameSite = secure ? ('none' as const) : ('lax' as const);
const opts = { httpOnly: true, sameSite, secure, domain };
res.clearCookie('accessToken', opts);
res.clearCookie('refreshToken', opts);
} }
private safeUser(user: User) { private safeUser(user: User) {
@@ -79,6 +86,10 @@ export class AuthService {
return safe; return safe;
} }
private get frontendUrl(): string {
return this.configService.get<string>('FRONTEND_URL') || 'http://localhost:3000';
}
// ─── Register ──────────────────────────────────────────────────────────────── // ─── Register ────────────────────────────────────────────────────────────────
async register(dto: RegisterDto, req: any, res: any) { async register(dto: RegisterDto, req: any, res: any) {
@@ -99,11 +110,6 @@ export class AuthService {
await this.storeRefreshToken(user.id, rawRefresh, req); await this.storeRefreshToken(user.id, rawRefresh, req);
this.cookieOptions(res, accessToken, refreshToken); this.cookieOptions(res, accessToken, refreshToken);
const isHtmx = req.headers['hx-request'] === 'true';
if (isHtmx) {
res.set('HX-Redirect', '/dashboard');
return res.render('partials/flash', { type: 'success', message: 'Welcome! Account created.' });
}
return res.json({ success: true, accessToken, refreshToken, user: this.safeUser(user) }); return res.json({ success: true, accessToken, refreshToken, user: this.safeUser(user) });
} }
@@ -123,11 +129,6 @@ export class AuthService {
await this.storeRefreshToken(user.id, rawRefresh, req); await this.storeRefreshToken(user.id, rawRefresh, req);
this.cookieOptions(res, accessToken, refreshToken); this.cookieOptions(res, accessToken, refreshToken);
const isHtmx = req.headers['hx-request'] === 'true';
if (isHtmx) {
res.set('HX-Redirect', '/dashboard');
return res.render('partials/flash', { type: 'success', message: `Welcome back, ${user.name || user.email}!` });
}
return res.json({ success: true, accessToken, refreshToken, user: this.safeUser(user) }); return res.json({ success: true, accessToken, refreshToken, user: this.safeUser(user) });
} }
@@ -185,18 +186,13 @@ export class AuthService {
await this.refreshTokenRepo.update({ tokenHash }, { revokedAt: new Date() }); await this.refreshTokenRepo.update({ tokenHash }, { revokedAt: new Date() });
} }
this.clearCookies(res); this.clearCookies(res);
const isHtmx = req.headers['hx-request'] === 'true';
if (isHtmx) {
res.set('HX-Redirect', '/');
return res.render('partials/flash', { type: 'success', message: 'Logged out successfully' });
}
return res.json({ success: true }); return res.json({ success: true });
} }
// ─── Magic Link ─────────────────────────────────────────────────────────────── // ─── Magic Link ───────────────────────────────────────────────────────────────
async requestMagicLink(email: string, req: any, res: any) { async requestMagicLink(email: string, req: any, res: any) {
const appUrl = this.configService.get<string>('APP_URL') || 'http://localhost:3000'; const appUrl = this.configService.get<string>('APP_URL') || 'http://localhost:3001';
const ttl = this.configService.get<number>('MAGIC_LINK_TTL_MINUTES') || 20; const ttl = this.configService.get<number>('MAGIC_LINK_TTL_MINUTES') || 20;
const user = await this.userRepo.findOne({ where: { email } }); const user = await this.userRepo.findOne({ where: { email } });
@@ -214,6 +210,7 @@ export class AuthService {
}), }),
); );
// Link points to backend verify endpoint which then redirects to frontend
const link = `${appUrl}/auth/magic-link/verify?token=${rawToken}`; const link = `${appUrl}/auth/magic-link/verify?token=${rawToken}`;
await sendMail({ await sendMail({
@@ -222,10 +219,6 @@ export class AuthService {
html: `<p>Click <a href="${link}">here</a> to sign in. Link expires in ${ttl} minutes.</p><p>${link}</p>`, html: `<p>Click <a href="${link}">here</a> to sign in. Link expires in ${ttl} minutes.</p><p>${link}</p>`,
}); });
const isHtmx = req.headers['hx-request'] === 'true';
if (isHtmx) {
return res.render('partials/flash', { type: 'success', message: 'Magic link sent! Check your email.' });
}
return res.json({ success: true, message: 'Magic link sent' }); return res.json({ success: true, message: 'Magic link sent' });
} }
@@ -240,7 +233,6 @@ export class AuthService {
record.consumedAt = new Date(); record.consumedAt = new Date();
await this.magicLinkRepo.save(record); await this.magicLinkRepo.save(record);
// Find or create user
let user = await this.userRepo.findOne({ where: { email: record.email } }); let user = await this.userRepo.findOne({ where: { email: record.email } });
if (!user) { if (!user) {
user = this.userRepo.create({ user = this.userRepo.create({
@@ -256,20 +248,19 @@ export class AuthService {
await this.storeRefreshToken(user.id, rawRefresh, req); await this.storeRefreshToken(user.id, rawRefresh, req);
this.cookieOptions(res, accessToken, refreshToken); this.cookieOptions(res, accessToken, refreshToken);
return res.redirect('/dashboard'); // Redirect to Next.js frontend dashboard
return res.redirect(`${this.frontendUrl}/dashboard`);
} }
// ─── Password Reset ─────────────────────────────────────────────────────────── // ─── Password Reset ───────────────────────────────────────────────────────────
async requestPasswordReset(email: string, req: any, res: any) { async requestPasswordReset(email: string, req: any, res: any) {
const appUrl = this.configService.get<string>('APP_URL') || 'http://localhost:3000'; const frontendUrl = this.frontendUrl;
const ttl = this.configService.get<number>('PASSWORD_RESET_TTL_MINUTES') || 30; const ttl = this.configService.get<number>('PASSWORD_RESET_TTL_MINUTES') || 30;
const user = await this.userRepo.findOne({ where: { email } }); const user = await this.userRepo.findOne({ where: { email } });
if (!user) { if (!user) {
// Return success to avoid enumeration // Return success to avoid enumeration
const isHtmx = req.headers['hx-request'] === 'true';
if (isHtmx) return res.render('partials/flash', { type: 'success', message: 'If that email exists, a reset link was sent.' });
return res.json({ success: true }); return res.json({ success: true });
} }
@@ -281,15 +272,14 @@ export class AuthService {
this.pwdResetRepo.create({ id: uuidv4(), userId: user.id, tokenHash, expiresAt }), this.pwdResetRepo.create({ id: uuidv4(), userId: user.id, tokenHash, expiresAt }),
); );
const link = `${appUrl}/auth?tab=reset&token=${rawToken}`; // Link points to Next.js frontend auth page with reset token
const link = `${frontendUrl}/auth?tab=reset&token=${rawToken}`;
await sendMail({ await sendMail({
to: email, to: email,
subject: 'Password Reset', subject: 'Password Reset',
html: `<p>Click <a href="${link}">here</a> to reset your password. Expires in ${ttl} minutes.</p>`, html: `<p>Click <a href="${link}">here</a> to reset your password. Expires in ${ttl} minutes.</p>`,
}); });
const isHtmx = req.headers['hx-request'] === 'true';
if (isHtmx) return res.render('partials/flash', { type: 'success', message: 'Reset link sent!' });
return res.json({ success: true }); return res.json({ success: true });
} }
@@ -310,8 +300,6 @@ export class AuthService {
record.consumedAt = new Date(); record.consumedAt = new Date();
await this.pwdResetRepo.save(record); await this.pwdResetRepo.save(record);
const isHtmx = req.headers['hx-request'] === 'true';
if (isHtmx) return res.render('partials/flash', { type: 'success', message: 'Password updated! You can now log in.' });
return res.json({ success: true }); return res.json({ success: true });
} }
@@ -329,7 +317,6 @@ export class AuthService {
if (oauthAccount) { if (oauthAccount) {
user = oauthAccount.user; user = oauthAccount.user;
} else { } else {
// Find or create user by email
user = await this.userRepo.findOne({ where: { email } }); user = await this.userRepo.findOne({ where: { email } });
if (!user) { if (!user) {
user = this.userRepo.create({ user = this.userRepo.create({
@@ -355,7 +342,8 @@ export class AuthService {
await this.storeRefreshToken(user.id, rawRefresh, req); await this.storeRefreshToken(user.id, rawRefresh, req);
this.cookieOptions(res, accessToken, refreshToken); this.cookieOptions(res, accessToken, refreshToken);
return res.redirect('/dashboard'); // Redirect to Next.js frontend dashboard after Google OAuth
return res.redirect(`${this.frontendUrl}/dashboard`);
} }
// ─── Private ────────────────────────────────────────────────────────────────── // ─── Private ──────────────────────────────────────────────────────────────────

View File

@@ -7,10 +7,7 @@ import {
Patch, Patch,
Post, Post,
Query, Query,
Req,
Res,
} from '@nestjs/common'; } from '@nestjs/common';
import { Request, Response } from 'express';
import { BlogPostsService } from './blog-posts.service'; import { BlogPostsService } from './blog-posts.service';
import { CreatePostDto } from './dto/create-post.dto'; import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto'; import { UpdatePostDto } from './dto/update-post.dto';
@@ -52,51 +49,6 @@ export class BlogPostsController {
return { success: true }; return { success: true };
} }
// ─── HTMX partials (public) ──────────────────────────────────────────────────
/**
* Renders the post-grid partial.
* Templates expect:
* result → { items, page, pageSize, total, totalPages }
* query → the raw query params (q, tags, category, sort, page, pageSize)
*/
@Get('partials/grid')
@Public()
async gridPartial(@Query() query: ListPostsQueryDto, @Res() res: Response) {
const result = await this.blogPostsService.findPublished(query);
return res.render('partials/post-grid', {
result,
query: {
q: query.q || '',
tags: query.tags || '',
category: query.category || '',
sort: query.sort || 'newest',
page: result.page,
pageSize: result.pageSize,
},
});
}
// ─── HTMX partials (authenticated) ───────────────────────────────────────────
/**
* Renders the dashboard-post-table partial.
* Template expects: posts[], currentUser
*/
@Get('partials/table')
async tablePartial(
@Query() query: ListPostsQueryDto,
@CurrentUser() currentUser: any,
@Req() req: Request,
@Res() res: Response,
) {
const data = await this.blogPostsService.findAll(query, currentUser);
return res.render('partials/dashboard-post-table', {
posts: data.posts,
currentUser,
});
}
// ─── Authenticated CRUD ─────────────────────────────────────────────────────── // ─── Authenticated CRUD ───────────────────────────────────────────────────────
@Get() @Get()
@@ -106,40 +58,26 @@ export class BlogPostsController {
@Post() @Post()
@Roles(UserRole.ADMIN, UserRole.MANAGER) @Roles(UserRole.ADMIN, UserRole.MANAGER)
async create(@Body() dto: CreatePostDto, @CurrentUser() user: any, @Res() res: Response, @Req() req: Request) { async create(@Body() dto: CreatePostDto, @CurrentUser() user: any) {
const post = await this.blogPostsService.create(dto, user); const post = await this.blogPostsService.create(dto, user);
const isHtmx = req.headers['hx-request'] === 'true'; return { success: true, post };
if (isHtmx) {
return res.render('partials/flash', { type: 'success', message: `Post "${post.title}" created!` });
}
return res.json({ success: true, post });
} }
@Patch(':id') @Patch(':id')
@Roles(UserRole.ADMIN) @Roles(UserRole.ADMIN, UserRole.MANAGER)
async update( async update(
@Param('id') id: string, @Param('id') id: string,
@Body() dto: UpdatePostDto, @Body() dto: UpdatePostDto,
@CurrentUser() user: any, @CurrentUser() user: any,
@Res() res: Response,
@Req() req: Request,
) { ) {
const post = await this.blogPostsService.update(id, dto, user); const post = await this.blogPostsService.update(id, dto, user);
const isHtmx = req.headers['hx-request'] === 'true'; return { success: true, post };
if (isHtmx) {
return res.render('partials/flash', { type: 'success', message: `Post "${post.title}" updated!` });
}
return res.json({ success: true, post });
} }
@Delete(':id') @Delete(':id')
@Roles(UserRole.ADMIN) @Roles(UserRole.ADMIN)
async remove(@Param('id') id: string, @Res() res: Response, @Req() req: Request) { async remove(@Param('id') id: string) {
await this.blogPostsService.remove(id); await this.blogPostsService.remove(id);
const isHtmx = req.headers['hx-request'] === 'true'; return { success: true };
if (isHtmx) {
return res.render('partials/flash', { type: 'success', message: 'Post deleted.' });
}
return res.json({ success: true });
} }
} }

View File

@@ -6,7 +6,7 @@ import {
HttpStatus, HttpStatus,
Logger, Logger,
} from '@nestjs/common'; } from '@nestjs/common';
import { Request, Response } from 'express'; import { Response } from 'express';
@Catch() @Catch()
export class AllExceptionsFilter implements ExceptionFilter { export class AllExceptionsFilter implements ExceptionFilter {
@@ -14,7 +14,6 @@ export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) { catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp(); const ctx = host.switchToHttp();
const req = ctx.getRequest<Request>();
const res = ctx.getResponse<Response>(); const res = ctx.getResponse<Response>();
let status = HttpStatus.INTERNAL_SERVER_ERROR; let status = HttpStatus.INTERNAL_SERVER_ERROR;
@@ -37,15 +36,9 @@ export class AllExceptionsFilter implements ExceptionFilter {
this.logger.error(exception.message, exception.stack); this.logger.error(exception.message, exception.stack);
} }
const isHtmx = req.headers['hx-request'] === 'true'; res.status(status).json({
success: false,
if (isHtmx) { error: { code: status, message },
res.status(status).render('partials/flash', { type: 'error', message }); });
} else {
res.status(status).json({
success: false,
error: { code: status, message },
});
}
} }
} }

View File

@@ -26,8 +26,6 @@ export class JwtAuthGuard {
const token = this.extractToken(request); const token = this.extractToken(request);
if (!token) { if (!token) {
const isHtmx = request.headers['hx-request'] === 'true';
if (isHtmx) throw new UnauthorizedException('Please log in to continue');
throw new UnauthorizedException('Missing authentication token'); throw new UnauthorizedException('Missing authentication token');
} }

View File

@@ -25,10 +25,15 @@ export class CsrfMiddleware implements NestMiddleware {
} }
// Set as non-httpOnly cookie so JS can read it // Set as non-httpOnly cookie so JS can read it
// SameSite=none required for cross-subdomain (frontend ↔ backend on different subdomains)
const secure = process.env.COOKIE_SECURE === 'true';
const domain = process.env.COOKIE_DOMAIN || undefined;
const sameSite = secure ? ('none' as const) : ('lax' as const);
res.cookie('csrfToken', csrfToken, { res.cookie('csrfToken', csrfToken, {
httpOnly: false, httpOnly: false,
sameSite: 'lax', sameSite,
secure: process.env.COOKIE_SECURE === 'true', secure,
domain,
}); });
(req as any).csrfToken = csrfToken; (req as any).csrfToken = csrfToken;

View File

@@ -4,7 +4,6 @@ import { ValidationPipe } from '@nestjs/common';
import { join } from 'path'; import { join } from 'path';
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const cookieParser = require('cookie-parser'); const cookieParser = require('cookie-parser');
import * as nunjucks from 'nunjucks';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
async function bootstrap() { async function bootstrap() {
@@ -21,36 +20,6 @@ async function bootstrap() {
// ─── Static assets ────────────────────────────────────────────────────────── // ─── Static assets ──────────────────────────────────────────────────────────
app.useStaticAssets(join(process.cwd(), 'public')); app.useStaticAssets(join(process.cwd(), 'public'));
// ─── Nunjucks view engine ────────────────────────────────────────────────────
// process.cwd() is always the project root, regardless of __dirname in dist/
const viewsDir = join(process.cwd(), 'src', 'views');
app.setBaseViewsDir(viewsDir);
app.setViewEngine('njk');
const nunjucksEnv = nunjucks.configure(viewsDir, {
autoescape: true,
throwOnUndefined: false,
watch: process.env.NODE_ENV === 'development',
express: app.getHttpAdapter().getInstance(),
});
nunjucksEnv.addFilter('urlencode', (s: string) => encodeURIComponent(s ?? ''));
nunjucksEnv.addFilter('truncate', (s: string, len: number) => {
if (!s) return '';
return s.length > len ? s.substring(0, len) + '...' : s;
});
nunjucksEnv.addFilter('date', (d: Date | string, fmt?: string) => {
if (!d) return '';
const date = new Date(d);
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
});
nunjucksEnv.addGlobal('appName', 'Duc Binh Blog');
nunjucksEnv.addGlobal('year', new Date().getFullYear());
// ─── Middleware ────────────────────────────────────────────────────────────── // ─── Middleware ──────────────────────────────────────────────────────────────
app.use(cookieParser()); app.use(cookieParser());

View File

@@ -1,149 +0,0 @@
import { Controller, Get, Param, Query, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { BlogPostsService } from '../blog-posts/blog-posts.service';
import { UsersService } from '../users/users.service';
import { Public } from '../common/decorators/public.decorator';
import { marked } from 'marked';
@Controller()
export class PagesController {
constructor(
private readonly blogPostsService: BlogPostsService,
private readonly usersService: UsersService,
) {}
@Get('health')
@Public()
health() {
return { status: 'ok', timestamp: new Date().toISOString() };
}
// ─── Home page ─────────────────────────────────────────────────────────────
@Get()
@Public()
async home(@Req() req: Request, @Res() res: Response, @Query() rawQuery: Record<string, string>) {
const currentUser = (req as any).user || null;
// Determine query params with defaults
const query = {
q: rawQuery.q || '',
tags: rawQuery.tags || '',
category: rawQuery.category || '',
sort: rawQuery.sort || 'newest',
page: rawQuery.page || '1',
pageSize: rawQuery.pageSize || '9',
};
const [featured, postsResult, topTags, topCategories, popularPosts] = await Promise.all([
this.blogPostsService.findFeatured(3),
this.blogPostsService.findPublished(query),
this.blogPostsService.getTagCloud(),
this.blogPostsService.getCategoryCloud(),
this.blogPostsService.findPopular(5),
]);
return res.render('pages/home', {
title: 'Duc Binh Blog',
currentUser,
featured,
// home.njk does {% set result = posts %} then includes post-grid.njk
// so `posts` must be the result shape { items, page, pageSize, total, totalPages }
posts: postsResult,
query,
topTags: topTags.slice(0, 20),
topCategories: topCategories.slice(0, 10),
popularPosts,
});
}
// ─── Blog detail ───────────────────────────────────────────────────────────
@Get('blog/:slug')
@Public()
async blogDetail(
@Param('slug') slug: string,
@Req() req: Request,
@Res() res: Response,
) {
const post = await this.blogPostsService.findBySlug(slug);
// Increment views
await this.blogPostsService.incrementViews(slug);
const contentHtml =
post.contentFormat === 'markdown'
? await marked(post.content)
: post.content;
const currentUser = (req as any).user || null;
const [relatedPosts, popularPosts, topTags] = await Promise.all([
this.blogPostsService.findRelated(post, 4),
this.blogPostsService.findPopular(5),
this.blogPostsService.getTagCloud(),
]);
return res.render('pages/blog-detail', {
title: post.title,
currentUser,
post,
contentHtml,
relatedPosts,
popularPosts,
topTags: topTags.slice(0, 20),
});
}
// ─── Auth page ─────────────────────────────────────────────────────────────
@Get('auth')
@Public()
async authPage(
@Req() req: Request,
@Res() res: Response,
@Query('token') resetToken?: string,
) {
// If already logged in, redirect to dashboard
if ((req as any).user) {
return res.redirect('/dashboard');
}
return res.render('pages/auth', {
title: 'Sign In — Duc Binh Blog',
currentUser: null,
resetToken: resetToken || '',
});
}
// ─── Dashboard ─────────────────────────────────────────────────────────────
@Get('dashboard')
async dashboard(@Req() req: Request, @Res() res: Response) {
const currentUser = (req as any).user;
const [postsResult, usersResult] = await Promise.all([
this.blogPostsService.findAll({ page: '1', pageSize: '10' }, currentUser),
currentUser.role === 'ADMIN'
? this.usersService.findAll(1, 10)
: Promise.resolve(null),
]);
return res.render('pages/dashboard', {
title: 'Dashboard — Duc Binh Blog',
currentUser,
// dashboard-post-table.njk uses `posts` directly (flat array)
posts: postsResult.posts,
postsPagination: {
page: postsResult.page,
totalPages: postsResult.totalPages,
total: postsResult.total,
},
users: usersResult?.users || null,
usersPagination: usersResult
? {
page: usersResult.page,
totalPages: usersResult.totalPages,
total: usersResult.total,
}
: null,
});
}
}

View File

@@ -1,10 +0,0 @@
import { Module } from '@nestjs/common';
import { BlogPostsModule } from '../blog-posts/blog-posts.module';
import { UsersModule } from '../users/users.module';
import { PagesController } from './pages.controller';
@Module({
imports: [BlogPostsModule, UsersModule],
controllers: [PagesController],
})
export class PagesModule {}

View File

@@ -1,15 +1,13 @@
import { import {
Body, Body,
Controller, Controller,
Delete,
Get, Get,
Param, Param,
Patch, Patch,
Post, Post,
Query, Query,
Req,
Res,
} from '@nestjs/common'; } from '@nestjs/common';
import { Request, Response } from 'express';
import { UsersService } from './users.service'; import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto'; import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserNameDto } from './dto/update-user-name.dto'; import { UpdateUserNameDto } from './dto/update-user-name.dto';
@@ -32,60 +30,35 @@ export class UsersController {
} }
@Post() @Post()
async create(@Body() dto: CreateUserDto, @Req() req: Request, @Res() res: Response) { async create(@Body() dto: CreateUserDto) {
const user = await this.usersService.create(dto); const user = await this.usersService.create(dto);
const { passwordHash, ...safe } = user as any; const { passwordHash, ...safe } = user as any;
const isHtmx = req.headers['hx-request'] === 'true'; return { success: true, user: safe };
if (isHtmx) {
return res.render('partials/flash', { type: 'success', message: `User "${safe.email}" created!` });
}
return res.json({ success: true, user: safe });
} }
@Patch(':id') @Patch(':id')
async updateName( async updateName(
@Param('id') id: string, @Param('id') id: string,
@Body() dto: UpdateUserNameDto, @Body() dto: UpdateUserNameDto,
@Req() req: Request,
@Res() res: Response,
) { ) {
const user = await this.usersService.updateName(id, dto); const user = await this.usersService.updateName(id, dto);
const { passwordHash, ...safe } = user as any; const { passwordHash, ...safe } = user as any;
const isHtmx = req.headers['hx-request'] === 'true'; return { success: true, user: safe };
if (isHtmx) {
return res.render('partials/flash', { type: 'success', message: `User "${safe.email}" renamed.` });
}
return res.json({ success: true, user: safe });
} }
@Patch(':id/role') @Patch(':id/role')
async updateRole( async updateRole(
@Param('id') id: string, @Param('id') id: string,
@Body() dto: UpdateUserRoleDto, @Body() dto: UpdateUserRoleDto,
@Req() req: Request,
@Res() res: Response,
) { ) {
const user = await this.usersService.updateRole(id, dto); const user = await this.usersService.updateRole(id, dto);
const { passwordHash, ...safe } = user as any; const { passwordHash, ...safe } = user as any;
const isHtmx = req.headers['hx-request'] === 'true'; return { success: true, user: safe };
if (isHtmx) {
return res.render('partials/flash', { type: 'success', message: `Role updated to ${safe.role}.` });
}
return res.json({ success: true, user: safe });
} }
@Get('partials/table') @Delete(':id')
async tablePartial( async remove(@Param('id') id: string) {
@Query('page') page = '1', await this.usersService.remove(id);
@Query('pageSize') pageSize = '20', return { success: true };
@Query('q') q: string,
@Res() res: Response,
) {
const data = await this.usersService.findAll(
parseInt(page, 10),
parseInt(pageSize, 10),
q,
);
return res.render('partials/dashboard-user-table', { users: data.users });
} }
} }

View File

@@ -76,6 +76,11 @@ export class UsersService {
return this.findById(id); return this.findById(id);
} }
async remove(id: string): Promise<void> {
await this.findById(id); // throws NotFoundException if not found
await this.userRepo.delete(id);
}
async setPassword(id: string, password: string): Promise<void> { async setPassword(id: string, password: string): Promise<void> {
const hash = await bcrypt.hash(password, 12); const hash = await bcrypt.hash(password, 12);
await this.userRepo.update(id, { passwordHash: hash }); await this.userRepo.update(id, { passwordHash: hash });

View File

@@ -1,80 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ title or "Duc Binh Blog" }}</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;700&family=Source+Serif+4:wght@400;600;700&display=swap" rel="stylesheet" />
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
</head>
<body class="min-h-screen bg-gradient-to-b from-amber-50 via-stone-50 to-emerald-50 font-[Space_Grotesk] text-zinc-900 antialiased">
<div class="mx-auto w-full max-w-7xl px-4 pb-10 pt-4 sm:px-6 lg:px-8">
<header class="sticky top-3 z-20 mb-4 rounded-2xl border border-zinc-200/80 bg-white/90 shadow-sm backdrop-blur">
<div class="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
<a class="inline-flex items-center gap-2 text-zinc-900 no-underline transition hover:text-teal-700" href="/">
<span class="inline-flex h-8 w-8 items-center justify-center rounded-full bg-teal-600 text-xs font-bold text-white">DB</span>
<span class="text-base font-semibold">Duc Binh Blog</span>
</a>
<nav class="flex flex-wrap items-center gap-2 text-sm">
<a class="rounded-full border border-zinc-200 bg-white px-3 py-1.5 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="/">Home</a>
{% if currentUser %}
<a class="rounded-full border border-zinc-200 bg-white px-3 py-1.5 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="/dashboard">Dashboard</a>
<form hx-post="/auth/logout" hx-target="#flash" hx-swap="innerHTML" class="m-0">
<button class="rounded-full border border-rose-200 bg-white px-3 py-1.5 text-sm font-medium text-rose-700 transition hover:bg-rose-50" type="submit">Logout</button>
</form>
{% else %}
<a class="rounded-full border border-zinc-200 bg-white px-3 py-1.5 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="/auth">Auth</a>
{% endif %}
</nav>
</div>
</header>
<main class="space-y-4">
{% block body %}{% endblock %}
</main>
</div>
<div id="flash" class="pointer-events-none fixed right-4 top-4 z-50 flex w-[min(26rem,calc(100%-2rem))] flex-col gap-2">
{% include "partials/flash.njk" %}
</div>
<script>
function readCookie(name) {
const cookie = document.cookie
.split(";")
.map((entry) => entry.trim())
.find((entry) => entry.startsWith(name + "="));
return cookie ? decodeURIComponent(cookie.split("=").slice(1).join("=")) : "";
}
document.body.addEventListener("htmx:configRequest", function(event) {
const csrfToken = readCookie("csrfToken");
if (csrfToken) {
event.detail.headers["x-csrf-token"] = csrfToken;
}
});
window.refreshDashboardPosts = function() {
if (document.querySelector("#dashboard-posts-table")) {
htmx.ajax("GET", "/blog-posts/partials/table", {
target: "#dashboard-posts-table",
swap: "innerHTML"
});
}
};
window.refreshDashboardUsers = function() {
if (document.querySelector("#dashboard-users-table")) {
htmx.ajax("GET", "/users/partials/table?page=1&pageSize=50", {
target: "#dashboard-users-table",
swap: "innerHTML"
});
}
};
</script>
</body>
</html>

View File

@@ -1,23 +0,0 @@
{% extends "layouts/base.njk" %}
{% block body %}
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm sm:p-5">
<div class="grid items-start gap-4 lg:grid-cols-[15rem_minmax(0,1fr)]">
<aside class="rounded-xl border border-zinc-200 bg-amber-50 p-4">
<h3 class="font-[Source_Serif_4] text-xl font-semibold text-zinc-900">Control Panel</h3>
<p class="mt-1 text-sm text-zinc-600">Role: <span class="font-semibold text-zinc-800">{{ currentUser.role }}</span></p>
<nav class="mt-4 grid gap-2 text-sm">
<a class="rounded-lg border border-zinc-200 bg-white px-3 py-2 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="#profile">Profile</a>
<a class="rounded-lg border border-zinc-200 bg-white px-3 py-2 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="#posts">Posts</a>
{% if currentUser.role == "ADMIN" %}
<a class="rounded-lg border border-zinc-200 bg-white px-3 py-2 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="#users">Users</a>
{% endif %}
</nav>
</aside>
<section class="space-y-4">
{% block dashboardBody %}{% endblock %}
</section>
</div>
</section>
{% endblock %}

View File

@@ -1,200 +0,0 @@
{% extends "layouts/base.njk" %}
{% block body %}
<div class="mx-auto w-full max-w-[42rem] space-y-5">
<section id="auth-tabs" data-initial-tab="{% if resetToken %}reset{% else %}signin{% endif %}" class="rounded-[2rem] border border-zinc-200 bg-zinc-50 p-6 shadow-sm sm:p-8">
<p class="text-center text-xs font-medium tracking-[0.5em] text-slate-500">SIGN IN TO CONTINUE</p>
<div class="mt-6 grid grid-cols-3 gap-1 rounded-full bg-zinc-200 p-1.5">
<button type="button" data-tab-button data-tab="signin" class="rounded-full px-3 py-3 text-center text-sm font-semibold text-slate-500 transition">Sign In</button>
<button type="button" data-tab-button data-tab="signup" class="rounded-full px-3 py-3 text-center text-sm font-semibold text-slate-500 transition">Sign Up</button>
<button type="button" data-tab-button data-tab="reset" class="rounded-full px-3 py-3 text-center text-sm font-semibold text-slate-500 transition">Reset Password</button>
</div>
<section data-tab-panel="signin" class="mt-7 space-y-4">
<form hx-post="/auth/login" hx-target="#flash" hx-swap="innerHTML" class="space-y-4">
<div>
<label for="login-email" class="mb-2 block text-sm font-semibold text-slate-700">Email address</label>
<input id="login-email" name="email" type="email" placeholder="name@email.com" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
</div>
<div>
<label for="login-password" class="mb-2 block text-sm font-semibold text-slate-700">Password</label>
<div class="flex gap-2">
<input id="login-password" name="password" type="password" placeholder="Enter your password" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
<button type="button" data-toggle-password data-target="login-password" class="rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-sm font-semibold text-slate-600 transition hover:bg-white">Show</button>
</div>
</div>
<button type="submit" class="w-full rounded-2xl bg-blue-600 px-4 py-3 text-lg font-semibold text-white transition hover:bg-blue-700">Sign In</button>
</form>
<form id="magic-link-form" hx-post="/auth/magic-link" hx-target="#flash" hx-swap="innerHTML">
<input id="magic-link-email" type="hidden" name="email" value="" />
<button type="submit" class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-lg font-semibold text-zinc-500 transition hover:bg-white hover:text-zinc-700">Send magic link</button>
</form>
<a href="/auth/google" class="block w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-center text-lg font-semibold text-slate-700 no-underline transition hover:bg-white">Continue with Google</a>
</section>
<section data-tab-panel="signup" class="mt-7 hidden space-y-4">
<form hx-post="/auth/register" hx-target="#flash" hx-swap="innerHTML" class="space-y-4">
<div>
<label for="signup-name" class="mb-2 block text-sm font-semibold text-slate-700">Name</label>
<input id="signup-name" name="name" placeholder="Your full name" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
</div>
<div>
<label for="signup-email" class="mb-2 block text-sm font-semibold text-slate-700">Email address</label>
<input id="signup-email" name="email" type="email" placeholder="name@email.com" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
</div>
<div>
<label for="signup-password" class="mb-2 block text-sm font-semibold text-slate-700">Password</label>
<div class="flex gap-2">
<input id="signup-password" name="password" type="password" placeholder="Create a password" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
<button type="button" data-toggle-password data-target="signup-password" class="rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-sm font-semibold text-slate-600 transition hover:bg-white">Show</button>
</div>
</div>
<button type="submit" class="w-full rounded-2xl bg-blue-600 px-4 py-3 text-lg font-semibold text-white transition hover:bg-blue-700">Create Account</button>
</form>
<p class="rounded-2xl border border-blue-100 bg-blue-50 px-4 py-3 text-sm text-blue-700">New sign-ups are assigned the default <strong>MEMBER</strong> role.</p>
</section>
<section data-tab-panel="reset" class="mt-7 hidden space-y-4">
<form hx-post="/auth/password-reset/request" hx-target="#flash" hx-swap="innerHTML" class="space-y-4">
<div>
<label for="reset-email" class="mb-2 block text-sm font-semibold text-slate-700">Email address</label>
<input id="reset-email" name="email" type="email" placeholder="name@email.com" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
</div>
<button type="submit" class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-lg font-semibold text-zinc-700 transition hover:bg-white">Request reset token</button>
</form>
<form hx-post="/auth/password-reset/confirm" hx-target="#flash" hx-swap="innerHTML" class="space-y-4 rounded-2xl border border-zinc-200 bg-white p-4">
<p class="text-sm font-semibold text-slate-700">Confirm reset</p>
<input name="token" placeholder="Reset token" value="{{ resetToken }}" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
<div class="flex gap-2">
<input id="reset-password" name="password" type="password" placeholder="New password" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
<button type="button" data-toggle-password data-target="reset-password" class="rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-sm font-semibold text-slate-600 transition hover:bg-white">Show</button>
</div>
<button type="submit" class="w-full rounded-2xl bg-blue-600 px-4 py-3 text-lg font-semibold text-white transition hover:bg-blue-700">Update password</button>
</form>
</section>
</section>
<section class="rounded-3xl border border-zinc-200 bg-zinc-50 p-6 shadow-sm">
<div class="rounded-2xl border border-zinc-200 bg-zinc-100 p-4">
<h2 class="text-2xl font-semibold text-slate-800">Default Admin Account</h2>
<p class="mt-2 text-lg text-slate-700">Email: <strong>admin@gmail.com</strong></p>
<p class="text-lg text-slate-700">Password: <strong>Whatever123$</strong></p>
<button type="button" data-try-login data-demo-email="admin@gmail.com" data-demo-password="Whatever123$" class="mt-3 rounded-xl border border-blue-200 bg-blue-50 px-4 py-2 text-sm font-semibold text-blue-700 transition hover:bg-blue-100">Use these credentials</button>
</div>
<ul class="mt-4 list-disc space-y-1 pl-5 text-zinc-700">
<li><strong>Sign in with the credentials above to access an <span class="font-bold text-red-600">ADMIN</span> account.</strong></li>
<li><strong>New sign-ups are assigned the default <span class="font-bold text-blue-600">MEMBER</span> role.</strong></li>
</ul>
<h3 class="mt-5 text-2xl font-bold text-zinc-800">Role Permissions Overview</h3>
<div class="mt-4 space-y-4 text-zinc-700">
<section>
<h4 class="text-xl font-bold text-blue-600">MEMBER</h4>
<ul class="list-disc space-y-1 pl-5">
<li>Can view the list of blog posts only.</li>
<li>No permission to create, edit, or delete posts.</li>
</ul>
</section>
<section>
<h4 class="text-xl font-bold text-amber-600">MANAGER</h4>
<ul class="list-disc space-y-1 pl-5">
<li>Can view all blog posts.</li>
<li>Can create new blog posts.</li>
<li>Newly created posts are always saved as Draft by default.</li>
<li>Cannot update or delete any post.</li>
</ul>
</section>
<section>
<h4 class="text-xl font-bold text-red-600">ADMIN</h4>
<ul class="list-disc space-y-1 pl-5">
<li>Full access to the system.</li>
<li>Can create, read, update, and delete any blog post.</li>
<li>Can manage all content without restrictions.</li>
</ul>
</section>
</div>
</section>
</div>
<script>
(function() {
const container = document.getElementById("auth-tabs");
if (!container) return;
const buttons = Array.from(container.querySelectorAll("[data-tab-button]"));
const panels = Array.from(container.querySelectorAll("[data-tab-panel]"));
const magicLinkForm = document.getElementById("magic-link-form");
const magicLinkEmail = document.getElementById("magic-link-email");
function setActiveTab(tabName) {
buttons.forEach((button) => {
const isActive = button.getAttribute("data-tab") === tabName;
button.classList.toggle("bg-white", isActive);
button.classList.toggle("text-zinc-800", isActive);
button.classList.toggle("shadow-sm", isActive);
button.classList.toggle("text-slate-500", !isActive);
});
panels.forEach((panel) => {
panel.classList.toggle("hidden", panel.getAttribute("data-tab-panel") !== tabName);
});
}
const initialTab = container.getAttribute("data-initial-tab") || "signin";
setActiveTab(initialTab);
container.addEventListener("click", function(event) {
const tabButton = event.target.closest("[data-tab-button]");
if (!tabButton) return;
setActiveTab(tabButton.getAttribute("data-tab") || "signin");
});
if (magicLinkForm && magicLinkEmail) {
magicLinkForm.addEventListener("submit", function() {
const emailInput = document.getElementById("login-email");
magicLinkEmail.value = emailInput ? emailInput.value.trim() : "";
});
}
document.addEventListener("click", function(event) {
const toggleButton = event.target.closest("[data-toggle-password]");
if (toggleButton) {
const targetId = toggleButton.getAttribute("data-target");
const input = targetId ? document.getElementById(targetId) : null;
if (input) {
const isPassword = input.getAttribute("type") === "password";
input.setAttribute("type", isPassword ? "text" : "password");
toggleButton.textContent = isPassword ? "Hide" : "Show";
}
return;
}
const demoButton = event.target.closest("[data-try-login]");
if (!demoButton) return;
const emailInput = document.getElementById("login-email");
const passwordInput = document.getElementById("login-password");
if (!emailInput || !passwordInput) return;
setActiveTab("signin");
emailInput.value = demoButton.getAttribute("data-demo-email") || "";
passwordInput.value = demoButton.getAttribute("data-demo-password") || "";
passwordInput.focus();
});
})();
</script>
{% endblock %}

View File

@@ -1,82 +0,0 @@
{% extends "layouts/base.njk" %}
{% block body %}
<article class="rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm">
<p class="text-sm font-medium uppercase tracking-wide text-zinc-500">{{ post.categories | join(", ") }}</p>
<h1 class="mt-2 font-[Source_Serif_4] text-4xl font-semibold leading-tight text-zinc-900">{{ post.title }}</h1>
<p class="mt-3 text-zinc-600">{{ post.excerpt }}</p>
{% if post.featuredImage %}
<img src="{{ post.featuredImage.url }}" alt="{{ post.featuredImage.alt }}" class="mt-4 w-full rounded-xl border border-zinc-200 object-cover" />
{% endif %}
<div class="mt-4 flex flex-wrap gap-2">
{% for tag in post.tags %}
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2.5 py-1 text-xs font-medium text-teal-700">#{{ tag }}</span>
{% endfor %}
</div>
<p class="mt-3 text-sm text-zinc-500">Views: {{ post.views }}</p>
<div class="mt-5 space-y-4 text-zinc-700 [&_a]:text-teal-700 [&_a]:underline [&_blockquote]:border-l-4 [&_blockquote]:border-zinc-300 [&_blockquote]:pl-4 [&_h1]:font-[Source_Serif_4] [&_h1]:text-3xl [&_h1]:font-semibold [&_h2]:font-[Source_Serif_4] [&_h2]:text-2xl [&_h2]:font-semibold [&_h3]:font-[Source_Serif_4] [&_h3]:text-xl [&_h3]:font-semibold [&_li]:ml-5 [&_li]:list-disc [&_p]:leading-7">
{{ contentHtml | safe }}
</div>
<div hx-post="/blog-posts/public/{{ post.slug }}/view" hx-trigger="load" hx-swap="none"></div>
</article>
<section class="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
<div class="rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm">
<div class="mb-4 flex flex-wrap items-center justify-between gap-2">
<h2 class="font-[Source_Serif_4] text-3xl font-semibold text-zinc-900">More from the blog</h2>
<a class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white no-underline transition hover:bg-teal-700" href="/">Back to Home</a>
</div>
{% if relatedPosts and relatedPosts.length > 0 %}
<div class="grid gap-3 sm:grid-cols-2">
{% for related in relatedPosts %}
<article class="rounded-xl border border-zinc-200 bg-zinc-50/60 p-4">
<div class="mb-2 flex flex-wrap gap-1.5">
{% for cat in related.categories %}
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-teal-700">{{ cat }}</span>
{% endfor %}
</div>
<h3 class="font-[Source_Serif_4] text-xl font-semibold leading-tight text-zinc-900">
<a href="/blog/{{ related.slug }}" class="transition hover:text-teal-700">{{ related.title }}</a>
</h3>
<p class="mt-2 text-sm text-zinc-600">{{ related.excerpt }}</p>
<p class="mt-2 text-xs text-zinc-500">{{ related.views }} views</p>
</article>
{% endfor %}
</div>
{% else %}
<div class="rounded-xl border border-zinc-200 bg-zinc-50 p-4">
<p class="text-sm text-zinc-600">No related posts yet. Try exploring tags and categories from the home page.</p>
</div>
{% endif %}
</div>
<aside class="grid gap-4">
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Popular Posts</h3>
<div class="mt-3 grid gap-2">
{% for item in popularPosts %}
<a href="/blog/{{ item.slug }}" class="flex items-center justify-between rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700">
<span>{{ item.title }}</span>
<strong class="text-zinc-500">{{ item.views }}</strong>
</a>
{% endfor %}
</div>
</section>
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Tags</h3>
<div class="mt-3 flex flex-wrap gap-2">
{% for tag in topTags %}
<a class="rounded-full border border-teal-200 bg-teal-50 px-2.5 py-1 text-xs font-medium text-teal-700 no-underline transition hover:border-teal-400 hover:bg-teal-100" href="/?tags={{ tag.name | urlencode }}">#{{ tag.name }}</a>
{% endfor %}
</div>
</section>
</aside>
</section>
{% endblock %}

View File

@@ -1,120 +0,0 @@
{% extends "layouts/dashboard.njk" %}
{% block dashboardBody %}
<section id="profile" class="rounded-2xl border border-zinc-200 bg-gradient-to-r from-white via-white to-zinc-50 p-4 shadow-sm">
<h2 class="font-[Source_Serif_4] text-3xl font-semibold text-zinc-900">Profile</h2>
<div class="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<div class="rounded-lg border border-zinc-200 bg-white p-3">
<p class="text-xs uppercase tracking-wide text-zinc-500">Name</p>
<p class="mt-1 font-semibold text-zinc-900">{{ currentUser.name or "-" }}</p>
</div>
<div class="rounded-lg border border-zinc-200 bg-white p-3">
<p class="text-xs uppercase tracking-wide text-zinc-500">Email</p>
<p class="mt-1 font-semibold text-zinc-900">{{ currentUser.email }}</p>
</div>
<div class="rounded-lg border border-zinc-200 bg-white p-3">
<p class="text-xs uppercase tracking-wide text-zinc-500">Role</p>
<p class="mt-1 font-semibold text-zinc-900">{{ currentUser.role }}</p>
</div>
</div>
</section>
<section id="posts" class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 class="font-[Source_Serif_4] text-3xl font-semibold text-zinc-900">Posts</h2>
<p class="text-sm text-zinc-500">{{ posts.length }} post{% if posts.length != 1 %}s{% endif %}</p>
</div>
{% if currentUser.role == "ADMIN" or currentUser.role == "MANAGER" %}
<form
hx-post="/blog-posts"
hx-target="#flash"
hx-swap="innerHTML"
hx-on::after-request="refreshDashboardPosts()"
class="mt-4 space-y-3 rounded-xl border border-zinc-200 bg-zinc-50/60 p-4"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Create New Post</h3>
<span class="rounded-full border border-zinc-200 bg-white px-3 py-1 text-xs font-semibold uppercase tracking-wide text-zinc-500">Editor</span>
</div>
<div class="grid gap-2 md:grid-cols-2">
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="title" placeholder="Title" required />
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="slug" placeholder="Slug (optional)" />
</div>
<textarea class="min-h-20 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="excerpt" placeholder="Excerpt"></textarea>
<textarea class="min-h-36 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="content" placeholder="Content" required></textarea>
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
<select name="contentFormat" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="markdown" selected>Markdown</option>
<option value="html">HTML</option>
</select>
{% if currentUser.role == "ADMIN" %}
<select name="status" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="draft" selected>Draft</option>
<option value="published">Published</option>
<option value="archived">Archived</option>
</select>
<select name="isFeatured" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="false" selected>Not featured</option>
<option value="true">Featured</option>
</select>
{% else %}
<input type="hidden" name="status" value="draft" />
<input type="hidden" name="isFeatured" value="false" />
<p class="text-sm text-zinc-500">Status is forced to draft for manager accounts.</p>
{% endif %}
</div>
<div class="grid gap-2 md:grid-cols-2">
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="categories" placeholder="Categories: backend,api" />
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="tags" placeholder="Tags: rest,pagination" />
</div>
<div class="grid gap-2 md:grid-cols-2">
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="featuredImageUrl" placeholder="Featured image URL (optional)" />
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="featuredImageAlt" placeholder="Featured image ALT (optional)" />
</div>
<div class="flex flex-wrap items-center justify-between gap-2">
<p class="text-xs text-zinc-500">Image URL + ALT will be saved into `featuredImage`. Leave URL empty to skip.</p>
<button class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700" type="submit">Create post</button>
</div>
</form>
{% endif %}
<div id="dashboard-posts-table" class="mt-4">
{% include "partials/dashboard-post-table.njk" %}
</div>
</section>
{% if currentUser.role == "ADMIN" %}
<section id="users" class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
<h2 class="font-[Source_Serif_4] text-3xl font-semibold text-zinc-900">Users</h2>
<form
hx-post="/users"
hx-target="#flash"
hx-swap="innerHTML"
hx-on::after-request="refreshDashboardUsers()"
class="mt-3 grid gap-2 lg:grid-cols-5"
>
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="name" placeholder="Name" required />
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="email" type="email" placeholder="Email" required />
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="password" type="password" placeholder="Password" required />
<select name="role" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="MEMBER" selected>MEMBER</option>
<option value="MANAGER">MANAGER</option>
<option value="ADMIN">ADMIN</option>
</select>
<button class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700" type="submit">Create user</button>
</form>
<div id="dashboard-users-table" class="mt-4">
{% include "partials/dashboard-user-table.njk" %}
</div>
</section>
{% endif %}
{% endblock %}

View File

@@ -1,160 +0,0 @@
{% extends "layouts/base.njk" %}
{% block body %}
<section class="rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm">
<div class="flex flex-wrap items-start justify-between gap-4">
<div class="max-w-3xl">
<h1 class="font-[Source_Serif_4] text-4xl font-semibold leading-tight text-zinc-900">Practical Engineering Stories</h1>
<p class="mt-2 text-zinc-600">Fast backend patterns, frontend craft, and product lessons from shipping real systems.</p>
</div>
<div class="flex flex-wrap justify-end gap-2">
{% for c in topCategories %}
<button
class="rounded-full border border-zinc-200 bg-zinc-50 px-3 py-1.5 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700"
type="button"
hx-get="/blog-posts/partials/grid?page=1&pageSize={{ query.pageSize }}&q=&tags=&category={{ c.name | urlencode }}&sort={{ query.sort }}"
hx-target="#post-grid-container"
hx-swap="innerHTML"
>
{{ c.name }} ({{ c.count }})
</button>
{% endfor %}
</div>
</div>
</section>
<section class="rounded-2xl border border-zinc-200 bg-gradient-to-r from-white via-sky-50 to-emerald-50 p-5 shadow-sm">
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)]">
{% if featured and featured.length > 0 %}
<article class="rounded-xl border border-dashed border-teal-200 bg-white/80 p-5">
<p class="mb-3 inline-flex items-center rounded-full border border-amber-200 bg-amber-50 px-2.5 py-0.5 text-xs font-semibold uppercase tracking-wide text-amber-700">Featured pick</p>
<h2 class="font-[Source_Serif_4] text-3xl font-semibold leading-tight text-zinc-900">
<a href="/blog/{{ featured[0].slug }}" class="transition hover:text-teal-700">{{ featured[0].title }}</a>
</h2>
<p class="mt-3 text-zinc-600">{{ featured[0].excerpt }}</p>
<p class="mt-3 text-sm font-medium text-zinc-500">{{ featured[0].views }} views</p>
</article>
{% endif %}
<div class="grid gap-3">
{% for post in featured %}
{% if loop.index0 > 0 %}
<article class="rounded-xl border border-zinc-200 bg-white/80 p-4">
<h3 class="font-[Source_Serif_4] text-xl font-semibold text-zinc-900">
<a href="/blog/{{ post.slug }}" class="transition hover:text-teal-700">{{ post.title }}</a>
</h3>
<p class="mt-2 text-sm text-zinc-600">{{ post.excerpt }}</p>
</article>
{% endif %}
{% endfor %}
</div>
</div>
</section>
<section class="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
<div>
<form
id="home-filter-form"
class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm"
hx-get="/blog-posts/partials/grid"
hx-target="#post-grid-container"
hx-swap="innerHTML"
hx-trigger="submit, keyup changed delay:450ms from:#q, keyup changed delay:450ms from:#tags, change delay:150ms from:#category, change delay:150ms from:#sort"
>
<div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
<div class="md:col-span-2">
<label for="q" class="mb-1 block text-sm font-medium text-zinc-600">Search title + excerpt</label>
<input id="q" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="q" type="search" placeholder="Search posts" value="{{ query.q }}" />
</div>
<div>
<label for="category" class="mb-1 block text-sm font-medium text-zinc-600">Category</label>
<select id="category" name="category" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="">All</option>
{% for c in topCategories %}
<option value="{{ c.name }}" {% if query.category == c.name %}selected{% endif %}>{{ c.name }}</option>
{% endfor %}
</select>
</div>
<div>
<label for="sort" class="mb-1 block text-sm font-medium text-zinc-600">Sort</label>
<select id="sort" name="sort" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="newest" {% if query.sort == "newest" %}selected{% endif %}>Newest</option>
<option value="oldest" {% if query.sort == "oldest" %}selected{% endif %}>Oldest</option>
<option value="most_viewed" {% if query.sort == "most_viewed" %}selected{% endif %}>Most viewed</option>
<option value="featured" {% if query.sort == "featured" %}selected{% endif %}>Featured first</option>
</select>
</div>
</div>
<div class="mt-3 grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-end">
<div>
<label for="tags" class="mb-1 block text-sm font-medium text-zinc-600">Tags (comma separated)</label>
<input id="tags" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="tags" value="{{ query.tags }}" placeholder="nextjs, ui" />
</div>
<div class="flex gap-2">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="{{ query.pageSize }}" />
<button type="submit" class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700">Apply</button>
</div>
</div>
</form>
<div id="post-grid-container" class="mt-4">
{% set result = posts %}
{% include "partials/post-grid.njk" %}
</div>
</div>
<aside class="grid gap-4">
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Popular Posts</h3>
<div class="mt-3 grid gap-2">
{% for item in popularPosts %}
<a href="/blog/{{ item.slug }}" class="flex items-center justify-between rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700">
<span>{{ item.title }}</span>
<span class="text-zinc-500">{{ item.views }}</span>
</a>
{% endfor %}
</div>
</section>
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Newsletter</h3>
<p class="mt-1 text-sm text-zinc-600">One practical note every Friday.</p>
<form hx-post="/auth/magic-link" hx-target="#flash" hx-swap="innerHTML" class="mt-3">
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" type="email" name="email" placeholder="you@example.com" required />
<button class="mt-2 w-full rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700" type="submit">Join</button>
</form>
</section>
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Tag Cloud</h3>
<div class="mt-3 flex flex-wrap gap-2">
{% for tag in topTags %}
<button
type="button"
class="rounded-full border border-teal-200 bg-teal-50 px-2.5 py-1 text-xs font-medium text-teal-700 transition hover:border-teal-400 hover:bg-teal-100"
hx-get="/blog-posts/partials/grid?page=1&pageSize={{ query.pageSize }}&q=&tags={{ tag.name | urlencode }}&category=&sort={{ query.sort }}"
hx-target="#post-grid-container"
hx-swap="innerHTML"
>
#{{ tag.name }} ({{ tag.count }})
</button>
{% endfor %}
</div>
</section>
<section class="rounded-2xl border border-zinc-200 bg-gradient-to-r from-amber-50 to-orange-50 p-4 shadow-sm">
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Ad Space</h3>
<p class="mt-1 text-sm text-zinc-600">Placeholder for sponsor content.</p>
</section>
</aside>
</section>
<footer class="rounded-2xl border border-zinc-200 bg-white p-4 text-center text-sm text-zinc-600 shadow-sm">
Built with Fastify + HTMX + Mongoose
</footer>
{% endblock %}

View File

@@ -1,112 +0,0 @@
{% if posts.length == 0 %}
<div class="rounded-xl border border-dashed border-zinc-300 bg-zinc-50 p-5 text-sm text-zinc-600">
No posts yet.
</div>
{% else %}
<div class="grid gap-4">
{% for post in posts %}
<article class="rounded-xl border border-zinc-200 bg-white p-4 shadow-sm">
<div class="flex flex-wrap items-start justify-between gap-3">
<div class="space-y-1">
<a href="/blog/{{ post.slug }}" class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900 transition hover:text-teal-700">{{ post.title }}</a>
<p class="text-xs text-zinc-500">/{{ post.slug }}</p>
<div class="flex flex-wrap gap-2 pt-1">
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2.5 py-0.5 text-xs font-medium uppercase tracking-wide text-teal-700">{{ post.status }}</span>
<span class="inline-flex items-center rounded-full border border-zinc-200 bg-zinc-100 px-2.5 py-0.5 text-xs font-medium text-zinc-600">{{ post.views }} views</span>
{% if post.isFeatured %}
<span class="inline-flex items-center rounded-full border border-amber-200 bg-amber-50 px-2.5 py-0.5 text-xs font-medium text-amber-700">featured</span>
{% endif %}
<span class="inline-flex items-center rounded-full border border-zinc-200 bg-zinc-50 px-2.5 py-0.5 text-xs font-medium text-zinc-600">Author: {{ post.author.name if post.author else "Unknown" }}</span>
</div>
</div>
<a href="/blog/{{ post.slug }}" class="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700">View post</a>
</div>
{% if post.featuredImage %}
<div class="mt-3 overflow-hidden rounded-lg border border-zinc-200">
<img src="{{ post.featuredImage.url }}" alt="{{ post.featuredImage.alt }}" class="h-44 w-full object-cover" loading="lazy" />
</div>
{% endif %}
<p class="mt-3 text-sm text-zinc-600">{{ post.excerpt or "No excerpt." }}</p>
<div class="mt-3 flex flex-wrap gap-2">
{% for cat in post.categories %}
<span class="inline-flex items-center rounded-full border border-indigo-200 bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700">{{ cat }}</span>
{% endfor %}
{% for tag in post.tags %}
<span class="inline-flex items-center rounded-full border border-sky-200 bg-sky-50 px-2 py-0.5 text-xs font-medium text-sky-700">#{{ tag }}</span>
{% endfor %}
</div>
{% if currentUser.role == "ADMIN" %}
<details class="mt-4 rounded-lg border border-zinc-200 bg-zinc-50 p-3">
<summary class="cursor-pointer text-sm font-semibold text-zinc-800">Edit this post</summary>
<form
hx-patch="/blog-posts/{{ post.id }}"
hx-target="#flash"
hx-swap="innerHTML"
hx-on::after-request="refreshDashboardPosts()"
class="mt-3 space-y-3"
>
<div class="grid gap-2 md:grid-cols-2">
<input name="title" value="{{ post.title }}" required class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
<input name="slug" value="{{ post.slug }}" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
</div>
<textarea name="excerpt" class="min-h-20 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">{{ post.excerpt }}</textarea>
<textarea name="content" class="min-h-36 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">{{ post.content }}</textarea>
<div class="grid gap-2 sm:grid-cols-3">
<select name="contentFormat" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="markdown" {% if post.contentFormat == "markdown" %}selected{% endif %}>Markdown</option>
<option value="html" {% if post.contentFormat == "html" %}selected{% endif %}>HTML</option>
</select>
<select name="status" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="draft" {% if post.status == "draft" %}selected{% endif %}>draft</option>
<option value="published" {% if post.status == "published" %}selected{% endif %}>published</option>
<option value="archived" {% if post.status == "archived" %}selected{% endif %}>archived</option>
</select>
<select name="isFeatured" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="false" {% if not post.isFeatured %}selected{% endif %}>not featured</option>
<option value="true" {% if post.isFeatured %}selected{% endif %}>featured</option>
</select>
</div>
<div class="grid gap-2 md:grid-cols-2">
<input name="categories" value="{{ post.categories | join(',') }}" placeholder="Categories: backend,api" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
<input name="tags" value="{{ post.tags | join(',') }}" placeholder="Tags: rest,pagination" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
</div>
<div class="grid gap-2 md:grid-cols-2">
<input name="featuredImageUrl" value="{{ post.featuredImage.url if post.featuredImage else '' }}" placeholder="Featured image URL (optional)" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
<input name="featuredImageAlt" value="{{ post.featuredImage.alt if post.featuredImage else '' }}" placeholder="Featured image ALT (optional)" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
</div>
<div class="flex flex-wrap items-center justify-between gap-2">
<p class="text-xs text-zinc-500">To remove image: clear the URL field and save changes.</p>
<button class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700" type="submit">Save changes</button>
</div>
</form>
</details>
<button
class="mt-3 rounded-lg border border-rose-200 bg-white px-3 py-2 text-sm font-medium text-rose-700 transition hover:bg-rose-50"
type="button"
hx-delete="/blog-posts/{{ post.id }}"
hx-target="#flash"
hx-swap="innerHTML"
hx-confirm="Delete this post permanently?"
hx-on::after-request="refreshDashboardPosts()"
>
Delete post
</button>
{% else %}
<p class="mt-3 text-sm text-zinc-500">Read-only for {{ currentUser.role }} role.</p>
{% endif %}
</article>
{% endfor %}
</div>
{% endif %}

View File

@@ -1,57 +0,0 @@
{% if users.length == 0 %}
<p class="text-sm text-zinc-600">No users found.</p>
{% else %}
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-zinc-200 text-sm">
<thead class="bg-zinc-50 text-left text-xs uppercase tracking-wide text-zinc-500">
<tr>
<th class="px-3 py-2 font-semibold">Name</th>
<th class="px-3 py-2 font-semibold">Email</th>
<th class="px-3 py-2 font-semibold">Role</th>
<th class="px-3 py-2 font-semibold">Active</th>
<th class="px-3 py-2 font-semibold">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 bg-white text-zinc-700">
{% for user in users %}
<tr class="align-top">
<td class="px-3 py-3">{{ user.name }}</td>
<td class="px-3 py-3">{{ user.email }}</td>
<td class="px-3 py-3">
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2.5 py-0.5 text-xs font-medium uppercase tracking-wide text-teal-700">{{ user.role }}</span>
</td>
<td class="px-3 py-3">{{ "yes" if user.isActive else "no" }}</td>
<td class="px-3 py-3">
<div class="grid min-w-[18rem] gap-2">
<form
hx-patch="/users/{{ user.id }}"
hx-target="#flash"
hx-swap="innerHTML"
hx-on::after-request="refreshDashboardUsers()"
class="flex gap-2"
>
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="name" value="{{ user.name }}" required />
<button class="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700" type="submit">Rename</button>
</form>
<form
hx-patch="/users/{{ user.id }}/role"
hx-target="#flash"
hx-swap="innerHTML"
hx-on::after-request="refreshDashboardUsers()"
class="flex flex-wrap gap-2"
>
<select name="role" class="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
<option value="MEMBER" {% if user.role == "MEMBER" %}selected{% endif %}>MEMBER</option>
<option value="MANAGER" {% if user.role == "MANAGER" %}selected{% endif %}>MANAGER</option>
<option value="ADMIN" {% if user.role == "ADMIN" %}selected{% endif %}>ADMIN</option>
</select>
<button class="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700" type="submit">Set role</button>
</form>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}

View File

@@ -1,9 +0,0 @@
{% if message %}
<div class="pointer-events-auto rounded-xl border px-4 py-3 text-sm font-medium shadow-lg {% if type == 'success' %}border-emerald-200 bg-emerald-50 text-emerald-800{% elif type == 'error' %}border-rose-200 bg-rose-50 text-rose-800{% else %}border-amber-200 bg-amber-50 text-amber-800{% endif %}">
{{ message }}
</div>
{% elif flash %}
<div class="pointer-events-auto rounded-xl border px-4 py-3 text-sm font-medium shadow-lg {% if flash.type == 'success' %}border-emerald-200 bg-emerald-50 text-emerald-800{% elif flash.type == 'error' %}border-rose-200 bg-rose-50 text-rose-800{% else %}border-amber-200 bg-amber-50 text-amber-800{% endif %}">
{{ flash.message }}
</div>
{% endif %}

View File

@@ -1,44 +0,0 @@
{% set pages = (result.total / result.pageSize) | round(0, "ceil") %}
{% if pages > 1 %}
<div class="flex flex-wrap items-center justify-between gap-3 border-t border-zinc-200 pt-4">
<p class="text-sm text-zinc-600">Page {{ result.page }} of {{ pages }}</p>
<div class="flex flex-wrap gap-2">
{% if result.page > 1 %}
<button
type="button"
class="rounded-lg border border-zinc-200 bg-white px-3 py-1.5 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700"
hx-get="/blog-posts/partials/grid?page={{ result.page - 1 }}&pageSize={{ result.pageSize }}&q={{ query.q | urlencode }}&tags={{ query.tags | urlencode }}&category={{ query.category | urlencode }}&sort={{ query.sort }}"
hx-target="#post-grid-container"
hx-swap="innerHTML"
>
Prev
</button>
{% endif %}
{% for n in range(1, pages + 1) %}
<button
type="button"
class="rounded-lg border px-3 py-1.5 text-sm font-medium transition {% if n == result.page %}border-teal-600 bg-teal-600 text-white{% else %}border-zinc-200 bg-white text-zinc-700 hover:border-teal-500 hover:text-teal-700{% endif %}"
hx-get="/blog-posts/partials/grid?page={{ n }}&pageSize={{ result.pageSize }}&q={{ query.q | urlencode }}&tags={{ query.tags | urlencode }}&category={{ query.category | urlencode }}&sort={{ query.sort }}"
hx-target="#post-grid-container"
hx-swap="innerHTML"
>
{{ n }}
</button>
{% endfor %}
{% if result.page < pages %}
<button
type="button"
class="rounded-lg border border-zinc-200 bg-white px-3 py-1.5 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700"
hx-get="/blog-posts/partials/grid?page={{ result.page + 1 }}&pageSize={{ result.pageSize }}&q={{ query.q | urlencode }}&tags={{ query.tags | urlencode }}&category={{ query.category | urlencode }}&sort={{ query.sort }}"
hx-target="#post-grid-container"
hx-swap="innerHTML"
>
Next
</button>
{% endif %}
</div>
</div>
{% endif %}

View File

@@ -1,37 +0,0 @@
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm sm:p-5">
<div class="grid gap-4 sm:grid-cols-2">
{% for post in result.items %}
<article class="rounded-xl border border-zinc-200 bg-zinc-50/60 p-4">
{% if post.featuredImage %}
<a href="/blog/{{ post.slug }}" class="mb-3 block overflow-hidden rounded-lg border border-zinc-200">
<img
src="{{ post.featuredImage.url }}"
alt="{{ post.featuredImage.alt or post.title }}"
class="h-48 w-full object-cover transition duration-200 hover:scale-[1.02]"
loading="lazy"
/>
</a>
{% endif %}
<div class="mb-3 flex flex-wrap gap-2">
{% for cat in post.categories %}
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2.5 py-0.5 text-xs font-medium uppercase tracking-wide text-teal-700">{{ cat }}</span>
{% endfor %}
</div>
<h3 class="mb-2 font-[Source_Serif_4] text-xl font-semibold leading-tight text-zinc-900">
<a href="/blog/{{ post.slug }}" class="transition hover:text-teal-700">{{ post.title }}</a>
</h3>
<p class="mb-3 text-sm text-zinc-600">{{ post.excerpt }}</p>
<p class="text-sm font-medium text-zinc-500">{{ post.views }} views</p>
</article>
{% else %}
<div class="rounded-xl border border-zinc-200 bg-zinc-50 p-5 sm:col-span-2">
<p class="text-sm text-zinc-600">No published posts found for this filter.</p>
</div>
{% endfor %}
</div>
<div class="mt-4">
{% include "partials/pagination.njk" %}
</div>
</section>

View File

@@ -22,7 +22,17 @@ import {
SheetHeader, SheetHeader,
SheetTitle, SheetTitle,
} from "@/components/ui/sheet"; } from "@/components/ui/sheet";
import { Loader2, Pencil, Check, Users2 } from "lucide-react"; import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Loader2, Pencil, Trash2, Check, Users2 } from "lucide-react";
interface Props { interface Props {
initialUsers: User[]; initialUsers: User[];
@@ -55,9 +65,11 @@ function Avatar({ name, email }: { name?: string; email: string }) {
export function UsersTable({ initialUsers }: Props) { export function UsersTable({ initialUsers }: Props) {
const [users, setUsers] = useState<User[]>(initialUsers); const [users, setUsers] = useState<User[]>(initialUsers);
const [editingUser, setEditingUser] = useState<User | null>(null); const [editingUser, setEditingUser] = useState<User | null>(null);
const [deletingUser, setDeletingUser] = useState<User | null>(null);
const [editName, setEditName] = useState(""); const [editName, setEditName] = useState("");
const [editRole, setEditRole] = useState<UserRole>(UserRole.MEMBER); const [editRole, setEditRole] = useState<UserRole>(UserRole.MEMBER);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
const openEdit = (user: User) => { const openEdit = (user: User) => {
setEditingUser(user); setEditingUser(user);
@@ -107,6 +119,21 @@ export function UsersTable({ initialUsers }: Props) {
} }
}; };
const handleDelete = async () => {
if (!deletingUser) return;
setDeleteLoading(true);
try {
await clientFetch(`/users/${deletingUser.id}`, { method: "DELETE" });
toast.success(`User "${deletingUser.email}" deleted.`);
setUsers((prev) => prev.filter((u) => u.id !== deletingUser.id));
setDeletingUser(null);
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : "Delete failed");
} finally {
setDeleteLoading(false);
}
};
if (users.length === 0) { if (users.length === 0) {
return ( return (
<div className="rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground"> <div className="rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground">
@@ -164,6 +191,15 @@ export function UsersTable({ initialUsers }: Props) {
> >
<Pencil className="h-3.5 w-3.5" /> <Pencil className="h-3.5 w-3.5" />
</Button> </Button>
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0 shrink-0 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeletingUser(user)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div> </div>
); );
})} })}
@@ -257,6 +293,37 @@ export function UsersTable({ initialUsers }: Props) {
</div> </div>
</SheetContent> </SheetContent>
</Sheet> </Sheet>
{/* ── Delete confirmation dialog ────────────────────────────────────── */}
<AlertDialog open={!!deletingUser} onOpenChange={(o) => !o && setDeletingUser(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete user?</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete{" "}
<span className="font-medium text-foreground">
{deletingUser?.name || deletingUser?.email}
</span>
. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteLoading}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={deleteLoading}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteLoading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Trash2 className="mr-2 h-4 w-4" />
)}
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</> </>
); );
} }

View File

@@ -5,7 +5,7 @@
@custom-variant dark (&:is(.dark *)); @custom-variant dark (&:is(.dark *));
:root { :root {
--background: oklch(1.0000 0 0); --background: oklch(1.0000 0 0);
--foreground: oklch(0 0 0); --foreground: oklch(0 0 0);
--card: oklch(1.0000 0 0); --card: oklch(1.0000 0 0);
@@ -14,8 +14,8 @@
--popover-foreground: oklch(0 0 0); --popover-foreground: oklch(0 0 0);
--primary: oklch(0.5323 0.1730 141.3064); --primary: oklch(0.5323 0.1730 141.3064);
--primary-foreground: oklch(1.0000 0 0); --primary-foreground: oklch(1.0000 0 0);
--secondary: oklch(0.5788 0.2316 259.6380); --secondary: oklch(0.5762 0.2175 258.9127);
--secondary-foreground: oklch(0 0 0); --secondary-foreground: oklch(1.0000 0 0);
--muted: oklch(0.9551 0 0); --muted: oklch(0.9551 0 0);
--muted-foreground: oklch(0.3211 0 0); --muted-foreground: oklch(0.3211 0 0);
--accent: oklch(0.5635 0.2408 260.8178); --accent: oklch(0.5635 0.2408 260.8178);

View File

@@ -116,7 +116,7 @@ export default async function HomePage({
<div className="flex flex-wrap items-start justify-between gap-4"> <div className="flex flex-wrap items-start justify-between gap-4">
<div className="max-w-2xl"> <div className="max-w-2xl">
<h1 className="text-3xl font-bold tracking-tight"> <h1 className="text-3xl font-bold tracking-tight">
Practical Engineering Stories The blog is all about web dev tech
</h1> </h1>
<p className="mt-2 text-muted-foreground"> <p className="mt-2 text-muted-foreground">
Fast backend patterns, frontend craft, and product lessons from Fast backend patterns, frontend craft, and product lessons from

View File

@@ -8,7 +8,7 @@ import { useRouter } from "next/navigation";
import { toast } from "sonner"; import { toast } from "sonner";
export function Navbar() { export function Navbar() {
const { currentUser, logout } = useAuth(); const { currentUser, loading, logout } = useAuth();
const router = useRouter(); const router = useRouter();
const handleLogout = async () => { const handleLogout = async () => {
@@ -41,31 +41,35 @@ export function Navbar() {
</Link> </Link>
</Button> </Button>
{currentUser ? ( {!loading && (
<> <>
<Button variant="ghost" size="sm" asChild> {currentUser ? (
<Link href="/dashboard"> <>
<LayoutDashboard className="h-4 w-4 mr-1" /> <Button variant="ghost" size="sm" asChild>
<span className="hidden sm:inline">Dashboard</span> <Link href="/dashboard">
</Link> <LayoutDashboard className="h-4 w-4 mr-1" />
</Button> <span className="hidden sm:inline">Dashboard</span>
<Button </Link>
variant="ghost" </Button>
size="sm" <Button
onClick={handleLogout} variant="ghost"
className="text-destructive hover:text-destructive" size="sm"
> onClick={handleLogout}
<LogOut className="h-4 w-4 mr-1" /> className="text-destructive hover:text-destructive"
<span className="hidden sm:inline">Logout</span> >
</Button> <LogOut className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Logout</span>
</Button>
</>
) : (
<Button variant="ghost" size="sm" asChild>
<Link href="/auth">
<LogIn className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Sign In</span>
</Link>
</Button>
)}
</> </>
) : (
<Button variant="ghost" size="sm" asChild>
<Link href="/auth">
<LogIn className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Sign In</span>
</Link>
</Button>
)} )}
</nav> </nav>
</div> </div>

View File

@@ -69,15 +69,12 @@ export async function apiFetch<T = unknown>(
// ─── Client-side fetch (use in Client Components) ───────────────────────────── // ─── Client-side fetch (use in Client Components) ─────────────────────────────
export async function clientFetch<T = unknown>( async function doClientFetch(path: string, init?: RequestInit): Promise<Response> {
path: string,
init?: RequestInit
): Promise<T> {
const method = (init?.method ?? "GET").toUpperCase(); const method = (init?.method ?? "GET").toUpperCase();
const needsCsrf = STATE_CHANGING_METHODS.includes(method); const needsCsrf = STATE_CHANGING_METHODS.includes(method);
const csrfToken = needsCsrf ? getClientCsrfToken() : ""; const csrfToken = needsCsrf ? getClientCsrfToken() : "";
const res = await fetch(`${API_URL}${path}`, { return fetch(`${API_URL}${path}`, {
...init, ...init,
credentials: "include", credentials: "include",
headers: { headers: {
@@ -86,6 +83,22 @@ export async function clientFetch<T = unknown>(
...(init?.headers as Record<string, string> | undefined), ...(init?.headers as Record<string, string> | undefined),
}, },
}); });
}
export async function clientFetch<T = unknown>(
path: string,
init?: RequestInit
): Promise<T> {
let res = await doClientFetch(path, init);
// Auto-refresh expired access token on 401, then retry once.
// Skip for /auth/ paths to avoid refresh loops.
if (res.status === 401 && !path.startsWith("/auth/")) {
const refreshRes = await doClientFetch("/auth/refresh", { method: "POST" });
if (refreshRes.ok) {
res = await doClientFetch(path, init);
}
}
if (!res.ok) { if (!res.ok) {
let msg = `API error ${res.status}`; let msg = `API error ${res.status}`;

View File

@@ -25,30 +25,22 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null); const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
/** Decode the JWT access token stored in the browser cookie (non-httpOnly portion). /** Calls GET /auth/me with the httpOnly cookie to restore the current user.
* Since accessToken is httpOnly, we detect auth state by calling a lightweight * Returns the JWT payload if valid, clears auth state if 401. */
* authenticated endpoint. If it returns 401 → not logged in. */
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
try { try {
// Call GET /blog-posts?pageSize=1 — requires auth. If cookie is valid, returns data. const data = await clientFetch<{ success: boolean; user: CurrentUser }>(
// We only care about the response headers/status here, not the body. "/auth/me"
const data = await clientFetch<{
posts?: unknown[];
total?: number;
// The JWT payload fields we need come from the cookie;
// we parse them via a lightweight /auth/me-style endpoint.
// Since we don't have /auth/me, we use the blog-posts endpoint response
// and get user info from a separate call to /users (ADMIN only) or just
// decode what we need from the refresh token.
// Simpler: call GET /blog-posts and use the response to confirm auth,
// then store minimal info from localStorage if previously set.
}>(
"/blog-posts?pageSize=1"
); );
// Auth succeeded — try to restore user from sessionStorage if (data.user) {
const cached = sessionStorage.getItem("currentUser"); const user: CurrentUser = {
if (cached) { sub: data.user.sub,
setCurrentUser(JSON.parse(cached)); email: data.user.email,
role: (data.user.role as string).toUpperCase() as UserRole,
name: data.user.name,
};
setCurrentUser(user);
sessionStorage.setItem("currentUser", JSON.stringify(user));
} }
} catch (err) { } catch (err) {
if (err instanceof ApiError && err.status === 401) { if (err instanceof ApiError && err.status === 401) {