Skip to content

Commit

Permalink
feat: system messages are now divide using newlines
Browse files Browse the repository at this point in the history
This way older clients will still be able to see a plain text version rather than a JSON payload if they don't support it. Server divides the payload using new lines which hides the parts after a newline
  • Loading branch information
jacobtread committed Jul 2, 2024
1 parent a65fb08 commit 9c3b190
Showing 1 changed file with 42 additions and 23 deletions.
65 changes: 42 additions & 23 deletions src/routes/auth.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
use std::sync::Arc;

use crate::{
config::RuntimeConfig, database::entities::{Player, PlayerRole}, services::sessions::Sessions, session::{models::messaging::MessageNotify, packet::Packet}, utils::{components::messaging, hashing::{hash_password, verify_password}}
config::RuntimeConfig,
database::entities::{Player, PlayerRole},
services::sessions::Sessions,
session::{models::messaging::MessageNotify, packet::Packet},
utils::{
components::messaging,
hashing::{hash_password, verify_password},
},
};
use axum::{
http::StatusCode,
Expand Down Expand Up @@ -50,11 +57,11 @@ pub enum AuthError {
/// Session is not active
#[error("This player is not currently connected, please connect to the server and visit the main menu in-game before attempting this action.")]
SessionNotActive,

/// Failed to create login code
#[error("Failed to generate login code")]
FailedGenerateCode,

/// Failed to create login code
#[error("The provided login code was incorrect")]
InvalidCode,
Expand Down Expand Up @@ -162,7 +169,6 @@ pub async fn create(
Ok(Json(TokenResponse { token }))
}


/// Request structure for requesting a login code
#[derive(Deserialize)]
pub struct RequestLoginCodeRequest {
Expand All @@ -171,7 +177,7 @@ pub struct RequestLoginCodeRequest {
}

/// POST /api/auth/request-code
///
///
/// Requests a login code be sent to a active session to be used
/// for logging in without a password
pub async fn handle_request_login_code(
Expand All @@ -190,31 +196,40 @@ pub async fn handle_request_login_code(
.ok_or(AuthError::SessionNotActive)?;

// Generate the login code
let login_code = sessions.create_login_code(player.id).map_err(|_|AuthError::FailedGenerateCode)?;
let login_code = sessions
.create_login_code(player.id)
.map_err(|_| AuthError::FailedGenerateCode)?;

let small_message =
format!("Login confirmation code: <font color='#FFFF66'>{login_code}</font>");
let full_message = format!("Your login confirmation code is <font color='#FFFF66'>{login_code}</font>, enter this on the dashboard to login");

// Create and serialize the message
let origin_message = serde_json::to_string(&SystemMessage {
title : "Login Confirmation Code".to_string(),
message: format!("Your login confirmation code is <font color='#FFFF66'>{login_code}</font>, enter this on the dashboard to login"),
title: "Login Confirmation Code".to_string(),
message: full_message,
image: "".to_string(),
ty:0,
ty: 0,
tracking_id: -1,
priority: 1
}).map_err(|_|AuthError::FailedGenerateCode)?;

priority: 1,
})
.map_err(|_| AuthError::FailedGenerateCode)?;

// Craft the payload with new lines so outdated clients don't see the JSON
let game_message = format!("{small_message}\n[SYSTEM_TERMINAL]{origin_message}\n");

let notify_origin = Packet::notify(
messaging::COMPONENT,
messaging::SEND_MESSAGE,
MessageNotify {
message: format!("[SYSTEM_TERMINAL]{origin_message}"),
message: game_message,
player_id: player.id,
},
);

// Send the message
session.notify_handle().notify(notify_origin);


Ok(StatusCode::OK)
}

Expand All @@ -236,30 +251,34 @@ pub struct RequestExchangeLoginCode {
}

/// POST /api/auth/exchange-code
///
///
/// Requests a login code be sent to a active session to be used
/// for logging in without a password
pub async fn handle_exchange_login_code(
Extension(sessions): Extension<Arc<Sessions>>,
Json(RequestExchangeLoginCode { login_code }): Json<RequestExchangeLoginCode>,
) -> AuthRes<TokenResponse> {

) -> AuthRes<TokenResponse> {
// Exchange the code for a token
let token = sessions.exchange_login_code(&login_code).ok_or(AuthError::InvalidCode)?;
let token = sessions
.exchange_login_code(&login_code)
.ok_or(AuthError::InvalidCode)?;

Ok(Json(TokenResponse { token }))
}


/// Response implementation for auth errors
impl IntoResponse for AuthError {
fn into_response(self) -> Response {
let status_code = match &self {
Self::Database(_) | Self::PasswordHash(_) | Self::FailedGenerateCode => StatusCode::INTERNAL_SERVER_ERROR,
Self::InvalidCredentials | Self::OriginAccess => StatusCode::UNAUTHORIZED,
Self::EmailTaken | Self::InvalidUsername | Self::SessionNotActive | Self::NoMatchingAccount | Self::InvalidCode => {
StatusCode::BAD_REQUEST
Self::Database(_) | Self::PasswordHash(_) | Self::FailedGenerateCode => {
StatusCode::INTERNAL_SERVER_ERROR
}
Self::InvalidCredentials | Self::OriginAccess => StatusCode::UNAUTHORIZED,
Self::EmailTaken
| Self::InvalidUsername
| Self::SessionNotActive
| Self::NoMatchingAccount
| Self::InvalidCode => StatusCode::BAD_REQUEST,
Self::RegistrationDisabled => StatusCode::FORBIDDEN,
};

Expand Down

0 comments on commit 9c3b190

Please sign in to comment.