diff --git a/package.json b/package.json index 9b07611..6c57406 100644 --- a/package.json +++ b/package.json @@ -18,13 +18,16 @@ "@codemirror/collab": "^6.1.1", "@codemirror/state": "^6.4.1", "@fastify/cors": "^9.0.0", + "@fastify/jwt": "^5.0.0", "@fastify/type-provider-typebox": "^4.0.0", "@fastify/websocket": "^10.0.1", "@sinclair/typebox": "^0.32.9", "dprint": "^0.46.1", + "@types/bcrypt": "^5.0.2", "bcrypt": "^5.1.1", "bcryptjs": "^2.4.3", "fastify": "^4.27.0", + "fastify-jwt": "^4.2.0", "nanoid": "^5.0.4", "sqlite3": "^5.1.7", "zeromq": "6.0.0-beta.19" diff --git a/src/server.ts b/src/server.ts index 90f144e..f57826f 100644 --- a/src/server.ts +++ b/src/server.ts @@ -5,6 +5,7 @@ import { Type, TypeBoxTypeProvider } from "@fastify/type-provider-typebox"; import websocket, { WebSocket } from "@fastify/websocket"; import bcrypt from "bcrypt"; import Fastify, { FastifyReply } from "fastify"; +import fastifyJwt from "@fastify/jwt"; import { nanoid } from "nanoid"; import { allocateBuffer, getRunner } from "runner"; import { Pull, Push } from "zeromq"; @@ -166,6 +167,11 @@ const database = db.openDatabase(); /* Créer les tables si elles n'existent pas */ db.createTables(database); +fastify.register(fastifyJwt, { + secret: 'supersecret' // Utilisez une clé secrète sécurisée en production +}); + + const salt = 10; /* Route pour créer un utilisateur */ @@ -190,7 +196,7 @@ fastify.post( if (!(await db.insertUser(database, login, hash, permissions))) { reply.send({ success: false }); } else { - reply.send({ success: true }); + return reply.send({ success: true }); } }); }, @@ -210,6 +216,17 @@ fastify.post( async (request, reply) => { const { login, password } = request.body; const user = await db.verifyUser(database, login); + if (!user) { + return reply.code(401).send({ error: 'Invalid username or password' }); + } + + const isPasswordValid = await bcrypt.compare(password, user.password); + if(isPasswordValid){ + const token = fastify.jwt.sign({ login }); + reply.send({ token: token }); + } else { + reply.code(401).send({ error: 'Invalid username or password' }); + } bcrypt.compare(password, user!.password) .then(res => reply.send({ sucess: res }))