Skip to content

Commit

Permalink
Fix deserialisation of Token type (serenity-rs#3086)
Browse files Browse the repository at this point in the history
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 serenity-rs#3085
  • Loading branch information
arqunis authored Jan 9, 2025
1 parent b72b1cc commit 5943323
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/secrets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Self, Self::Error> {
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<String> for Token {
type Error = TokenError;

fn try_from(s: String) -> Result<Self, Self::Error> {
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),
Expand Down

0 comments on commit 5943323

Please sign in to comment.