Skip to content
Snippets Groups Projects
Select Git revision
  • 27e1b0fc44c3ed0343f2a7aeb5068e43c30f361a
  • main default protected
2 results

middleware.ts

Blame
  • Forked from an inaccessible project.
    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'});
        }