summaryrefslogtreecommitdiffstats
path: root/src/bin/server/database.rs
blob: 9c5199749772c814c322813f134c207a8950ade4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
use rusqlite::Connection;

pub fn init_db() -> Connection {
    let conn = Connection::open("server.db").unwrap();
    conn.execute(
        "CREATE TABLE IF NOT EXISTS users (
            username TEXT PRIMARY KEY,
            hashed_password TEXT NOT NULL
        )",
        [],
    ).unwrap();
    conn
}

pub fn add_user(conn: &Connection, username: &str, hashed_password: &str) -> Result<(), Box<dyn std::error::Error>> {
    conn.execute(
        "INSERT INTO users (username, hashed_password) VALUES (?1, ?2)",
        [username, hashed_password],
    )?;
    Ok(())
}

pub fn get_hashed_password(conn: &Connection, username: &str) -> Option<String> {
    let mut stmt = conn.prepare("SELECT hashed_password FROM users WHERE username = ?1").unwrap();
    let mut rows = stmt.query([username]).unwrap();
    if let Ok(Some(row)) = rows.next() {
        row.get(0).ok()
    } else {
        None
    }
}