forked from Ruderverein-Donau-Linz/rowt
95 lines
2.7 KiB
Rust
95 lines
2.7 KiB
Rust
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.0
|
|
|
|
use rocket::{
|
|
http::Status,
|
|
request::{self, FromRequest, Outcome},
|
|
Request, State,
|
|
};
|
|
use sea_orm::{entity::prelude::*, Set};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
|
#[sea_orm(table_name = "user")]
|
|
pub struct Model {
|
|
#[sea_orm(primary_key)]
|
|
pub id: i32,
|
|
pub name: String,
|
|
pub pw: Option<String>,
|
|
pub is_cox: bool,
|
|
pub is_admin: bool,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
pub struct AdminUser(Model);
|
|
|
|
impl Model {
|
|
pub async fn find_or_create_user(name: &str, db: &DatabaseConnection) -> Model {
|
|
let user = Entity::find()
|
|
.filter(Column::Name.eq(name))
|
|
.one(db)
|
|
.await
|
|
.unwrap();
|
|
|
|
match user {
|
|
Some(user) => user,
|
|
None => {
|
|
let user = ActiveModel {
|
|
name: Set(name.into()),
|
|
..Default::default()
|
|
};
|
|
log::info!("User {:?} created", user);
|
|
user.insert(db).await.unwrap()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum UserError {
|
|
NoCookieSet,
|
|
NoAdmin,
|
|
}
|
|
|
|
#[rocket::async_trait]
|
|
impl<'r> FromRequest<'r> for Model {
|
|
type Error = UserError;
|
|
|
|
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
|
match req.cookies().get_private("name") {
|
|
Some(name) => {
|
|
let db = req.guard::<&'r State<DatabaseConnection>>();
|
|
let name = name.value();
|
|
let user = Model::find_or_create_user(name, db.await.unwrap().inner()).await;
|
|
Outcome::Success(user)
|
|
}
|
|
None => Outcome::Failure((Status::Unauthorized, UserError::NoCookieSet)),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[rocket::async_trait]
|
|
impl<'r> FromRequest<'r> for AdminUser {
|
|
type Error = UserError;
|
|
|
|
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
|
match req.cookies().get_private("name") {
|
|
Some(name) => {
|
|
let db = req.guard::<&'r State<DatabaseConnection>>();
|
|
let name = name.value();
|
|
let user = Model::find_or_create_user(name, db.await.unwrap().inner()).await;
|
|
if user.is_admin {
|
|
Outcome::Success(AdminUser(user))
|
|
} else {
|
|
Outcome::Failure((Status::Unauthorized, UserError::NoAdmin))
|
|
}
|
|
}
|
|
None => Outcome::Failure((Status::Unauthorized, UserError::NoCookieSet)),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
|
pub enum Relation {}
|
|
|
|
impl ActiveModelBehavior for ActiveModel {}
|