grafbase_sdk/types/
token.rs

1use crate::wit;
2
3/// Token produced by an authentication extension.
4#[derive(Clone)]
5pub struct Token(wit::Token);
6
7impl std::fmt::Debug for Token {
8    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9        f.debug_struct("Token").finish_non_exhaustive()
10    }
11}
12
13impl From<wit::Token> for Token {
14    fn from(token: wit::Token) -> Self {
15        Self(token)
16    }
17}
18
19impl From<Token> for wit::Token {
20    fn from(token: Token) -> Self {
21        token.0
22    }
23}
24
25impl Token {
26    /// Create a new anonymous token.
27    pub fn anonymous() -> Self {
28        Self(wit::Token::Anonymous)
29    }
30
31    /// Create a new token from raw bytes.
32    pub fn from_bytes(bytes: Vec<u8>) -> Self {
33        Self(wit::Token::Bytes(bytes))
34    }
35
36    /// Whether the current user is anonymous or not.
37    pub fn is_anonymous(&self) -> bool {
38        matches!(self.0, wit::Token::Anonymous)
39    }
40
41    /// Get the token's raw bytes. Will be `None` if the user is anonymous.
42    pub fn into_bytes(self) -> Option<Vec<u8>> {
43        match self.0 {
44            wit::Token::Anonymous => None,
45            wit::Token::Bytes(bytes) => Some(bytes),
46        }
47    }
48
49    /// Get a reference to the token's raw bytes. Will be `None` if the user is anonymous.
50    pub fn as_bytes(&self) -> Option<&[u8]> {
51        match &self.0 {
52            wit::Token::Anonymous => None,
53            wit::Token::Bytes(bytes) => Some(bytes),
54        }
55    }
56}