feat: add user and session entities
parent
f51b6ce3b3
commit
a65b647f65
|
@ -1,6 +1,7 @@
|
|||
mod comment;
|
||||
mod event;
|
||||
mod plant;
|
||||
mod user;
|
||||
|
||||
use r2d2_sqlite::{rusqlite, SqliteConnectionManager};
|
||||
|
||||
|
|
|
@ -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,
|
||||
)?)
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
);
|
Loading…
Reference in New Issue