diff --git a/src/routes/auth.ts b/src/routes/auth.ts new file mode 100644 index 0000000..e8dd4b3 --- /dev/null +++ b/src/routes/auth.ts @@ -0,0 +1,103 @@ +import type { FastifyInstance } from 'fastify'; +import { AuthService } from '../services/auth/auth.service.js'; + +const registerSchema = { + body: { + type: 'object', + required: ['email', 'password', 'nickname'], + properties: { + email: { type: 'string', minLength: 1 }, + password: { type: 'string', minLength: 8 }, + nickname: { type: 'string', minLength: 2, maxLength: 30 }, + }, + }, +}; + +const loginSchema = { + body: { + type: 'object', + required: ['email', 'password'], + properties: { + email: { type: 'string', minLength: 1 }, + password: { type: 'string' }, + }, + }, +}; + +const refreshTokenSchema = { + body: { + type: 'object', + required: ['refreshToken'], + properties: { + refreshToken: { type: 'string' }, + }, + }, +}; + +const logoutSchema = refreshTokenSchema; + +export async function authRoutes(app: FastifyInstance) { + const authService = new AuthService(app.db); + + app.post( + '/register', + { schema: registerSchema }, + async (req, reply) => { + const body = req.body as { email: string; password: string; nickname: string }; + const { userId, verificationCode } = await authService.register(body); + + return reply.status(201).send({ + userId, + message: 'Registration successful. Please verify your email.', + verificationCode, + }); + }, + ); + + app.post( + '/login', + { schema: loginSchema }, + async (req, reply) => { + const body = req.body as { email: string; password: string }; + const userAgent = req.headers['user-agent']; + const ipAddress = req.ip; + + const result = await authService.login({ + email: body.email, + password: body.password, + userAgent, + ipAddress, + }); + + return reply.send(result); + }, + ); + + app.post( + '/logout', + { schema: logoutSchema }, + async (req, reply) => { + const body = req.body as { refreshToken: string }; + await authService.logout(body.refreshToken); + return reply.status(204).send(); + }, + ); + + app.post( + '/refresh', + { schema: refreshTokenSchema }, + async (req, reply) => { + const body = req.body as { refreshToken: string }; + const userAgent = req.headers['user-agent']; + const ipAddress = req.ip; + + const result = await authService.refresh({ + refreshToken: body.refreshToken, + userAgent, + ipAddress, + }); + + return reply.send(result); + }, + ); +}