feat: add user and session entities

image-uploads
Jef Roosens 2025-01-11 16:40:55 +01:00
parent f51b6ce3b3
commit a65b647f65
No known key found for this signature in database
GPG Key ID: 21FD3D77D56BAF49
3 changed files with 60 additions and 0 deletions

View File

@ -1,6 +1,7 @@
mod comment;
mod event;
mod plant;
mod user;
use r2d2_sqlite::{rusqlite, SqliteConnectionManager};

45
src/db/user.rs 100644
View File

@ -0,0 +1,45 @@
use rusqlite::Row;
use serde::{Deserialize, Serialize};
use super::{DbError, DbPool};
#[derive(Serialize, Deserialize)]
pub struct User {
id: i32,
username: String,
password_hash: String,
admin: bool,
}
#[derive(Serialize, Deserialize)]
pub struct NewUser {
username: String,
password: String,
admin: bool,
}
impl User {
pub fn from_row(row: &Row<'_>) -> Result<Self, rusqlite::Error> {
Ok(Self {
id: row.get("id")?,
username: row.get("username")?,
password_hash: row.get("password_hash")?,
admin: row.get("admin")?,
})
}
}
impl NewUser {
pub fn insert(self, pool: &DbPool) -> Result<User, DbError> {
let conn = pool.get()?;
let mut stmt = conn.prepare(
"insert into users (username, password_hash, admin) values ($1, $2, $3) returning *",
)?;
Ok(stmt.query_row(
(&self.username, &self.password, &self.admin),
User::from_row,
)?)
}
}

View File

@ -0,0 +1,14 @@
create table users (
id integer primary key,
username text unique not null,
password_hash text not null,
admin boolean not null
);
create table sessions (
id integer primary key,
user_id integer not null
references users (id)
on delete cascade,
unique (id, user_id)
);