- Replace ADMIN_PASSWORD_HASH with ADMIN_PASSWORD in auth route and docker-compose - Remove bcryptjs / @types/bcryptjs dependencies - Delete scripts/hashPassword.ts (no longer needed) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
import { Router, Request, Response, NextFunction } from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import { AppError, ok } from '../types/index';
|
|
import { authMiddleware } from '../middleware/authMiddleware';
|
|
|
|
export const authRouter = Router();
|
|
|
|
const COOKIE_OPTS = {
|
|
httpOnly: true,
|
|
sameSite: 'strict' as const,
|
|
secure: process.env.NODE_ENV === 'production',
|
|
path: '/',
|
|
};
|
|
|
|
authRouter.post('/login', (req: Request, res: Response, next: NextFunction) => {
|
|
try {
|
|
const { username, password } = req.body as { username?: string; password?: string };
|
|
|
|
if (!username || !password) {
|
|
throw new AppError('Username and password are required', 400, 'MISSING_FIELDS');
|
|
}
|
|
|
|
const adminUsername = process.env.ADMIN_USERNAME;
|
|
const adminPassword = process.env.ADMIN_PASSWORD;
|
|
|
|
if (!adminUsername || !adminPassword) {
|
|
throw new AppError('Server not configured: admin credentials missing', 500, 'CONFIG_ERROR');
|
|
}
|
|
|
|
if (username !== adminUsername || password !== adminPassword) {
|
|
throw new AppError('Invalid username or password', 401, 'INVALID_CREDENTIALS');
|
|
}
|
|
|
|
const secret = process.env.JWT_SECRET;
|
|
if (!secret) throw new AppError('Server not configured: JWT_SECRET missing', 500, 'CONFIG_ERROR');
|
|
|
|
const token = jwt.sign({ sub: 'admin' }, secret, {
|
|
expiresIn: (process.env.JWT_EXPIRY ?? '8h') as jwt.SignOptions['expiresIn'],
|
|
});
|
|
|
|
res.cookie('token', token, COOKIE_OPTS);
|
|
res.json(ok({ success: true }));
|
|
} catch (e) {
|
|
next(e);
|
|
}
|
|
});
|
|
|
|
authRouter.post('/logout', (_req: Request, res: Response) => {
|
|
res.clearCookie('token', COOKIE_OPTS);
|
|
res.json(ok({ success: true }));
|
|
});
|
|
|
|
authRouter.get('/me', authMiddleware, (_req: Request, res: Response) => {
|
|
res.json(ok({ authenticated: true }));
|
|
});
|