Redirect user to authentication

This commit is contained in:
2025-01-21 21:26:01 +01:00
parent 1c99bbadc1
commit fffa561d43
11 changed files with 642 additions and 61 deletions

37
src/server/mod.rs Normal file
View File

@ -0,0 +1,37 @@
use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError};
use std::error::Error;
pub mod web_ui;
#[derive(thiserror::Error, Debug)]
pub enum HttpFailure {
#[error("this resource requires higher privileges")]
Forbidden,
#[error("this resource was not found")]
NotFound,
#[error("an unhandled session insert error occurred")]
SessionInsertError(#[from] actix_session::SessionInsertError),
#[error("an unhandled session error occurred")]
SessionError(#[from] actix_session::SessionGetError),
#[error("an unspecified open id error occurred: {0}")]
OpenID(Box<dyn Error>),
#[error("an unspecified internal error occurred: {0}")]
InternalError(#[from] anyhow::Error),
}
impl ResponseError for HttpFailure {
fn status_code(&self) -> StatusCode {
match &self {
Self::Forbidden => StatusCode::FORBIDDEN,
Self::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code()).body(self.to_string())
}
}
pub type HttpResult = std::result::Result<HttpResponse, HttpFailure>;

30
src/server/web_ui.rs Normal file
View File

@ -0,0 +1,30 @@
use crate::app_config::AppConfig;
use crate::constants::{STATE_KEY, USER_SESSION_KEY};
use crate::server::{HttpFailure, HttpResult};
use crate::user::User;
use crate::utils;
use actix_session::Session;
use actix_web::HttpResponse;
use light_openid::primitives::OpenIDConfig;
pub async fn home(session: Session) -> HttpResult {
// Get user information
let Some(user): Option<User> = session.get(USER_SESSION_KEY)? else {
// Generate auth state
let state = utils::rand_str(10);
session.insert(STATE_KEY, &state)?;
let oidc = AppConfig::get().openid_provider();
let config = OpenIDConfig::load_from_url(oidc.configuration_url)
.await
.map_err(HttpFailure::OpenID)?;
let auth_url = config.gen_authorization_url(oidc.client_id, &state, &oidc.redirect_url);
return Ok(HttpResponse::Found()
.append_header(("location", auth_url))
.finish());
};
Ok(HttpResponse::Ok().body("You are authenticated!"))
}