From 43e256f38c216b0136dd9b6fb41a73f98047d110 Mon Sep 17 00:00:00 2001 From: Nicolai Ort Date: Wed, 30 Dec 2020 14:19:54 +0100 Subject: [PATCH] Impelemented stats api auth via token or the usual auth (jwt with get for runners, teams and orgs). ref #56 --- src/middlewares/StatsAuth.ts | 44 ++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/src/middlewares/StatsAuth.ts b/src/middlewares/StatsAuth.ts index e9e4aaf..990206b 100644 --- a/src/middlewares/StatsAuth.ts +++ b/src/middlewares/StatsAuth.ts @@ -2,6 +2,7 @@ import * as argon2 from "argon2"; import { Request, Response } from 'express'; import { getConnectionManager } from 'typeorm'; import { StatsClient } from '../models/entities/StatsClient'; +import authchecker from './authchecker'; /** * This middleware handels the authentification of stats client api tokens. @@ -17,25 +18,48 @@ const StatsAuth = async (req: Request, res: Response, next: () => void) => { 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."); + res.status(401).send("No valid jwt or api token provided."); return; } + let prefix = ""; + try { + prefix = provided_token.split(".")[0]; + } + finally { + if (prefix == "" || prefix == undefined || prefix == null) { + 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; + let user_authorized = false; + try { + let action = { request: req, response: res, context: null, next: next } + user_authorized = await authchecker(action, ["RUNNER:GET", "TEAM:GET", "ORGANISATION:GET"]); + } + finally { + if (user_authorized == false) { + res.status(401).send("Api token non-existant or invalid syntax."); + return; + } + else { + next(); + } + } } + else { + if (!(await argon2.verify(client.key, provided_token))) { + res.status(401).send("Api token invalid."); + return; + } - next(); + next(); + } } export default StatsAuth; \ No newline at end of file