Fix redirect issues

Dashboard button now correctly redirects to login page if user is not
logged in while login page redirects to dashboard the other way around.
This commit is contained in:
Alphonse Paix
2025-09-17 23:57:45 +02:00
parent eec6e5f566
commit 848fd621b7
2 changed files with 17 additions and 4 deletions

View File

@@ -6,12 +6,15 @@ use crate::{
templates::ErrorTemplate, templates::ErrorTemplate,
}; };
use askama::Template; use askama::Template;
use axum::http::{HeaderMap, StatusCode};
use axum::{ use axum::{
Form, Json, Form, Json,
extract::State, extract::State,
response::{Html, IntoResponse, Response}, response::{Html, IntoResponse, Response},
}; };
use axum::{
http::{HeaderMap, StatusCode},
response::Redirect,
};
use secrecy::SecretString; use secrecy::SecretString;
#[derive(thiserror::Error)] #[derive(thiserror::Error)]
@@ -65,8 +68,17 @@ pub struct LoginFormData {
password: SecretString, password: SecretString,
} }
pub async fn get_login() -> Html<String> { pub async fn get_login(session: TypedSession) -> Result<Response, LoginError> {
Html(LoginTemplate.render().unwrap()) if session
.get_user_id()
.await
.map_err(|e| LoginError::UnexpectedError(e.into()))?
.is_some()
{
Ok(Redirect::to("/admin/dashboard").into_response())
} else {
Ok(Html(LoginTemplate.render().unwrap()).into_response())
}
} }
pub async fn post_login( pub async fn post_login(

View File

@@ -9,7 +9,7 @@
{% block title %}zero2prod{% endblock %} {% block title %}zero2prod{% endblock %}
</title> </title>
<link href="/assets/css/main.css" rel="stylesheet" /> <link href="/assets/css/main.css" rel="stylesheet" />
<script src="../assets/js/htmx.min.js"></script> <script src="/assets/js/htmx.min.js"></script>
</head> </head>
<body class="bg-gray-50 min-h-screen flex flex-col"> <body class="bg-gray-50 min-h-screen flex flex-col">
<header class="bg-white shadow-sm border-b border-gray-200 top-0 z-40"> <header class="bg-white shadow-sm border-b border-gray-200 top-0 z-40">
@@ -24,6 +24,7 @@
</div> </div>
<nav> <nav>
<a href="/admin/dashboard" <a href="/admin/dashboard"
hx-boost="true"
class="bg-blue-600 text-white hover:bg-blue-700 px-4 py-2 rounded-md text-sm font-medium transition-colors"> class="bg-blue-600 text-white hover:bg-blue-700 px-4 py-2 rounded-md text-sm font-medium transition-colors">
Dashboard Dashboard
</a> </a>