improve code with clippy

This commit is contained in:
philipp 2023-03-23 10:26:18 +01:00
parent 31258bdf15
commit de35247c76
13 changed files with 47 additions and 2187 deletions

1871
migration/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +0,0 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }
[dependencies.sea-orm-migration]
version = "0.11.0"
features = ["sqlx-sqlite", "runtime-tokio-rustls"]

View File

@ -1,41 +0,0 @@
# Running Migrator CLI
- Generate a new migration file
```sh
cargo run -- migrate generate MIGRATION_NAME
```
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

View File

@ -1,18 +0,0 @@
pub use sea_orm_migration::prelude::*;
mod m20230208_114547_create_day;
mod m20230209_063357_create_user;
mod m20230209_074936_create_trip;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
Box::new(m20230208_114547_create_day::Migration),
Box::new(m20230209_063357_create_user::Migration),
Box::new(m20230209_074936_create_trip::Migration),
]
}
}

View File

@ -1,48 +0,0 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Day::Table)
.if_not_exists()
.col(ColumnDef::new(Day::Day).date().not_null().primary_key())
.col(
ColumnDef::new(Day::PlannedAmountCox)
.not_null()
.integer()
.default(0),
)
.col(ColumnDef::new(Day::PlannedStartingTime).string())
.col(
ColumnDef::new(Day::OpenRegistration)
.boolean()
.not_null()
.default(true),
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Day::Table).to_owned())
.await
}
}
/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
pub enum Day {
Table,
Day,
PlannedAmountCox,
PlannedStartingTime,
OpenRegistration,
}

View File

@ -1,56 +0,0 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(
ColumnDef::new(User::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(User::Name).string().not_null().unique_key())
.col(ColumnDef::new(User::Pw).string())
.col(
ColumnDef::new(User::IsCox)
.boolean()
.not_null()
.default(false),
)
.col(
ColumnDef::new(User::IsAdmin)
.boolean()
.not_null()
.default(false),
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
}
/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
pub enum User {
Table,
Id,
Name,
Pw,
IsCox,
IsAdmin,
}

View File

@ -1,74 +0,0 @@
use sea_orm_migration::prelude::*;
use sea_query::Expr;
use crate::m20230208_114547_create_day::Day;
use crate::m20230209_063357_create_user::User;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Trip::Table)
.if_not_exists()
.col(ColumnDef::new(Trip::Day).date().not_null())
.foreign_key(
ForeignKey::create()
.name("FK_day")
.from(Trip::Table, Trip::Day)
.to(Day::Table, Day::Day),
)
.col(ColumnDef::new(Trip::UserId).integer().not_null())
.foreign_key(
ForeignKey::create()
.name("FK_userid")
.from(Trip::Table, Trip::UserId)
.to(User::Table, User::Id),
)
.col(ColumnDef::new(Trip::CoxId).integer())
.foreign_key(
ForeignKey::create()
.name("FK_coxid")
.from(Trip::Table, Trip::CoxId)
.to(User::Table, User::Id),
)
.col(ColumnDef::new(Trip::Begin).string())
.col(
ColumnDef::new(Trip::Created)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.primary_key(
Index::create()
.col(Trip::Day)
.col(Trip::UserId)
.col(Trip::CoxId)
.col(Trip::Begin),
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Trip::Table).to_owned())
.await
}
}
/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
enum Trip {
Table,
Day,
UserId,
CoxId,
Begin,
Created,
}

View File

@ -1,6 +0,0 @@
use sea_orm_migration::prelude::*;
#[async_std::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}

View File

