From 1e42dc04dc099088b22a2592639580fb9e9e5b27 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Mon, 29 May 2023 23:37:23 +0200 Subject: [PATCH] feat: add auth step --- include/http_loop.h | 6 ++++++ src/http_loop/http_loop_tools.c | 18 ++++++++++++++++++ src/lander/lander.c | 3 ++- src/main.c | 1 + 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/include/http_loop.h b/include/http_loop.h index d215ee6..edae126 100644 --- a/include/http_loop.h +++ b/include/http_loop.h @@ -30,6 +30,7 @@ typedef struct http_loop_gctx { http_route *routes; size_t route_count; Trie *trie; + const char *api_key; } http_loop_gctx; /* @@ -110,6 +111,11 @@ void http_loop_res_add_header(http_loop_ctx *ctx, http_header type, */ bool http_loop_step_body_to_buf(event_loop_conn *conn); +/* + * Authenticate the request using the X-Api-Key header + */ +bool http_loop_step_auth(event_loop_conn *conn); + /** * Initialize a new http loop */ diff --git a/src/http_loop/http_loop_tools.c b/src/http_loop/http_loop_tools.c index c089f7d..fcd2a22 100644 --- a/src/http_loop/http_loop_tools.c +++ b/src/http_loop/http_loop_tools.c @@ -97,3 +97,21 @@ bool http_loop_step_body_to_buf(event_loop_conn *conn) { return ctx->req.body_received == ctx->req.body_len; } + +bool http_loop_step_auth(event_loop_conn *conn) { + http_loop_ctx *ctx = conn->ctx; + + for (size_t i = 0; i < ctx->req.num_headers; i++) { + struct phr_header *header = &ctx->req.headers[i]; + + if ((strncmp("X-Api-Key", header->name, header->name_len) == 0) && + (strncmp(header->value, ctx->g->api_key, header->value_len) == 0)) { + return true; + } + } + + ctx->res.status = http_unauthorized; + conn->state = event_loop_conn_state_res; + + return true; +} diff --git a/src/lander/lander.c b/src/lander/lander.c index af30e71..df76ece 100644 --- a/src/lander/lander.c +++ b/src/lander/lander.c @@ -59,4 +59,5 @@ http_route lander_routes[] = { {.type = http_route_literal, .method = http_post, .path = "/s/", - .steps = {http_loop_step_body_to_buf, lander_post_redirect, NULL}}}; + .steps = {http_loop_step_auth, http_loop_step_body_to_buf, + lander_post_redirect, NULL}}}; diff --git a/src/main.c b/src/main.c index 217f83e..99f6f91 100644 --- a/src/main.c +++ b/src/main.c @@ -21,6 +21,7 @@ int main() { gctx->trie = trie; gctx->routes = lander_routes; gctx->route_count = sizeof(lander_routes) / sizeof(lander_routes[0]); + gctx->api_key = "test"; event_loop *el = http_loop_init(gctx); http_loop_run(el, 8000);