use std::borrow::Cow;
use ch_parsing::error::{ParseError, ParseErrorCode, ParseResult};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String")]
pub struct AuthMessageKey(Cow<'static, str>);
impl AuthMessageKey {
pub fn parse(raw: &str, field: &'static str) -> ParseResult<Self> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(ParseError::for_field(field, ParseErrorCode::Required));
}
if !is_valid_message_key(trimmed) {
return Err(ParseError::for_field(field, ParseErrorCode::InvalidFormat)
.with_parameter("expected", "domain_code"));
}
Ok(Self(Cow::Owned(trimmed.to_string())))
}
pub fn new_static(key: &'static str) -> Self {
Self::parse(key, "auth_message_key").expect("invalid message key")
}
pub fn as_str(&self) -> &str {
self.0.as_ref()
}
}
impl TryFrom<String> for AuthMessageKey {
type Error = ParseError;
fn try_from(value: String) -> ParseResult<Self> {
Self::parse(&value, "auth_message_key")
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthMessageArg {
name: Cow<'static, str>,
value: Cow<'static, str>,
}
impl AuthMessageArg {
pub fn new(name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) -> Self {
Self {
name: name.into(),
value: value.into(),
}
}
pub fn name(&self) -> &str {
self.name.as_ref()
}
pub fn value(&self) -> &str {
self.value.as_ref()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthMessage {
key: AuthMessageKey,
args: Vec<AuthMessageArg>,
}
impl AuthMessage {
pub fn new(key: AuthMessageKey) -> Self {
Self {
key,
args: Vec::new(),
}
}
pub fn from_static(key: &'static str) -> Self {
Self::new(AuthMessageKey::new_static(key))
}
pub fn with_arg(
mut self,
name: impl Into<Cow<'static, str>>,
value: impl Into<Cow<'static, str>>,
) -> Self {
self.args.push(AuthMessageArg::new(name, value));
self
}
pub fn key(&self) -> &AuthMessageKey {
&self.key
}
pub fn args(&self) -> &[AuthMessageArg] {
&self.args
}
}
pub(crate) fn is_valid_message_key(value: &str) -> bool {
value.chars().all(|ch| {
ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '.' || ch == '_' || ch == '-'
})
}
#[cfg(test)]
mod tests {
use super::AuthMessageKey;
#[test]
fn deserialization_uses_the_message_key_parser() {
for invalid in [
"",
" ",
"bad key",
"INVALID",
"auth.login\nforged",
"auth.ΓΌ",
] {
assert!(AuthMessageKey::parse(invalid, "key").is_err());
let input = serde_json::to_string(invalid).unwrap();
assert!(serde_json::from_str::<AuthMessageKey>(&input).is_err());
}
let key: AuthMessageKey = serde_json::from_str("\" auth.login.success \"").unwrap();
assert_eq!(key.as_str(), "auth.login.success");
assert_eq!(
serde_json::to_string(&key).unwrap(),
"\"auth.login.success\""
);
}
}