48 lines
1.9 KiB
C
48 lines
1.9 KiB
C
#include "jwt.h"
|
|
#include "user.h"
|
|
|
|
void get_token(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 username and password"));
|
|
return;
|
|
}
|
|
cJSON *jsonbody = cJSON_Parse(hm->body.buf);
|
|
cJSON *username = cJSON_GetObjectItem(jsonbody, "username");
|
|
cJSON *password = cJSON_GetObjectItem(jsonbody, "password");
|
|
if (username == NULL || password == NULL) {
|
|
const char *error_ptr = cJSON_GetErrorPtr();
|
|
if (error_ptr != NULL) {
|
|
mg_http_reply(c, 400, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"), MG_ESC(error_ptr));
|
|
return;
|
|
}
|
|
mg_http_reply(c, 400, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
|
|
MG_ESC("must have username and password"));
|
|
return;
|
|
}
|
|
User *db_user = db_get_user_by_username(username->valuestring);
|
|
if (!db_user) {
|
|
mg_http_reply(c, 400, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
|
|
MG_ESC("couldn't find user"));
|
|
return;
|
|
}
|
|
if (strcmp(db_user->password, password->valuestring)) {
|
|
mg_http_reply(c, 400, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("error"),
|
|
MG_ESC("wrong password"));
|
|
return;
|
|
}
|
|
const char *header = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
|
|
char payload[1024];
|
|
snprintf(payload, sizeof(payload),
|
|
"{\"id\": %d,\"username\": "
|
|
"\"%s\",\"email\": "
|
|
"\"%s\",\"group\": "
|
|
"\"%s\",\"is_superuser\": %s}",
|
|
db_user->id, db_user->username, db_user->email, db_user->group,
|
|
db_user->is_superuser ? "true" : "false");
|
|
char *token = jwt_createJWT(header, payload, JWT_DEFAULT_SECRET);
|
|
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "{%m:%m}", MG_ESC("token"), MG_ESC(token));
|
|
free_user(db_user);
|
|
free(token);
|
|
}
|