zino_auth/
client_credentials.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
use super::AuthorizationProvider;
use parking_lot::RwLock;
use std::{marker::PhantomData, time::Duration};
use toml::Table;
use zino_core::{
    datetime::DateTime,
    error::Error,
    extension::{JsonObjectExt, TomlTableExt},
    warn, Map, SharedString,
};

/// Credentials for the client authentication.
#[derive(Debug)]
pub struct ClientCredentials<S: ?Sized> {
    /// Client ID.
    client_id: SharedString,
    /// Client key.
    client_key: SharedString,
    /// Client secret.
    client_secret: SharedString,
    /// Access token.
    access_token: RwLock<String>,
    /// Expires time.
    expires_at: RwLock<DateTime>,
    /// Phantom type of authorization server.
    phantom: PhantomData<S>,
}

impl<S: ?Sized> ClientCredentials<S> {
    /// Creates a new instance.
    #[inline]
    pub fn new(client_id: impl Into<SharedString>, client_secret: impl Into<SharedString>) -> Self {
        Self {
            client_id: client_id.into(),
            client_key: "".into(),
            client_secret: client_secret.into(),
            access_token: RwLock::new(String::new()),
            expires_at: RwLock::new(DateTime::now()),
            phantom: PhantomData,
        }
    }

    /// Attempts to create a new instance with the configuration.
    pub fn try_from_config(config: &'static Table) -> Result<Self, Error> {
        let client_id = config
            .get_str("client-id")
            .ok_or_else(|| warn!("the `client-id` field should be specified"))?;
        let client_key = config.get_str("client-key").unwrap_or_default();
        let client_secret = config
            .get_str("client-secret")
            .ok_or_else(|| warn!("the `client-secret` field should be specified"))?;
        Ok(Self {
            client_id: client_id.into(),
            client_key: client_key.into(),
            client_secret: client_secret.into(),
            access_token: RwLock::new(String::new()),
            expires_at: RwLock::new(DateTime::now()),
            phantom: PhantomData,
        })
    }

    /// Sets the client key.
    #[inline]
    pub fn set_client_key(&mut self, client_key: impl Into<SharedString>) {
        self.client_key = client_key.into();
    }

    /// Sets the access token.
    #[inline]
    pub fn set_access_token(&self, access_token: impl ToString) {
        *self.access_token.write() = access_token.to_string();
    }

    /// Sets the expires.
    #[inline]
    pub fn set_expires(&self, expires_in: Duration) {
        *self.expires_at.write() = DateTime::now() + expires_in
    }

    /// Returns the client ID.
    #[inline]
    pub fn client_id(&self) -> &str {
        self.client_id.as_ref()
    }

    /// Returns the client key.
    #[inline]
    pub fn client_key(&self) -> &str {
        self.client_key.as_ref()
    }

    /// Returns the client secret.
    #[inline]
    pub fn client_secret(&self) -> &str {
        self.client_secret.as_ref()
    }

    /// Returns the access token regardless of whether it has expired.
    #[inline]
    pub fn access_token(&self) -> String {
        self.access_token.read().clone()
    }

    /// Returns the time the client credentials expire at.
    #[inline]
    pub fn expires_at(&self) -> DateTime {
        *self.expires_at.read()
    }

    /// Returns the time when the client credentials will expire in.
    #[inline]
    pub fn expires_in(&self) -> Duration {
        self.expires_at().span_after_now().unwrap_or_default()
    }

    /// Returns `true` if the access token for the client credentials has expired.
    #[inline]
    pub fn is_expired(&self) -> bool {
        self.expires_at() <= DateTime::now()
    }

    /// Converts `self` to the request params.
    pub fn to_request_params(&self) -> Map {
        let mut params = Map::new();
        let client_id = self.client_id();
        let client_key = self.client_key();
        let client_secret = self.client_secret();
        if !client_id.is_empty() {
            params.upsert("client_id", client_id);
        }
        if !client_key.is_empty() {
            params.upsert("client_key", client_key);
        }
        if !client_secret.is_empty() {
            params.upsert("client_secret", client_secret);
        }
        params
    }
}

impl<S: ?Sized + AuthorizationProvider> ClientCredentials<S> {
    /// Requests an access token for the client credentials.
    #[inline]
    pub async fn request(&self) -> Result<String, Error> {
        if self.is_expired() {
            S::grant_client_credentials(self).await?;
        }
        Ok(self.access_token())
    }
}