add rest login

This commit is contained in:
philipp 2023-07-16 20:44:27 +02:00
parent eb4c4bb558
commit e6d7f15cd8

View File

@ -1,7 +1,36 @@
use rocket::{fs::FileServer, Build, Rocket}; use rocket::{
form::Form, fs::FileServer, http::CookieJar, post, routes, Build, FromForm, Rocket, State,
};
use serde_json::json;
use sqlx::SqlitePool;
use crate::model::user::{LoginError, User};
#[derive(FromForm)]
struct LoginForm<'r> {
name: &'r str,
password: &'r str,
}
// name, is_admin, is_guest, is_cox
#[post("/", data = "<login>")]
async fn login(login: Form<LoginForm<'_>>, db: &State<SqlitePool>) -> String {
match User::login(db, login.name, login.password).await {
Ok(user) => serde_json::to_string(&json!({"status": "success", "user": user})).unwrap(),
Err(LoginError::NoPasswordSet(_)) => {
serde_json::to_string(&json!({"status": "set new pw"})).unwrap()
}
Err(_) => serde_json::to_string(&json!({"status": "wrong"})).unwrap(),
}
//let user_json: String = format!("{}", json!(user));
//cookies.add_private(Cookie::new("loggedin_user", user_json));
}
pub fn config(rocket: Rocket<Build>) -> Rocket<Build> { pub fn config(rocket: Rocket<Build>) -> Rocket<Build> {
rocket.mount("/", FileServer::from("svelte/build").rank(0)) rocket
.mount("/", FileServer::from("svelte/build").rank(0))
.mount("/api/login", routes![login])
} }
//#[cfg(test)] //#[cfg(test)]