Handlers: create authentication machinery
Build nomnom / Build-NomNom (push) Successful in 3m35s Details

This commit is contained in:
Félix Baylac Jacqué 2023-11-27 16:56:08 +01:00
parent e950366ebc
commit b508bbe18b
3 changed files with 45 additions and 9 deletions

View File

@ -1,14 +1,49 @@
use actix_web::{HttpResponse, http::header::ContentType, web};
use actix_web::{HttpResponse, http::header::{ContentType, self}, web, HttpRequest, cookie::{Cookie, SameSite}};
use uuid::Uuid;
use crate::{models::AppState, templates};
use crate::{models::{AppState, SessionUuid, User}, templates};
pub mod authentication;
pub use authentication::*;
pub async fn landing_page (app_state: web::Data<AppState<'_>>) -> HttpResponse {
let content: String = templates::landing_page(app_state.hbs.clone()).unwrap();
HttpResponse::Ok()
.content_type(ContentType::html())
.body(content)
pub async fn landing_page (app_state: web::Data<AppState<'_>>, req: HttpRequest) -> HttpResponse {
match check_authentication(app_state.clone(), req).await {
Ok(_) => {
let content: String = templates::landing_page(app_state.hbs.clone(), true).unwrap();
HttpResponse::Ok()
.content_type(ContentType::html())
.body(content)
},
Err(redirect) => redirect,
}
}
async fn check_authentication(app_state: web::Data<AppState<'_>>, req: HttpRequest) -> Result<User, HttpResponse> {
fn redirect_to_login<T>(e: T, req: &HttpRequest) -> HttpResponse
where T: ToString
{
eprintln!("check_authentication: invalid session {}", e.to_string());
let secure = false;
#[cfg(not(debug_assertions))]
let secure = true;
let redirect_cookie = Cookie::build("redirect", req.path())
.http_only(true)
.same_site(SameSite::Strict)
.path("/")
.secure(secure)
.finish();
HttpResponse::Found()
.append_header((header::LOCATION, "/login"))
.cookie(redirect_cookie)
.body("Please login")
}
let auth_session = app_state.session.user_sessions.read().await;
let cookie = req.cookie("auth-uuid").ok_or_else(|| redirect_to_login("missing cookie in request", &req))?;
let cookie = cookie.value();
let client_uuid = Uuid::parse_str(&cookie).map_err(|e| redirect_to_login(e, &req))?;
let user = auth_session.get(&SessionUuid(client_uuid)).ok_or_else(|| redirect_to_login("cannot find UUID in session", &req))?;
Ok(user.clone())
}

View File

@ -1,3 +1,4 @@
{{#> template }}
<p>Hello world, this is the nom nom S3 GC</p>
<p>Logged? {{ logged }}</p>
{{ /template }}

View File

@ -28,9 +28,9 @@ pub fn new<'a>() -> Result<Handlebars<'a>, RenderError> {
Ok(hbs)
}
pub fn landing_page(hb: Arc<Handlebars<'_>>) -> Result<String, RenderError> {
pub fn landing_page(hb: Arc<Handlebars<'_>>, logged: bool) -> Result<String, RenderError> {
let data = json!({
"logged": logged
});
hb.render("landing", &data)
}