64 lines
1.8 KiB
C
64 lines
1.8 KiB
C
#include "database.h"
|
|
#include "sql.h"
|
|
#include "user.h"
|
|
|
|
User *db_insert_user(const char *username, const char *email,
|
|
const char *password, const char *group,
|
|
const bool *is_superuser) {
|
|
pthread_mutex_lock(&db_mutex);
|
|
if (!db) {
|
|
fprintf(stderr, "Databse not initialized\n");
|
|
pthread_mutex_unlock(&db_mutex);
|
|
return nullptr;
|
|
}
|
|
if (!username || !email || !password) {
|
|
fprintf(stderr, "username, email, password connot be empty\n");
|
|
pthread_mutex_unlock(&db_mutex);
|
|
return nullptr;
|
|
}
|
|
const char *sql = nullptr;
|
|
sqlite3_stmt *stmt;
|
|
int rc;
|
|
if (!group || !is_superuser) {
|
|
sql = INSERT_USER_USERNAME_EMAIL_PASSWORD_SQL;
|
|
} else if (!group) {
|
|
sql = INSERT_USER_USERNAME_EMAIL_PASSWORD_GROUP_SQL;
|
|
} else {
|
|
sql = INSERT_USER_FULL_SQL;
|
|
}
|
|
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
|
|
if (rc != SQLITE_OK) {
|
|
fprintf(stderr, "Cannot prepare statement: %s\n", sqlite3_errmsg(db));
|
|
pthread_mutex_unlock(&db_mutex);
|
|
return nullptr;
|
|
}
|
|
|
|
sqlite3_bind_text(stmt, 1, username, -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 2, email, -1, SQLITE_STATIC);
|
|
sqlite3_bind_text(stmt, 3, password, -1, SQLITE_STATIC);
|
|
|
|
if (group) {
|
|
sqlite3_bind_text(stmt, 4, group, -1, SQLITE_STATIC);
|
|
}
|
|
if (is_superuser) {
|
|
sqlite3_bind_int(stmt, 5, *is_superuser);
|
|
}
|
|
|
|
rc = sqlite3_step(stmt);
|
|
if (rc != SQLITE_DONE) {
|
|
fprintf(stderr, "Execution failed: %s\n", sqlite3_errmsg(db));
|
|
sqlite3_finalize(stmt);
|
|
pthread_mutex_unlock(&db_mutex);
|
|
return nullptr;
|
|
}
|
|
|
|
int inserted_id = sqlite3_last_insert_rowid(db);
|
|
|
|
sqlite3_finalize(stmt);
|
|
printf("User inserted successfully. ID: %d\n", inserted_id);
|
|
pthread_mutex_unlock(&db_mutex);
|
|
User *new_db_user =
|
|
new_user(inserted_id, username, email, password, group, is_superuser);
|
|
return new_db_user;
|
|
}
|