Files
auth_service_c/src/get_user.c
T
wt 194d12e010
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-Make (push) Failing after 13s
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-CMake (push) Failing after 10s
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-Meson (push) Failing after 10s
updated tests and fix some errors
2025-08-27 13:21:54 +07:00

47 lines
1.7 KiB
C

#include "jwt.h"
#include "user.h"
#include "utils.h"
void get_user(struct mg_connection *c, struct mg_http_message *hm) {
if (hm->body.len == 0) {
mg_http_reply(c, 400, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
MG_ESC("must have token"));
return;
}
request_with_token *requestdata = check_body(hm);
if (requestdata->error != NULL) {
mg_http_reply(c, 403, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"), MG_ESC(requestdata->error));
return;
}
if (!jwt_verifyJWT(requestdata->token, JWT_DEFAULT_SECRET)) {
free_request_with_token(requestdata);
mg_http_reply(c, 403, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
MG_ESC("invalid token"));
return;
}
cJSON *payload = jwt_get_payload(requestdata->token);
char *username =
strdup(cJSON_GetObjectItem(payload, "username")->valuestring);
User *user = db_get_user_by_username(username);
if (!user) {
free_request_with_token(requestdata);
cJSON_Delete(payload);
free(username);
mg_http_reply(c, 404, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
MG_ESC("user not found"));
return;
}
char responsedata[2048] = {0};
snprintf(responsedata, sizeof(responsedata),
"{\"id\": %d, \"username\": \"%s\", \"email\": \"%s\", \"group\": "
"\"%s\", \"is_superuser\": %s}",
user->id, user->username, user->email, user->group,
user->is_superuser ? "true" : "false");
mg_http_reply(c, 200, "Content-Type: application/json\r\n", responsedata);
free_request_with_token(requestdata);
free(username);
free_user(user);
cJSON_Delete(payload);
}