rowt/src/rest/mod.rs

58 lines
1.8 KiB
Rust
Raw Normal View History

2023-07-18 17:32:34 +02:00
use rocket::{form::Form, fs::FileServer, post, routes, Build, FromForm, Rocket, State};
2023-07-16 20:44:27 +02:00
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"
2023-07-16 20:44:27 +02:00
#[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));
}
2023-07-16 18:42:59 +02:00
pub fn config(rocket: Rocket<Build>) -> Rocket<Build> {
2023-07-16 20:44:27 +02:00
rocket
.mount("/", FileServer::from("svelte/build").rank(0))
.mount("/api/login", routes![login])
2023-07-16 18:42:59 +02:00
}
//#[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");
// }
//}