2023-04-03 16:11:26 +02:00
|
|
|
use rocket::{
|
|
|
|
form::Form,
|
2023-04-03 17:32:41 +02:00
|
|
|
get,
|
|
|
|
http::{Cookie, CookieJar},
|
|
|
|
post,
|
2023-04-03 16:11:26 +02:00
|
|
|
request::FlashMessage,
|
2023-04-03 17:32:41 +02:00
|
|
|
response::{Flash, Redirect},
|
|
|
|
routes, FromForm, Route, State,
|
2023-04-03 16:11:26 +02:00
|
|
|
};
|
2023-04-03 17:32:41 +02:00
|
|
|
use rocket_dyn_templates::{tera, Template};
|
|
|
|
use serde_json::json;
|
2023-04-03 16:11:26 +02:00
|
|
|
use sqlx::SqlitePool;
|
|
|
|
|
2023-04-03 17:32:41 +02:00
|
|
|
use crate::model::user::User;
|
2023-04-03 16:11:26 +02:00
|
|
|
|
|
|
|
#[get("/")]
|
|
|
|
async fn index(flash: Option<FlashMessage<'_>>) -> Template {
|
|
|
|
let mut context = tera::Context::new();
|
|
|
|
|
|
|
|
if let Some(msg) = flash {
|
|
|
|
context.insert("flash", &msg.into_inner());
|
|
|
|
}
|
|
|
|
|
|
|
|
Template::render("auth/login", context.into_json())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(FromForm)]
|
|
|
|
struct LoginForm {
|
|
|
|
name: String,
|
|
|
|
password: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[post("/", data = "<login>")]
|
2023-04-03 17:32:41 +02:00
|
|
|
async fn login(
|
|
|
|
login: Form<LoginForm>,
|
|
|
|
db: &State<SqlitePool>,
|
|
|
|
cookies: &CookieJar<'_>,
|
|
|
|
) -> Flash<Redirect> {
|
2023-04-03 16:11:26 +02:00
|
|
|
let user = User::login(db, login.name.clone(), login.password.clone()).await;
|
|
|
|
|
2023-04-03 22:03:45 +02:00
|
|
|
//TODO: be able to use ? for login. This would get rid of the following match clause.
|
2023-04-03 16:11:26 +02:00
|
|
|
let user = match user {
|
|
|
|
Ok(user) => user,
|
|
|
|
Err(_) => {
|
|
|
|
return Flash::error(Redirect::to("/auth"), "Falscher Benutzername/Passwort");
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-04-03 17:32:41 +02:00
|
|
|
let user_json: String = format!("{}", json!(user));
|
2023-04-03 22:03:45 +02:00
|
|
|
cookies.add_private(Cookie::new("loggedin_user", user_json));
|
2023-04-03 17:32:41 +02:00
|
|
|
|
2023-04-03 16:11:26 +02:00
|
|
|
Flash::success(Redirect::to("/"), "Login erfolgreich")
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn routes() -> Vec<Route> {
|
|
|
|
routes![index, login]
|
|
|
|
}
|