First part of backend rework

- Added the base data structure for the new database
- Added the new routes for the new database
- Reworked the users endpoints
This commit is contained in:
2024-02-26 10:20:29 +01:00
parent 902bab14c7
commit 0ddbc437b9
40 changed files with 1237 additions and 1911 deletions

40
modules/tokenManager.js Normal file
View File

@@ -0,0 +1,40 @@
/* eslint-disable no-undef */
import jwt from 'jsonwebtoken';
import { Level } from 'level';
import { respondWithStatus } from './requestHandler';
import { userExists } from './permissionManager';
const db = new Level('tokens', { valueEncoding: 'json' });
export async function generateToken(userId, password) {
const token = jwt.sign({ userId: userId, password: password }, process.env.JWT_SECRET, { expiresIn: '7d' });
await db.put(token, 'valid');
return token;
}
export async function verifyToken(req, res, next) {
const token = req.headers.authorization;
if (!token) return await respondWithStatus(res, 401, 'No token provided');
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
if (!userExists(userId)) return await respondWithStatus(res, 404, 'User not found');
const passwordMatch = await Bun.password.verify(decoded.password, rows[0].password);
if (!passwordMatch) return await respondWithStatus(res, 401, 'Token is invalid');
const tokenStatus = await db.get(token);
if (tokenStatus != 'valid') {
return await respondWithStatus(res, 401, 'Token has been revoked ');
}
next();
}
catch (error) {
return await respondWithStatus(res, 401, 'Invalid user');
}
}
export async function revokeToken(token) {
db.put(token, 'revoked');
}