factoriauth/src/db.rs

85 lines
2.2 KiB
Rust
Raw Normal View History

2024-02-10 13:07:36 +01:00
use secrecy::ExposeSecret;
2024-02-10 12:25:46 +01:00
use sqlx::{query, query_as, Connection, SqliteConnection};
2024-02-10 12:06:53 +01:00
2024-02-10 12:32:01 +01:00
use crate::secrets::UserToken;
2024-02-10 12:06:53 +01:00
// TODO: allow configuring this via envar
const DB_URI_DEFAULT: &str = "sqlite://sqlite.db";
2024-02-10 13:07:36 +01:00
const TABLE_USER_TOKENS: &str = "user_tokens";
2024-02-10 12:06:53 +01:00
pub trait Database {
2024-02-10 12:25:46 +01:00
async fn get_token(&mut self, username: &str) -> Result<UserToken, sqlx::Error>;
2024-02-10 13:07:36 +01:00
async fn save_token(&mut self, username: &str, token: &UserToken) -> Result<(), sqlx::Error>;
2024-02-10 12:06:53 +01:00
}
#[derive(Debug)]
pub struct SqliteDatabase {
conn: SqliteConnection,
}
impl SqliteDatabase {
pub async fn open() -> Self {
let mut db = Self {
conn: SqliteConnection::connect(DB_URI_DEFAULT)
.await
.expect("Failed to open SQLite database"),
};
db.init().await;
db
}
pub async fn init(&mut self) {
query(
2024-02-10 13:07:36 +01:00
"CREATE TABLE IF NOT EXISTS {TABLE_USER_TOKENS} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
2024-02-10 12:06:53 +01:00
username VARCHAR(255),
token NCHAR(30),
created DATETIME,
valid BOOLEAN,
);",
)
.execute(&mut self.conn)
.await
.expect("Failed to initialize table user_tokens");
}
}
impl Database for SqliteDatabase {
2024-02-10 12:25:46 +01:00
async fn get_token(&mut self, username: &str) -> Result<UserToken, sqlx::Error> {
let row: (String,) = query_as(
"SELECT token
FROM user_tokens
WHERE
2024-02-10 13:07:36 +01:00
username = ?
2024-02-10 12:25:46 +01:00
AND valid = TRUE
ORDER BY
created DESC",
)
.bind(username)
.fetch_one(&mut self.conn)
.await?;
Ok(UserToken::from(row.0))
2024-02-10 12:06:53 +01:00
}
2024-02-10 13:07:36 +01:00
async fn save_token(&mut self, username: &str, token: &UserToken) -> Result<(), sqlx::Error> {
query(
"INSERT INTO {TABLE_USER_TOKENS}
(username, token, created, valid)
VALUES
(?, ?, DATETIME('NOW'), TRUE)
",
)
.bind(username)
.bind(token.0.expose_secret())
.execute(&mut self.conn)
.await?;
Ok(())
}
2024-02-10 12:06:53 +01:00
}