forked from TWS/kalkutago
Compare commits
No commits in common. "01004e237b644ab51ff6183a868a971a74e7d806" and "cf8380db3593180103d94cdf1c554ed3173f9b71" have entirely different histories.
01004e237b
...
cf8380db35
|
@ -1,8 +1,5 @@
|
|||
|
||||
|
||||
use derive_deref::Deref;
|
||||
use either::Either::{self, Right};
|
||||
|
||||
use log::warn;
|
||||
use rocket::{
|
||||
http::{Cookie, CookieJar, Status},
|
||||
outcome::IntoOutcome,
|
||||
|
@ -19,8 +16,6 @@ use crate::{
|
|||
error::Error,
|
||||
};
|
||||
|
||||
use super::ErrorResponder;
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub(super) struct LoginData {
|
||||
name: String,
|
||||
|
@ -32,22 +27,22 @@ pub(super) async fn login(
|
|||
db: &State<DatabaseConnection>,
|
||||
user_data: Json<LoginData>,
|
||||
cookies: &CookieJar<'_>,
|
||||
) -> Result<Status, Either<Status, ErrorResponder>> {
|
||||
let user = Users::find()
|
||||
.filter(users::Column::Name.eq(&user_data.name))
|
||||
.one(db as &DatabaseConnection)
|
||||
) -> ApiResult<Status> {
|
||||
let users = User::find()
|
||||
.filter(user::Column::Name.eq(&user_data.name))
|
||||
.all(db as &DatabaseConnection)
|
||||
.await
|
||||
.map_err(|err| Right(Error::from(err).into()))?;
|
||||
let Some(user) = user else {
|
||||
info!(name = user_data.name; "no user found with the given name");
|
||||
.map_err(Error::from)?;
|
||||
if users.len() > 1 {
|
||||
warn!(count = users.len(), name = &user_data.name; "multiple entries found in database for user");
|
||||
}
|
||||
let Some(user) = users.get(0) else {
|
||||
return Ok(Status::Unauthorized);
|
||||
};
|
||||
let user = user.check_password(&user_data.password)?;
|
||||
cookies.add_private(Cookie::new(
|
||||
"user",
|
||||
serde_json::to_string(&user).map_err(|err| Right(Error::from(err).into()))?,
|
||||
serde_json::to_string(&user).map_err(Error::from)?,
|
||||
));
|
||||
cookies.add(Cookie::new("name", user.name));
|
||||
Ok(Status::Ok)
|
||||
}
|
||||
|
||||
|
@ -57,7 +52,7 @@ pub(super) async fn sign_up(
|
|||
user_data: Json<LoginData>,
|
||||
cookies: &CookieJar<'_>,
|
||||
) -> ApiResult<()> {
|
||||
let user_data = users::ActiveModel::new(&user_data.name, &user_data.password)?
|
||||
let user_data = user::ActiveModel::new(&user_data.name, &user_data.password)?
|
||||
.insert(db as &DatabaseConnection)
|
||||
.await
|
||||
.map_err(Error::from)?;
|
||||
|
@ -65,13 +60,12 @@ pub(super) async fn sign_up(
|
|||
"user",
|
||||
serde_json::to_string(&user_data).map_err(Error::from)?,
|
||||
));
|
||||
cookies.add(Cookie::new("name", user_data.name));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Authentication guard
|
||||
#[derive(Deref)]
|
||||
pub(super) struct Auth(users::Model);
|
||||
pub(super) struct Auth(user::Model);
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for Auth {
|
||||
|
@ -83,7 +77,7 @@ impl<'r> FromRequest<'r> for Auth {
|
|||
};
|
||||
serde_json::from_str(user.value())
|
||||
.ok()
|
||||
.map(Auth)
|
||||
.map(|user| Auth(user))
|
||||
.into_outcome(unauthorized)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::default::default;
|
||||
|
||||
use crate::api::auth::Auth;
|
||||
use crate::api::{self, error::ApiResult};
|
||||
|
@ -8,7 +8,7 @@ use crate::error::Error;
|
|||
use either::Either::{self, Left, Right};
|
||||
use rocket::http::Status;
|
||||
use rocket::{serde::json::Json, State};
|
||||
use sea_orm::{prelude::*, DatabaseConnection, IntoActiveModel, Statement};
|
||||
use sea_orm::{prelude::*, DatabaseConnection, IntoActiveModel, Statement, TryIntoModel};
|
||||
use tokio::sync::broadcast::Sender;
|
||||
|
||||
use super::update::Update;
|
||||
|
@ -31,7 +31,7 @@ pub(super) async fn all_tracks(
|
|||
async fn get_track_check_user(
|
||||
db: &DatabaseConnection,
|
||||
track_id: i32,
|
||||
user: &users::Model,
|
||||
user: &user::Model,
|
||||
) -> Result<Json<tracks::Model>, Either<Status, api::ErrorResponder>> {
|
||||
if let Some(Some(user)) = user
|
||||
.find_related(Tracks)
|
||||
|
@ -53,7 +53,7 @@ pub(super) async fn track(
|
|||
id: i32,
|
||||
auth: Auth,
|
||||
) -> Result<Json<tracks::Model>, Either<Status, api::ErrorResponder>> {
|
||||
get_track_check_user(db, id, &auth).await
|
||||
get_track_check_user(db, id, &*auth).await
|
||||
}
|
||||
|
||||
#[get("/<id>/ticks")]
|
||||
|
@ -63,7 +63,7 @@ pub(super) async fn ticks_for_track(
|
|||
auth: Auth,
|
||||
) -> Result<Json<Vec<ticks::Model>>, Either<Status, api::ErrorResponder>> {
|
||||
let db = db as &DatabaseConnection;
|
||||
let track = get_track_check_user(db, id, &auth).await?;
|
||||
let track = get_track_check_user(db, id, &*auth).await?;
|
||||
let result = track.find_related(Ticks).all(db).await;
|
||||
match result {
|
||||
Ok(ticks) => Ok(Json(ticks)),
|
||||
|
@ -81,48 +81,40 @@ pub(super) async fn insert_track(
|
|||
fn bad() -> Either<Status, ErrorResponder> {
|
||||
Left(Status::BadRequest)
|
||||
}
|
||||
fn bad_value_for(key: &'static str) -> impl Fn() -> Either<Status, ErrorResponder> {
|
||||
move || {
|
||||
warn!(key = key; "bad value");
|
||||
bad()
|
||||
}
|
||||
}
|
||||
let track = track.0.as_object().ok_or_else(|| {
|
||||
warn!("received value was not an object");
|
||||
bad()
|
||||
})?;
|
||||
let track = track.0.as_object().ok_or_else(bad)?;
|
||||
let Some(track_id) = db
|
||||
.query_one(Statement::from_sql_and_values(
|
||||
sea_orm::DatabaseBackend::Postgres,
|
||||
r#"with track_insertion as (
|
||||
insert into tracks (name, description, icon, enabled,
|
||||
multiple_entries_per_day, color, "order"
|
||||
"insert into $1 (user_id, track_id) values (
|
||||
$2, (
|
||||
insert into $3 (
|
||||
name, description, icon, enabled, multiple_entries_per_day,
|
||||
color, order
|
||||
) values (
|
||||
$2, $3, $4, $5, $6, $7, $8
|
||||
$4, $5, $6, $7, $8, $9, $10,
|
||||
) returning id
|
||||
)
|
||||
insert into user_tracks (
|
||||
user_id, track_id
|
||||
) select $1, ti.id
|
||||
from track_insertion ti
|
||||
join track_insertion using (id);"#,
|
||||
) returning track_id;",
|
||||
[
|
||||
user_tracks::Entity::default().table_name().into(),
|
||||
auth.id.into(),
|
||||
track.get("name").ok_or_else(bad_value_for("name"))?.as_str().ok_or_else(bad_value_for("name"))?.into(),
|
||||
tracks::Entity::default().table_name().into(),
|
||||
track.get("name").ok_or_else(bad)?.as_str().ok_or_else(bad)?.into(),
|
||||
track
|
||||
.get("description")
|
||||
.ok_or_else(bad_value_for("description"))?
|
||||
.ok_or_else(bad)?
|
||||
.as_str()
|
||||
.ok_or_else(bad_value_for("description"))?
|
||||
.ok_or_else(bad)?
|
||||
.into(),
|
||||
track.get("icon").ok_or_else(bad_value_for("icon"))?.as_str().ok_or_else(bad_value_for("icon"))?.into(),
|
||||
track.get("enabled").and_then(|it| it.as_i64()).into(),
|
||||
track.get("icon").ok_or_else(bad)?.as_str().ok_or_else(bad)?.into(),
|
||||
track.get("enabled").ok_or_else(bad)?.as_i64().into(),
|
||||
track
|
||||
.get("multiple_entries_per_day")
|
||||
.and_then(|it| it.as_i64())
|
||||
.ok_or_else(bad)?
|
||||
.as_i64()
|
||||
.into(),
|
||||
track.get("color").and_then(|it| it.as_i64()).into(),
|
||||
track.get("order").and_then(|it| it.as_i64()).into(),
|
||||
track.get("color").ok_or_else(bad)?.as_i64().into(),
|
||||
track.get("order").ok_or_else(bad)?.as_i64().into(),
|
||||
],
|
||||
))
|
||||
.await
|
||||
|
@ -194,7 +186,7 @@ pub(super) async fn ticked(
|
|||
.insert(db as &DatabaseConnection)
|
||||
.await
|
||||
.map_err(|err| Right(Error::from(err).into()))?
|
||||
;
|
||||
.to_owned();
|
||||
tx.send(Update::tick_added(tick.clone()))
|
||||
.map_err(|err| Right(Error::from(err).into()))?;
|
||||
Ok(Json(tick))
|
||||
|
@ -222,7 +214,7 @@ pub(super) async fn ticked_on_date(
|
|||
.insert(db as &DatabaseConnection)
|
||||
.await
|
||||
.map_err(Error::from)?
|
||||
;
|
||||
.to_owned();
|
||||
tx.send(Update::tick_added(tick.clone()))
|
||||
.map_err(Error::from)?;
|
||||
Ok(Left(Json(tick)))
|
||||
|
@ -250,7 +242,7 @@ pub(super) async fn clear_all_ticks(
|
|||
.map_err(Error::from)?;
|
||||
for tick in ticks.clone() {
|
||||
tick.clone().delete(db).await.map_err(Error::from)?;
|
||||
Update::tick_cancelled(tick).send(tx)?;
|
||||
Update::tick_cancelled(tick).send(&tx)?;
|
||||
}
|
||||
Ok(Right(Json(ticks)))
|
||||
}
|
||||
|
@ -279,7 +271,7 @@ pub(super) async fn clear_all_ticks_on_day(
|
|||
.map_err(Error::from)?;
|
||||
for tick in ticks.clone() {
|
||||
tick.clone().delete(db).await.map_err(Error::from)?;
|
||||
Update::tick_cancelled(tick).send(tx)?;
|
||||
Update::tick_cancelled(tick).send(&tx)?;
|
||||
}
|
||||
Ok(Right(Json(ticks)))
|
||||
}
|
||||
|
|
|
@ -6,5 +6,5 @@ pub mod groups;
|
|||
pub mod ticks;
|
||||
pub mod track2_groups;
|
||||
pub mod tracks;
|
||||
pub mod user;
|
||||
pub mod user_tracks;
|
||||
pub mod users;
|
||||
|
|
|
@ -4,5 +4,5 @@ pub use super::groups::Entity as Groups;
|
|||
pub use super::ticks::Entity as Ticks;
|
||||
pub use super::track2_groups::Entity as Track2Groups;
|
||||
pub use super::tracks::Entity as Tracks;
|
||||
pub use super::user::Entity as User;
|
||||
pub use super::user_tracks::Entity as UserTracks;
|
||||
pub use super::users::Entity as Users;
|
||||
|
|
|
@ -46,9 +46,9 @@ impl Related<super::user_tracks::Entity> for Entity {
|
|||
}
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
impl Related<super::user::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
super::user_tracks::Relation::Users.def()
|
||||
super::user_tracks::Relation::User.def()
|
||||
}
|
||||
fn via() -> Option<RelationDef> {
|
||||
Some(super::user_tracks::Relation::Tracks.def().rev())
|
||||
|
|
|
@ -5,7 +5,7 @@ use std::default::default;
|
|||
use bcrypt::*;
|
||||
// TODO Add option for argon2 https://docs.rs/argon2/latest/argon2/
|
||||
use either::Either::{self, Left, Right};
|
||||
use rocket::http::Status;
|
||||
use rocket::response::status::Unauthorized;
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
|
@ -17,7 +17,7 @@ use crate::{
|
|||
use super::tracks;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "users")]
|
||||
#[sea_orm(table_name = "user")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
#[serde(skip_deserializing)]
|
||||
|
@ -43,7 +43,7 @@ impl Related<super::tracks::Entity> for Entity {
|
|||
}
|
||||
|
||||
fn via() -> Option<RelationDef> {
|
||||
Some(super::user_tracks::Relation::Users.def().rev())
|
||||
Some(super::user_tracks::Relation::User.def().rev())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -65,11 +65,11 @@ impl ActiveModel {
|
|||
impl Model {
|
||||
pub fn check_password(
|
||||
self,
|
||||
password: impl AsRef<[u8]>,
|
||||
) -> std::result::Result<Self, Either<Status, ErrorResponder>> {
|
||||
password: String,
|
||||
) -> std::result::Result<Self, Either<Unauthorized<()>, ErrorResponder>> {
|
||||
match verify(password, &self.password_hash) {
|
||||
Ok(true) => Ok(self),
|
||||
Ok(false) => Err(Left(Status::Unauthorized)),
|
||||
Ok(false) => Err(Left(Unauthorized(None))),
|
||||
Err(err) => Err(Right(Error::from(err).into())),
|
||||
}
|
||||
}
|
|
@ -22,13 +22,13 @@ pub enum Relation {
|
|||
)]
|
||||
Tracks,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
belongs_to = "super::user::Entity",
|
||||
from = "Column::UserId",
|
||||
to = "super::users::Column::Id",
|
||||
to = "super::user::Column::Id",
|
||||
on_update = "NoAction",
|
||||
on_delete = "NoAction"
|
||||
)]
|
||||
Users,
|
||||
User,
|
||||
}
|
||||
|
||||
impl Related<super::tracks::Entity> for Entity {
|
||||
|
@ -37,9 +37,9 @@ impl Related<super::tracks::Entity> for Entity {
|
|||
}
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
impl Related<super::user::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Users.def()
|
||||
Relation::User.def()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -9,17 +9,17 @@ impl MigrationTrait for Migration {
|
|||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(Users::Table)
|
||||
.table(User::Table)
|
||||
.if_not_exists()
|
||||
.col(
|
||||
ColumnDef::new(Users::Id)
|
||||
ColumnDef::new(User::Id)
|
||||
.integer()
|
||||
.not_null()
|
||||
.auto_increment()
|
||||
.primary_key(),
|
||||
)
|
||||
.col(ColumnDef::new(Users::Name).string().unique_key().not_null())
|
||||
.col(ColumnDef::new(Users::PasswordHash).string().not_null())
|
||||
.col(ColumnDef::new(User::Name).string().not_null())
|
||||
.col(ColumnDef::new(User::PasswordHash).string().not_null())
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
|
@ -27,14 +27,14 @@ impl MigrationTrait for Migration {
|
|||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(Users::Table).to_owned())
|
||||
.drop_table(Table::drop().table(User::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Learn more at https://docs.rs/sea-query#iden
|
||||
#[derive(Iden)]
|
||||
pub(crate) enum Users {
|
||||
pub(crate) enum User {
|
||||
Table,
|
||||
Id,
|
||||
Name,
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use super::{
|
||||
m20230606_000001_create_tracks_table::Tracks, m20230626_083036_create_users_table::Users,
|
||||
m20230606_000001_create_tracks_table::Tracks, m20230626_083036_create_users_table::User,
|
||||
};
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
|
@ -27,7 +27,7 @@ impl MigrationTrait for Migration {
|
|||
ForeignKey::create()
|
||||
.name("fk-user_tracks-user_id")
|
||||
.from(UserTracks::Table, UserTracks::UserId)
|
||||
.to(Users::Table, Users::Id),
|
||||
.to(User::Table, User::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKey::create()
|
||||
|
|
Loading…
Reference in a new issue