rowt/src/rest/mod.rs
2023-07-18 17:32:34 +02:00

58 lines
1.8 KiB
Rust

use rocket::{form::Form, fs::FileServer, 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,
}
// curl -X POST localhost:8000/api/login -d "name=rower&password=rower"
#[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> {
rocket
.mount("/", FileServer::from("svelte/build").rank(0))
.mount("/api/login", routes![login])
}
//#[cfg(test)]
//mod test {
// use crate::testdb;
//
// use super::start;
// use rocket::http::Status;
// use rocket::local::asynchronous::Client;
// use rocket::uri;
// use sqlx::SqlitePool;
//
// #[sqlx::test]
// fn test_not_logged_in() {
// let pool = testdb!();
//
// let client = Client::tracked(start(pool))
// .await
// .expect("valid rocket instance");
// let response = client.get(uri!(super::index)).dispatch().await;
//
// assert_eq!(response.status(), Status::SeeOther);
// let location = response.headers().get("Location").next().unwrap();
// assert_eq!(location, "/auth");
// }
//}