feat: implement auth middleware

This commit is contained in:
Jef Roosens 2025-01-11 17:35:20 +01:00
parent a65b647f65
commit df741c931b
Signed by: Jef Roosens
GPG key ID: 21FD3D77D56BAF49
8 changed files with 211 additions and 6 deletions

View file

@ -1,6 +1,7 @@
mod comment;
mod event;
mod plant;
mod session;
mod user;
use r2d2_sqlite::{rusqlite, SqliteConnectionManager};
@ -10,6 +11,8 @@ use std::{error::Error, fmt};
pub use comment::{Comment, NewComment};
pub use event::{Event, EventType, NewEvent, EVENT_TYPES};
pub use plant::{NewPlant, Plant};
pub use session::Session;
pub use user::{NewUser, User};
pub type DbPool = r2d2::Pool<SqliteConnectionManager>;

19
src/db/session.rs Normal file
View file

@ -0,0 +1,19 @@
use super::{DbError, DbPool, User};
pub struct Session {
id: u64,
user_id: i32,
}
impl Session {
pub fn user_from_id(pool: &DbPool, id: u64) -> Result<Option<super::User>, DbError> {
let conn = pool.get()?;
let mut stmt = conn.prepare("select users.* from sessions inner join users on sessions.user_id = users.id where sessions.id = $1")?;
match stmt.query_row((id,), User::from_row) {
Ok(user) => Ok(Some(user)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(err) => Err(DbError::Db(err)),
}
}
}

View file

@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};
use super::{DbError, DbPool};
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub struct User {
id: i32,
username: String,