feat: added logout

This commit is contained in:
Fu Zi Xiang 2023-10-10 13:02:41 +08:00
parent a293bd34ee
commit 427612b11f
No known key found for this signature in database
5 changed files with 90 additions and 72 deletions

View File

@ -5,7 +5,7 @@ mod templates;
mod web_api;
mod web_app;
use axum::Router;
use axum::{response::Redirect, routing::get, Router};
#[tokio::main]
async fn main() {
@ -19,12 +19,13 @@ async fn main() {
let state = AppState { gotrue_client };
let web_api_router = web_api::router().with_state(state.clone());
let web_app_router = web_app::router();
let web_api_router = web_api::router().with_state(state);
let app = Router::new()
.nest_service("/web-api", web_api_router)
.nest_service("/", web_app_router);
.route("/", get(|| async { Redirect::permanent("/web") }))
.nest_service("/web", web_app_router)
.nest_service("/web-api", web_api_router);
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())

View File

@ -3,3 +3,7 @@ use askama::Template;
#[derive(Template)]
#[template(path = "login.html")]
pub struct Login;
#[derive(Template)]
#[template(path = "home.html")]
pub struct Home;

View File

@ -2,7 +2,7 @@ use crate::error::RenderError;
use askama::Template;
use axum::response::Result;
use axum::{response::Html, routing::get, Router};
use axum_extra::extract::cookie::{Cookie, CookieJar};
use axum_extra::extract::cookie::CookieJar;
use crate::templates;
@ -11,17 +11,15 @@ pub fn router() -> Router {
.route("/", get(home_handler))
.route("/home", get(home_handler))
.route("/login", get(login_handler))
// for testing and debugging
.route("/setcookie", get(set_cookie_handler))
.route("/resetcookie", get(reset_cookie_handler))
}
pub async fn home_handler(cookies: CookieJar) -> Result<Html<String>, RenderError> {
println!("cookies: {:?}", cookies);
let access_token = cookies.get("access_token");
match access_token {
Some(access_token) => Ok(Html(access_token.to_string())), // TODO: render home page
Some(access_token) => {
let s = templates::Home {}.render()?;
Ok(Html(s))
},
None => login_handler().await,
}
}
@ -30,11 +28,3 @@ pub async fn login_handler() -> Result<Html<String>, RenderError> {
let s = templates::Login {}.render()?;
Ok(Html(s))
}
pub async fn set_cookie_handler(jar: CookieJar) -> CookieJar {
jar.add(Cookie::new("access_token", "test"))
}
pub async fn reset_cookie_handler(jar: CookieJar) -> CookieJar {
jar.remove(Cookie::new("access_token", ""))
}

View File

@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<body>
<h1>Welcome to the Home Page</h1>
<button id="logoutBtn">Logout</button>
<script>
document
.getElementById("logoutBtn")
.addEventListener("click", function () {
// Remove the cookie by setting its value to an empty string and its expiry date to the past.
document.cookie =
"access_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
// Redirect to the login page.
window.location.href = "/web/login";
});
</script>
</body>
</html>

View File

@ -1,62 +1,65 @@
<!doctype html>
<html>
<body>
<body>
<h1>Admin Login</h1>
<form id="loginForm">
<table>
<tr>
<td>
<label for="email">Email:</label>
</td>
<td>
<input type="text" id="email" name="email" required />
</td>
</tr>
<tr>
<td>
<label for="password">Password:</label>
</td>
<td>
<input type="password" id="password" name="password" required />
</td>
</tr>
</table>
<button type="button" id="submitBtn">Submit</button>
<table>
<tr>
<td>
<label for="email">Email:</label>
</td>
<td>
<input type="text" id="email" name="email" required />
</td>
</tr>
<tr>
<td>
<label for="password">Password:</label>
</td>
<td>
<input type="password" id="password" name="password" required />
</td>
</tr>
</table>
<button type="button" id="submitBtn">Submit</button>
</form>
<div id="response"></div>
<script>
document.getElementById('submitBtn').addEventListener('click', function () {
var data = {
email: document.getElementById('email').value,
password: document.getElementById('password').value
};
fetch('/web-api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => {
if (!response.ok) {
// If HTTP status code is not OK, throw an error with the status text
throw Error(response.statusText);
}
// Parse the JSON response
return response.json();
})
.then(data => {
// Set the token as a cookie
document.cookie = "access_token=" + data.data.access_token + "; path=/";
window.location.href = "/home";
})
.catch((error) => {
console.error('Error:', error);
document.getElementById('response').innerText = 'Login failed: ' + error.message;
});
});
document
.getElementById("submitBtn")
.addEventListener("click", function () {
var data = {
email: document.getElementById("email").value,
password: document.getElementById("password").value,
};
fetch("/web-api/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => {
if (!response.ok) {
// If HTTP status code is not OK, throw an error with the status text
throw Error(response.statusText);
}
// Parse the JSON response
return response.json();
})
.then((data) => {
// Set the token as a cookie
document.cookie =
"access_token=" + data.data.access_token + "; path=/";
window.location.href = "/";
})
.catch((error) => {
console.error("Error:", error);
document.getElementById("response").innerText =
"Login failed: " + error.message;
});
});
</script>
</body>
</body>
</html>