import { Response, Request } from "express"; import { APIHelper } from "../helpers/APIHelper"; import { APIClient } from "./APIClient"; /** * Response to a request * * @author Pierre HUBERT */ export class RequestHandler { private client : APIClient = null; public constructor(private req : Request, private response : Response) {} /** * Get a parameter included in the post request * * @param name Name of the parameter to get */ private getPostParam(name : string) : any { return this.req.body[name]; } /** * Get a String from the request * * @param name The name of the string to get * @param minLength Minimal required size of the string * @param required If set to true (true by default), an error will * be thrown if the string is not included in the request */ public getString(name : string, minLength : number = 1, required : boolean = true) : string { const param = this.getPostParam(name); // Check if parameter was not found if(param == undefined) { if(required) this.error(400, "Could not find required string: '"+name+"'"); return ""; } if(param.length < minLength) this.error(400, "Parameter "+name+" is too short!"); return param; } /** * Validate API tokens * * @throws If the tokens could not be validated */ public async checkAPITokens() { // Extract API name & token from request const apiName = this.getString("serviceName"); const apiToken = this.getString("serviceToken"); // Validate the client const client = await APIHelper.GetClient(apiName, apiToken); if(client == null) this.error(400, "Client not recognized!"); if(client.domain) { const allowedOrigin = "http://" + client.domain; const referer = this.req.get("Referer"); if(!referer || !referer.startsWith(allowedOrigin)) this.error(401, "Use of this client is prohibited from this domain!"); this.response.set("Access-Control-Allow-Origin", allowedOrigin); } // Save client information for latter access this.client = client; } /** * Output an error code * * @param code HTTP Status code * @param message The message to send */ public error(code : number, message : string) { this.response.status(code).send({ code: code, message: message }); throw Error("Could not complete request!"); } /** * Return a successful operation * * @param message Message associated to success */ public success(message: string) { this.response.send({ success: message }); } /** * Send some data to the server * * @param data The data to send back to the server */ public send(data: any) { this.response.send(data); } }