@ -16,15 +16,14 @@ pub struct Model {
impl Model {
pub async fn find_or_create_day(date: chrono::NaiveDate, db: &DatabaseConnection) -> Model {
let day = Entity::find_by_id(date).one(db).await.unwrap();
match day {
Some(day) => day,
None => {
let new_day = ActiveModel {
day: Set(date),
..Default::default()
};
new_day.insert(db).await.unwrap()
}
if let Some(day) = day {
day
} else {
let new_day = ActiveModel {
day: Set(date),
..Default::default()
};
new_day.insert(db).await.unwrap()
}
}
}

View File

@ -30,29 +30,28 @@ impl Model {
.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()
}
if let Some(user) = user {
user
} else {
let user = ActiveModel {
name: Set(name.into()),
..Default::default()
};
log::info!("User {:?} created", user);
user.insert(db).await.unwrap()
}
}
}
#[derive(Debug)]
pub enum UserError {
pub enum Error {
NoCookieSet,
NoAdmin,
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Model {
type Error = UserError;
type Error = Error;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("name") {
@ -62,14 +61,14 @@ impl<'r> FromRequest<'r> for Model {
let user = Model::find_or_create_user(name, db.await.unwrap().inner()).await;
Outcome::Success(user)
}
None => Outcome::Failure((Status::Unauthorized, UserError::NoCookieSet)),
None => Outcome::Failure((Status::Unauthorized, Error::NoCookieSet)),
}
}
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for AdminUser {
type Error = UserError;
type Error = Error;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("name") {
@ -80,10 +79,10 @@ impl<'r> FromRequest<'r> for AdminUser {
if user.is_admin {
Outcome::Success(AdminUser(user))
} else {
Outcome::Failure((Status::Unauthorized, UserError::NoAdmin))
Outcome::Failure((Status::Unauthorized, Error::NoAdmin))
}
}
None => Outcome::Failure((Status::Unauthorized, UserError::NoCookieSet)),
None => Outcome::Failure((Status::Unauthorized, Error::NoCookieSet)),
}
}
}

View File

@ -93,8 +93,8 @@ async fn savename(
db: &State<DatabaseConnection>,
) -> Flash<Redirect> {
let user = user::Model::find_or_create_user(&name.name, db.inner()).await;
match user.pw {
Some(pw) => match &name.pw {
if let Some(pw) = user.pw {
match &name.pw {
Some(entered_pw) => {
let mut hasher = Sha3_256::new();
hasher.update(entered_pw);
@ -116,12 +116,11 @@ async fn savename(
);
Flash::error(Redirect::to("/name"), "Benutzer besitzt hat Passwort, du hast jedoch keines eingegeben. Bitte nochmal probieren")
}
},
None => {
log::info!("{} hat sich erfolgreich eingeloggt (ohne PW)", name.name);
cookies.add_private(Cookie::new("name", name.name.clone()));
Flash::success(Redirect::to("/"), "Name erfolgreich ausgewählt")
}
} else {
log::info!("{} hat sich erfolgreich eingeloggt (ohne PW)", name.name);
cookies.add_private(Cookie::new("name", name.name.clone()));
Flash::success(Redirect::to("/"), "Name erfolgreich ausgewählt")
}
}

View File

@ -27,15 +27,12 @@ async fn create(db: &State<DatabaseConnection>, day: Form<DayForm>) -> Redirect
.one(db.inner())
.await
.unwrap();
match day {
Some(day) => {
log::info!("{:?} got updated to {:?}", day, new_day);
new_day.update(db.inner()).await.unwrap(); //TODO: fixme
}
None => {
log::info!("{:?} got inserted", new_day);
new_day.insert(db.inner()).await.unwrap(); //TODO: fixme
}
if let Some(day) = day {
log::info!("{:?} got updated to {:?}", day, new_day);
new_day.update(db.inner()).await.unwrap(); //TODO: fixme
} else {
log::info!("{:?} got inserted", new_day);
new_day.insert(db.inner()).await.unwrap(); //TODO: fixme
}
Redirect::to("/")

View File

@ -3,7 +3,7 @@ use rocket::{
response::{Flash, Redirect},
Route, State,
};
use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, Set};
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set};
use crate::models::{day, trip, user};
@ -64,23 +64,19 @@ async fn register(
day: Set(day.clone()),
user_id: Set(user.id),
begin: Set(register.time.clone()),
cox_id: Set(register.cox_id.clone()),
cox_id: Set(register.cox_id),
..Default::default()
};
match trip.insert(db.inner()).await {
Ok(_) => {
log::info!("{} registered for {:?}", user.name, day);
Flash::success(Redirect::to("/"), "Erfolgreich angemeldet!")
}
Err(_) => {
log::warn!(
"{} tried to register for {:?}, but is already registered",
user.name,
day
);
Flash::error(Redirect::to("/"), "Du bist bereits angemeldet")
}
if trip.insert(db.inner()).await.is_ok() {
log::info!("{} registered for {:?}", user.name, day);
Flash::success(Redirect::to("/"), "Erfolgreich angemeldet!")
} else {
log::warn!(
"{} tried to register for {:?}, but is already registered",
user.name,
day
);
Flash::error(Redirect::to("/"), "Du bist bereits angemeldet")
}
}