added database

This commit is contained in:
wt committed 2025-08-22 17:46:38 +07:00
1 parent c4ea7a4293
commit 4f67cf11bd
30 files changed
+601 -267

No files matched your search

+22 -3
View File
@@ -1,5 +1,5 @@
#include "user.h"
#include "jwt.h"
#include "user.h"
void get_token(struct mg_connection *c, struct mg_http_message *hm) {
if (hm->body.len == 0) {
@@ -20,9 +20,28 @@ void get_token(struct mg_connection *c, struct mg_http_message *hm) {
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, "", "{%m:%m}", MG_ESC("error"),
MG_ESC("couldn't find user"));
return;
}
if (strcmp(db_user->password, password->valuestring)) {
mg_http_reply(c, 400, "", "{%m:%m}", MG_ESC("error"),
MG_ESC("wrong password"));
return;
}
const char *header = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
const char *payload = "{\"sub\": \"1234567890\",\"username\": "
"\"tola\",\"is_superuser\": true,\"iat\": 1516239022}";
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, "", "{%m:%m}", MG_ESC("token"), MG_ESC(token));
free_user(db_user);
free(token);
}