mirror of
https://gitlab.com/comunic/comunicapiv2
synced 2025-06-21 00:55:17 +00:00
Ready to check API tokens
This commit is contained in:
94
src/entities/RequestHandler.ts
Normal file
94
src/entities/RequestHandler.ts
Normal file
@ -0,0 +1,94 @@
|
||||
import { Response, Request } from "express";
|
||||
|
||||
/**
|
||||
* Response to a request
|
||||
*
|
||||
* @author Pierre HUBERT
|
||||
*/
|
||||
|
||||
export class RequestHandler {
|
||||
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 "";
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 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 token
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user