From 5f9aa6d41cafe6dc35664580515032e670e898d8 Mon Sep 17 00:00:00 2001 From: "Alex M. M." Date: Thu, 9 Jan 2025 18:24:22 +0100 Subject: [PATCH] Fix deserialisation of `Token` type (#3086) The `Deserialize` implementation neglects to add the `Bot ` prefix to the string when it is deserialised. This adds `TryFrom` implementations for `&str` and `String` and tells serde to deserialise `Token` using the `TryFrom<&str>` implementation, which will prepend the `Bot ` prefix. Fixes #3085 --- src/secrets.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/secrets.rs b/src/secrets.rs index 208a5f50a5f..bf2f57a4bab 100644 --- a/src/secrets.rs +++ b/src/secrets.rs @@ -49,6 +49,7 @@ impl typesize::TypeSize for SecretString { /// A type for securely storing and passing around a Discord token. #[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))] #[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(try_from = "&str")] pub struct Token(SecretString); impl Token { @@ -119,7 +120,29 @@ impl FromStr for Token { } } -/// Error that can be returned by [`Token::from_str`] or [`Token::from_env`]. +/// Parses a token and validates that is is likely in a valid format. +/// +/// Refer to the [`Token::from_str`] implementation for details. +impl TryFrom<&str> for Token { + type Error = TokenError; + + fn try_from(s: &str) -> Result { + s.parse() + } +} + +/// Parses a token and validates that is is likely in a valid format. +/// +/// Refer to the [`Token::from_str`] implementation for details. +impl TryFrom for Token { + type Error = TokenError; + + fn try_from(s: String) -> Result { + s.parse() + } +} + +/// Error that can be returned by [`Token::from_str`], [`Token::try_from`], or [`Token::from_env`]. #[derive(Debug)] pub enum TokenError { Env(VarError),