1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2025-02-19 23:42:40 +00:00
comunicapiv2/src/entities/RequestHandler.ts

117 lines
2.6 KiB
TypeScript
Raw Normal View History

2019-11-22 08:50:15 +01:00
import { Response, Request } from "express";
2019-11-22 09:42:01 +01:00
import { APIHelper } from "../helpers/APIHelper";
import { APIClient } from "./APIClient";
2019-11-22 08:50:15 +01:00
/**
* Response to a request
*
* @author Pierre HUBERT
*/
export class RequestHandler {
2019-11-22 09:42:01 +01:00
private client : APIClient = null;
2019-11-22 08:50:15 +01:00
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!");
2019-11-22 09:42:01 +01:00
return param;
2019-11-22 08:50:15 +01:00
}
/**
* 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");
2019-11-22 09:42:01 +01:00
// 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;
2019-11-22 08:50:15 +01:00
}
/**
* 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);
}
}