initial commit

This commit is contained in:
2026-04-26 13:47:35 -05:00
commit 844c63dd85
27 changed files with 1241 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
import { Router } from 'express';
import bcrypt from 'bcryptjs';
import { z } from 'zod';
import { pool } from '../db.js';
import { config } from '../config.js';
import { requireAuth, signUser } from '../middleware/auth.js';
export const authRouter = Router();
const loginSchema = z.object({ email: z.string().email(), password: z.string().min(1) });
authRouter.post('/login', async (req, res) => {
const body = loginSchema.parse(req.body);
const result = await pool.query(
`SELECT id, email, password_hash, role, allowed_domains FROM admin_users WHERE email=$1 AND active=true`,
[body.email.toLowerCase()],
);
const user = result.rows[0];
if (!user || !(await bcrypt.compare(body.password, user.password_hash))) {
res.status(401).json({ error: 'Invalid email or password' });
return;
}
const token = signUser({ id: user.id, email: user.email, role: user.role, allowed_domains: user.allowed_domains ?? [] });
res.cookie('mailadmin_token', token, {
httpOnly: true,
sameSite: 'lax',
secure: config.cookieSecure,
maxAge: 12 * 60 * 60 * 1000,
});
res.json({ email: user.email, role: user.role, allowed_domains: user.allowed_domains ?? [] });
});
authRouter.post('/logout', (_req, res) => {
res.clearCookie('mailadmin_token');
res.json({ ok: true });
});
authRouter.get('/me', requireAuth, (req, res) => {
res.json(req.user);
});