feat: add auth step

c-web-server
Jef Roosens 2023-05-29 23:37:23 +02:00
parent 16103f9b24
commit 1e42dc04dc
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
4 changed files with 27 additions and 1 deletions

View File

@ -30,6 +30,7 @@ typedef struct http_loop_gctx {
http_route *routes; http_route *routes;
size_t route_count; size_t route_count;
Trie *trie; Trie *trie;
const char *api_key;
} http_loop_gctx; } 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); 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 * Initialize a new http loop
*/ */

View File

@ -97,3 +97,21 @@ bool http_loop_step_body_to_buf(event_loop_conn *conn) {
return ctx->req.body_received == ctx->req.body_len; 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;
}

View File

@ -59,4 +59,5 @@ http_route lander_routes[] = {
{.type = http_route_literal, {.type = http_route_literal,
.method = http_post, .method = http_post,
.path = "/s/", .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}}};

View File

@ -21,6 +21,7 @@ int main() {
gctx->trie = trie; gctx->trie = trie;
gctx->routes = lander_routes; gctx->routes = lander_routes;
gctx->route_count = sizeof(lander_routes) / sizeof(lander_routes[0]); gctx->route_count = sizeof(lander_routes) / sizeof(lander_routes[0]);
gctx->api_key = "test";
event_loop *el = http_loop_init(gctx); event_loop *el = http_loop_init(gctx);
http_loop_run(el, 8000); http_loop_run(el, 8000);