feat(backend): add fastify api, auth, prisma schema and jobs
This commit is contained in:
43
apps/backend/src/modules/auth/auth.routes.ts
Normal file
43
apps/backend/src/modules/auth/auth.routes.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
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 };
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user