parent
b53b5cf91f
commit
7c5a3893ef
|
@ -0,0 +1,41 @@
|
|||
import * as argon2 from "argon2";
|
||||
import { Request, Response } from 'express';
|
||||
import { getConnectionManager } from 'typeorm';
|
||||
import { StatsClient } from '../models/entities/StatsClient';
|
||||
|
||||
/**
|
||||
* This middleware handels the authentification of stats client api tokens.
|
||||
* The tokens have to be provided via Bearer auth header.
|
||||
* @param req Express request object.
|
||||
* @param res Express response object.
|
||||
* @param next Next function to call on success.
|
||||
*/
|
||||
const StatsAuth = async (req: Request, res: Response, next: () => void) => {
|
||||
let provided_token: string = req.headers["authorization"];
|
||||
if (provided_token == "" || provided_token === undefined || provided_token === null) {
|
||||
res.status(401).send("No api token provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
let prefix = "";
|
||||
try {
|
||||
provided_token = provided_token.replace("Bearer ", "");
|
||||
prefix = provided_token.split(".")[0];
|
||||
} catch (error) {
|
||||
res.status(401).send("Api token non-existant or invalid syntax.");
|
||||
return;
|
||||
}
|
||||
|
||||
const client = await getConnectionManager().get().getRepository(StatsClient).findOne({ prefix: prefix });
|
||||
if (!client) {
|
||||
res.status(401).send("Api token non-existant or invalid syntax.");
|
||||
return;
|
||||
}
|
||||
if (!(await argon2.verify(client.key, provided_token))) {
|
||||
res.status(401).send("Api token invalid.");
|
||||
return;
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
export default StatsAuth;
|
Loading…
Reference in New Issue