From 5dc4774ed3380762b4d7aadc86193af6073c456a Mon Sep 17 00:00:00 2001 From: cel 🌸 Date: Mon, 11 Dec 2023 13:57:51 +0000 Subject: implement log-out --- src/main.rs | 22 +++++++++++++++++++--- templates/base.rs.html | 8 ++++---- templates/home.rs.html | 10 ++++++++++ templates/login.rs.html | 2 +- templates/signup.rs.html | 2 +- templates/users.rs.html | 4 ++-- 6 files changed, 37 insertions(+), 11 deletions(-) create mode 100644 templates/home.rs.html diff --git a/src/main.rs b/src/main.rs index 2736c5a..b10d0cf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -59,6 +59,7 @@ async fn main() -> std::io::Result<()> { // .service(home_auth) .service(get_login) .service(post_login) + .service(post_logout) .service(get_signup) .service(post_signup) .service(get_users) @@ -74,12 +75,19 @@ async fn main() -> std::io::Result<()> { } #[get("/")] -async fn home(session: Session) -> Result { +async fn home(session: Session, state: web::Data) -> Result { + let username: Option; if let Some(user_id) = session.get::("user_id")? { - return Ok(HttpResponse::Ok().body(format!("you are logged in as {}", user_id))); + username = Some( + sqlx::query!("select username from users where id = $1", user_id) + .fetch_one(&state.db) + .await? + .username, + ) } else { - return Ok(HttpResponse::Ok().body("Hello world!")); + username = None } + return Ok(HttpResponse::Ok().body(render!(templates::home_html, username).unwrap())); } #[get("/signup")] @@ -228,6 +236,14 @@ async fn post_login( } } +#[post("/logout")] +async fn post_logout(session: Session) -> HttpResponse { + session.purge(); + HttpResponse::SeeOther() + .insert_header((LOCATION, "/")) + .finish() +} + #[derive(sqlx::Type)] #[sqlx(type_name = "privacy", rename_all = "lowercase")] enum Privacy { diff --git a/templates/base.rs.html b/templates/base.rs.html index 64a8d4e..0bf70eb 100644 --- a/templates/base.rs.html +++ b/templates/base.rs.html @@ -1,7 +1,7 @@ @use super::statics::*; @use crate::Notification; -@(authenticated: bool, notification: Option, body: Content) +@(user: Option, notification: Option, body: Content) @@ -15,9 +15,9 @@