rusty_box/auth/
auth_developer.rs1use crate::config::Config;
3use async_trait::async_trait;
4use chrono::{DateTime, Duration, Utc};
5use serde::Serialize;
6
7use super::{access_token::AccessToken, Auth, AuthError};
8
9#[derive(Debug, Clone, Serialize, Default)]
12pub struct DevAuth {
13 config: Config,
14 access_token: AccessToken,
15 expires_by: DateTime<Utc>,
16}
17
18impl DevAuth {
19 pub fn new(config: Config, developer_token: String) -> Self {
20 let mut access_token = AccessToken::new();
21 access_token.access_token = Some(developer_token);
22
23 DevAuth {
24 config,
25 access_token,
26 expires_by: Utc::now() + Duration::seconds(3600),
27 }
28 }
29
30 pub fn is_expired(&self) -> bool {
31 Utc::now() > self.expires_by - Duration::seconds(60 * 5)
32 }
33}
34
35#[async_trait]
36impl<'a> Auth<'a> for DevAuth {
37 async fn access_token(&mut self) -> Result<String, AuthError> {
38 if self.is_expired() {
39 Err(AuthError::Generic("Developer token has expired".to_owned()))
40 } else {
41 let access_token = match self.access_token.access_token.clone() {
42 Some(token) => token,
43 None => return Err(AuthError::Generic("Developer token is not set".to_owned())),
44 };
45 Ok(access_token)
46 }
47 }
48
49 async fn to_json(&mut self) -> Result<String, AuthError> {
50 self.access_token().await?;
51 match serde_json::to_string(&self) {
52 Ok(json) => Ok(json),
53 Err(e) => Err(AuthError::Serde(e)),
54 }
55 }
56
57 fn base_api_url(&self) -> String {
58 self.config.base_api_url()
59 }
60
61 fn user_agent(&self) -> String {
62 self.config.user_agent()
63 }
64}
65
66#[cfg(test)]
67mod tests {
68
69 use super::*;
70
71 #[tokio::test]
72 async fn test_dev_token_new() {
73 let mut dev_token = DevAuth::new(Config::default(), "test".to_owned());
74 let access_token = dev_token.access_token().await.unwrap_or_default();
75 assert_eq!(access_token, "test");
76 assert!(dev_token.expires_by <= Utc::now() + Duration::seconds(3600));
77 assert!(!dev_token.is_expired());
78 }
79}