use rocket::{ form::Form, get, http::{Cookie, CookieJar}, post, request::FlashMessage, response::{Flash, Redirect}, routes, FromForm, Route, State, }; use rocket_dyn_templates::{tera, Template}; use serde_json::json; use sqlx::SqlitePool; use crate::model::user::User; #[get("/")] async fn index(flash: Option>) -> 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 = "")] async fn login( login: Form, db: &State, cookies: &CookieJar<'_>, ) -> Flash { let user = User::login(db, login.name.clone(), login.password.clone()).await; //TODO: be able to use for find_by_name. This would get rid of the following match clause. let user = match user { Ok(user) => user, Err(_) => { return Flash::error(Redirect::to("/auth"), "Falscher Benutzername/Passwort"); } }; let user_json: String = format!("{}", json!(user)); cookies.add_private(Cookie::new("user", user_json)); Flash::success(Redirect::to("/"), "Login erfolgreich") } pub fn routes() -> Vec { routes![index, login] }