use bevy_ecs::resource::Resource;
use crate::{ConnectToken, Error, Key, generate_key};
use core::net::SocketAddr;
use core::str::FromStr;
#[derive(Resource, Default, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Authentication {
Token(ConnectToken),
Manual {
server_addr: SocketAddr,
client_id: u64,
private_key: Key,
protocol_id: u64,
},
#[default]
None,
}
impl Authentication {
pub fn has_token(&self) -> bool {
matches!(self, Authentication::Token(..))
}
pub fn get_token(
self,
client_timeout_secs: i32,
token_expire_secs: i32,
) -> Result<ConnectToken, Error> {
Ok(match self {
Authentication::Token(token) => token,
Authentication::Manual {
server_addr,
client_id,
private_key,
protocol_id,
} => ConnectToken::build(server_addr, protocol_id, client_id, private_key)
.timeout_seconds(client_timeout_secs)
.expire_seconds(token_expire_secs)
.generate()?,
Authentication::None => {
ConnectToken::build(
SocketAddr::from_str("0.0.0.0:0").unwrap(),
0,
0,
generate_key(),
)
.timeout_seconds(client_timeout_secs)
.generate()?
}
})
}
}
impl core::fmt::Debug for Authentication {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Authentication::Token(_) => write!(f, "Token(<connect_token>)"),
Authentication::Manual {
server_addr,
client_id,
private_key,
protocol_id,
} => f
.debug_struct("Manual")
.field("server_addr", server_addr)
.field("client_id", client_id)
.field("private_key", private_key)
.field("protocol_id", protocol_id)
.finish(),
Authentication::None => write!(f, "None"),
}
}
}