Select Git revision
cours_20.md
middleware.ts 4.37 KiB
import express from 'express';
import {StatusCodes} from 'http-status-codes';
import {userType} from '../database/models/User'
import {Database} from "../database/Database";
const jwt = require('jsonwebtoken');
export function checkUserFields(req: express.Request, res: express.Response, next: express.NextFunction) {
if (!req.body.username && !req.body.password && !req.body.accountType) {
return res.status(400).json({ error: '"username", "password" and "accountType" required' });
}
if(req.body.accountType !== userType.Gamer && req.body.accountType !== userType.Admin){
const accountType={
Gamer: 0,
Admin: 1
}
return res.status(StatusCodes.NOT_ACCEPTABLE).json({error: {
valueAccountTypePossible: accountType
} });
}
next();
}
export async function checkExistingUser(req: express.Request, res: express.Response, next: express.NextFunction) {
let id = "";
if (req.params.username) {
id = req.params.username;
}
if (req.params.admin) {
id = req.params.admin;
}
console.log(`id = ${id}`);
const typeAccount = await Database.accountExist(id);
if(typeAccount !== undefined){
console.log(`type = ${typeAccount}`);
console.log({message: typeAccount === 'user' ? `"${id}" => user` : `"${id}" => admin`});
}else{
res.status(StatusCodes.NOT_FOUND).json({message: 'USER_NOT_FOUND'});
}
next();
}
export interface TokenRequest extends express.Request {
user?: any;
}
export async function verifyToken(req: TokenRequest, res: express.Response, next: express.NextFunction) {
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).json({message: 'Token not provided', header: req.headers});
}
const token = authHeader.split(" ")[1];
const secretKey = process.env.SECRET_KEY;
try {
req.user = jwt.verify(token, secretKey);
if(req.user.username !== req.params.admin && req.user.username !== req.params.username)
return res.status(403).json({message: 'Invalid token user'});
//check if admin or user
next();
} catch (error) {
return res.status(403).json({message: 'Invalid token'});
}
}
export function checkQuestionFields(req: express.Request, res: express.Response, next: express.NextFunction) {
if (!req.body.question && !req.body.possibleResponse && !req.body.correctResponse && !req.body.category) {
return res.status(400).json({ error: '"question", "possibleResponse", "correctResponse" and "category" required' });
}
if(req.body.possibleResponse.length < 2){
return res.status(400).json({error: "possibleResponse must be under 2 response possible"})
}
next();
}
export function checkIdField(req: express.Request, res: express.Response, next: express.NextFunction) {
if (!req.body.id) {
return res.status(400).json({ error: 'ID is required' });
}
next();
}
export function checkUsernameField(req: express.Request, res: express.Response, next: express.NextFunction) {
if (!req.body.username) {
return res.status(400).json({ error: 'Username is required' });
}
next();
}
export function createAccountCheck(req: express.Request, res: express.Response){
const data=req.body
Database.createAccount(data.username, data.password, data.firstname, data.lastname, data.email, data.accountType)
.then(result => {
if(result[0] !== -1){
if(result[1] === "User") res.status(StatusCodes.OK).json({new_user: {
username: data.username,
lastname: data.lastname,
firstname: data.firstname,
email: data.email
}});
if(result[1] === "Admin") res.status(StatusCodes.OK).json({new_admin: {
username: data.username,
lastname: data.lastname,
firstname: data.firstname,
email: data.email
}});
}else{
if(result[1] === "Exist"){
res.status(StatusCodes.NOT_ACCEPTABLE).json({message: "USER_EXIST"});
}
}
}).catch(error => {
res.status(StatusCodes.BAD_REQUEST).json({message: "An error occured"});
});
}