Files
auth_service_c/src/add_user.c
T

57 lines
2.3 KiB
C

#include "jwt.h"
#include "user.h"
#include "utils.h"
void add_user(struct mg_connection *c, struct mg_http_message *hm) {
request_with_token *requestdata = check_body(hm);
const bool valid = jwt_verifyJWT(requestdata->token, JWT_DEFAULT_SECRET);
if (!valid) {
mg_http_reply(c, 403, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
MG_ESC("invalid token"));
return;
}
cJSON *jsonbody = cJSON_Parse(hm->body.buf);
cJSON *username = cJSON_GetObjectItem(jsonbody, "username");
cJSON *password = cJSON_GetObjectItem(jsonbody, "password");
cJSON *email = cJSON_GetObjectItem(jsonbody, "email");
cJSON *group = cJSON_GetObjectItem(jsonbody, "group");
cJSON *is_superuser = cJSON_GetObjectItem(jsonbody, "is_superuser");
if (username == nullptr || password == nullptr || email == nullptr ||
is_superuser == nullptr || group == nullptr) {
mg_http_reply(c, 400, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
MG_ESC("must have <username>, <password>, <email>, <group, "
"optional>, <is_superuser, optional>"));
return;
}
cJSON *payload = jwt_get_payload(requestdata->token);
bool jwt_is_superuser =
cJSON_GetObjectItem(payload, "is_superuser")->valueint;
if (!jwt_is_superuser) {
mg_http_reply(c, 403, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
MG_ESC("not authorized"));
cJSON_Delete(payload);
return;
}
const bool user_is_superuser = is_superuser->valueint ? true : false;
User *new_db_user = db_insert_user(
username->valuestring, email->valuestring, password->valuestring,
group->valuestring,
&user_is_superuser);
if (!new_db_user) {
mg_http_reply(c, 500, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
MG_ESC("failed to create user"));
cJSON_Delete(payload);
return;
}
char responsedata[2048] = {0};
snprintf(responsedata, sizeof(responsedata),
"{\"username\":\"%s\",\"email\":\"%s\",\"group\":\"%s\",\"is_"
"superuser\":%s}",
username->valuestring, email->valuestring, group->valuestring,
is_superuser->valueint ? "true" : "false");
mg_http_reply(c, 200, "Content-Type: application/json\r\n", responsedata);
cJSON_Delete(payload);
}