use anyhow::Error; use thiserror::Error; use crate::message::{AuthenticatedInstance, Message, MessageHandler, NetworkMessage, State}; use giterated_models::messages::authentication::{ AuthenticationTokenRequest, RegisterAccountRequest, TokenExtensionRequest, }; use super::wrapper::ConnectionState; pub async fn authentication_handle( message_type: &str, message: &NetworkMessage, state: &ConnectionState, ) -> Result { match message_type { "&giterated_models::messages::authentication::RegisterAccountRequest" => { register_account_request .handle_message(&message, state) .await?; Ok(true) } "&giterated_models::messages::authentication::AuthenticationTokenRequest" => { authentication_token_request .handle_message(&message, state) .await?; Ok(true) } "&giterated_models::messages::authentication::TokenExtensionRequest" => { token_extension_request .handle_message(&message, state) .await?; Ok(true) } _ => Ok(false), } } async fn register_account_request( State(connection_state): State, Message(request): Message, instance: AuthenticatedInstance, ) -> Result<(), AuthenticationConnectionError> { if *instance.inner() != connection_state.instance { return Err(AuthenticationConnectionError::SameInstance); } let mut user_backend = connection_state.user_backend.lock().await; let response = user_backend .register(request.clone()) .await .map_err(|e| AuthenticationConnectionError::Registration(e))?; drop(user_backend); connection_state .send(response) .await .map_err(|e| AuthenticationConnectionError::Sending(e))?; Ok(()) } async fn authentication_token_request( State(connection_state): State, Message(request): Message, instance: AuthenticatedInstance, ) -> Result<(), AuthenticationConnectionError> { let issued_for = instance.inner().clone(); let mut token_granter = connection_state.auth_granter.lock().await; let response = token_granter .token_request(issued_for, request.username, request.password) .await .map_err(|e| AuthenticationConnectionError::TokenIssuance(e))?; connection_state .send(response) .await .map_err(|e| AuthenticationConnectionError::Sending(e))?; Ok(()) } async fn token_extension_request( State(connection_state): State, Message(request): Message, instance: AuthenticatedInstance, ) -> Result<(), AuthenticationConnectionError> { let issued_for = instance.inner().clone(); let mut token_granter = connection_state.auth_granter.lock().await; let response = token_granter .extension_request(&issued_for, request.token) .await .map_err(|e| AuthenticationConnectionError::TokenIssuance(e))?; connection_state .send(response) .await .map_err(|e| AuthenticationConnectionError::Sending(e))?; Ok(()) } #[derive(Debug, Error)] pub enum AuthenticationConnectionError { #[error("the request was invalid")] InvalidRequest, #[error("request must be from the same instance")] SameInstance, #[error("issue during registration {0}")] Registration(Error), #[error("sending error")] Sending(Error), #[error("error issuing token")] TokenIssuance(Error), }