44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
import type { FastifyInstance } from 'fastify';
|
|
import { loginSchema } from '@family-wishlist/shared';
|
|
import { verifyCredentials } from './auth.service.js';
|
|
import { usersRegistry } from '../../auth/users.registry.js';
|
|
import { UnauthorizedError } from '../../utils/errors.js';
|
|
|
|
export default async function authRoutes(app: FastifyInstance) {
|
|
app.post(
|
|
'/login',
|
|
{
|
|
config: {
|
|
rateLimit: { max: 5, timeWindow: '10 minutes' },
|
|
},
|
|
},
|
|
async (request, reply) => {
|
|
const body = loginSchema.parse(request.body);
|
|
const user = await verifyCredentials(body.username, body.password);
|
|
const token = await reply.jwtSign({ id: user.id, username: user.username });
|
|
app.setAuthCookie(reply, token);
|
|
return {
|
|
id: user.id,
|
|
username: user.username,
|
|
slug: user.slug,
|
|
displayName: user.displayName,
|
|
};
|
|
},
|
|
);
|
|
|
|
app.post('/logout', async (_request, reply) => {
|
|
app.clearAuthCookie(reply);
|
|
return { ok: true };
|
|
});
|
|
|
|
app.get(
|
|
'/me',
|
|
{ preHandler: [app.authenticate] },
|
|
async (request) => {
|
|
const u = usersRegistry.findById(request.user.id);
|
|
if (!u) throw new UnauthorizedError();
|
|
return { id: u.id, username: u.username, slug: u.slug, displayName: u.displayName };
|
|
},
|
|
);
|
|
}
|