Account *accountGetBySId(sqlite3 *DB, char *sid) { if (sid == NULL) return NULL; Session *session = sessionGetBySId(DB, sid); if (session == NULL) return NULL; Account *account = NULL; sqlite3_stmt *statement; if (sqlite3_prepare_v2(DB, "SELECT id, createdAt, name, email, username" " FROM accounts" " WHERE id = ?", -1, &statement, NULL) != SQLITE_OK) { return NULL; } if (sqlite3_bind_int(statement, 1, session->accountId) != SQLITE_OK) goto fail; if (sqlite3_step(statement) != SQLITE_ROW) goto fail; account = accountNew(sqlite3_column_int(statement, 0), sqlite3_column_int(statement, 1), (char *)sqlite3_column_text(statement, 2), (char *)sqlite3_column_text(statement, 3), (char *)sqlite3_column_text(statement, 4)); fail: sessionDel(session); sqlite3_finalize(statement); return account; }
Session *sessionCreate(sqlite3 *DB, char *username, char *password) { int aid; char *sid = NULL; Session *session = NULL; sqlite3_stmt *statement; if (sqlite3_prepare_v2(DB, "SELECT id" " FROM accounts" " WHERE username = ?" " AND password = ?", -1, &statement, NULL) != SQLITE_OK) { return NULL; } if (sqlite3_bind_text(statement, 1, username, -1, NULL) != SQLITE_OK) goto fail; if (sqlite3_bind_text(statement, 2, password, -1, NULL) != SQLITE_OK) goto fail; if (sqlite3_step(statement) != SQLITE_ROW) goto fail; sid = bsRandom(24, username); aid = sqlite3_column_int(statement, 0); sqlite3_finalize(statement); if (sqlite3_prepare_v2(DB, "INSERT INTO sessions(createdAt, account, session)" " VALUES ( ?, ?, ?)", -1, &statement, NULL) != SQLITE_OK) { goto fail; } if (sqlite3_bind_int(statement, 1, time(NULL)) != SQLITE_OK) goto fail; if (sqlite3_bind_int(statement, 2, aid) != SQLITE_OK) goto fail; if (sqlite3_bind_text(statement, 3, sid, -1, NULL) != SQLITE_OK) goto fail; if (sqlite3_step(statement) != SQLITE_DONE) goto fail; session = sessionGetBySId(DB, sid); fail: if (sid) bsDel(sid); sqlite3_finalize(statement); return session; }