GeneIT/geneit_backend/src/models.rs
2023-06-21 17:35:07 +02:00

119 lines
2.6 KiB
Rust

use crate::schema::{families, memberships, users};
use diesel::prelude::*;
/// User ID holder
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct UserID(pub i32);
#[derive(Queryable, Debug, serde::Serialize)]
pub struct User {
id: i32,
pub name: String,
pub email: String,
#[serde(skip_serializing)]
pub password: Option<String>,
pub time_create: i64,
#[serde(skip_serializing)]
pub reset_password_token: Option<String>,
#[serde(skip_serializing)]
pub time_gen_reset_token: i64,
#[serde(skip_serializing)]
pub delete_account_token: Option<String>,
#[serde(skip_serializing)]
pub time_gen_delete_account_token: i64,
pub time_activate: i64,
pub active: bool,
pub admin: bool,
}
impl User {
pub fn id(&self) -> UserID {
UserID(self.id)
}
pub fn check_password(&self, password: &str) -> bool {
self.password
.as_deref()
.map(|hash| {
bcrypt::verify(password, hash).unwrap_or_else(|e| {
log::error!("Failed to validate password! {}", e);
false
})
})
.unwrap_or(false)
}
}
#[derive(Insertable)]
#[diesel(table_name = users)]
pub struct NewUser<'a> {
pub name: &'a str,
pub email: &'a str,
pub time_create: i64,
}
/// Family ID holder
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct FamilyID(pub i32);
#[derive(Queryable, Debug, serde::Serialize)]
pub struct Family {
id: i32,
pub time_create: i64,
pub name: String,
pub invitation_code: String,
}
impl Family {
pub fn id(&self) -> FamilyID {
FamilyID(self.id)
}
}
#[derive(Insertable)]
#[diesel(table_name = families)]
pub struct NewFamily<'a> {
pub name: &'a str,
pub invitation_code: String,
pub time_create: i64,
}
#[derive(Queryable, Debug, serde::Serialize)]
pub struct Membership {
user_id: i32,
family_id: i32,
pub time_create: i64,
pub is_admin: bool,
}
impl Membership {
pub fn user_id(&self) -> UserID {
UserID(self.user_id)
}
pub fn family_id(&self) -> FamilyID {
FamilyID(self.family_id)
}
}
#[derive(Insertable)]
#[diesel(table_name = memberships)]
pub struct NewMembership {
pub user_id: i32,
pub family_id: i32,
pub time_create: i64,
pub is_admin: bool,
}
#[derive(Queryable, Debug, serde::Serialize)]
pub struct FamilyMembership {
user_id: i32,
family_id: i32,
name: String,
time_create: i64,
pub is_admin: bool,
invitation_code: String,
pub count_members: i64,
pub count_admins: i64,
}