import { NextFunction , Router , Request , Response } from 'express' ; import { LogService } from "matrix-bot-sdk" ; import * as Errors from "./errors" ; export function validatePost ( router , endpoint , callback ) { router . post ( endpoint , ( ( req , res , next ) => { try { callback ( req , res , next ) ; } catch ( err ) { errorHandler ( req , err ) ; } } ) ) ; } export function handlePostAsync ( router , endpoint , callback ) { router . post ( endpoint , ( async ( req , res ) => { try { await callback ( req , res ) ; } catch ( err ) { errorHandler ( req , err ) ; } } ) ) ; } export function handleGet ( router , endpoint , callback ) { router . get ( endpoint , ( ( req , res ) => { try { callback ( req , res ) ; } catch ( err ) { errorHandler ( req , err ) ; } } ) ) ; } function errorHandler ( req , err ) { const id = req [ 'id' ] ; if ( err instanceof Error ) { LogService . error ( 'marco-webserver' , `Request ${ id }` , err . message ) ; } else { LogService . error ( 'marco-webserver' , `Request ${ id }` , err ) ; } } param { Request } req param { Response } res param { NextFunction } next export function checkPlayerIntegrity ( req , res , next ) { const reqID = req [ 'id' ] ; const body = req . body ; LogService . info ( 'WebInterface' , `[Request ${ reqID }]: Checking Body Integrity` ) ; if ( body == undefined ) { fail ( res , Errors . noBodyError ) ; return ; } const player = body [ 'player' ] ; if ( player == undefined ) { fail ( res , Errors . noPlayerError ) ; return ; } else if ( ! ( typeof player == 'object' ) ) { fail ( res , Errors . playerTypeError ) ; return ; } const name = player . name ; if ( name == undefined ) { fail ( res , Errors . noPlayerNameError ) ; return ; } else if ( ! ( typeof name == 'string' ) ) { fail ( res , Errors . playerNameTypeError ) ; return ; } LogService . debug ( 'WebInterface' , `[Request ${ reqID }]: Player name "${ name }"` ) ; const uuid = player . uuid ; if ( uuid == undefined ) { fail ( res , Errors . noPlayerIdError ) ; } else if ( ! ( typeof uuid == 'string' ) ) { fail ( res , Errors . playerIdTypeError ) ; return ; } LogService . debug ( 'WebInterface' , `[Request ${ reqID }]: Player UUID "${ uuid }"` ) ; LogService . info ( 'WebInterface' , `[Request ${ reqID }]: Integrity Check Passed` ) ; /**
     * If the integrity passed this is what the body should look like:
     * {
     *   "reason": "The reason for the kick",
     *   "player" {
     *     "name": "player name",
     *     "uuid": "player uuid"
     *   }
     * }
     */ next ( ) ; } export function fail ( res , error ) { res . status ( 400 ) ; res . send ( error ) ; res . end ( ) ; }