pageseeder_api/
oauth.rs

1use std::collections::HashMap;
2
3use chrono::{DateTime, Duration, Utc};
4use reqwest::header::HeaderValue;
5use serde::Deserialize;
6
7use crate::model::{PSError, PSResult};
8
9#[derive(Debug)]
10pub enum PSCredentials {
11    ClientCredentials { id: String, secret: String },
12}
13
14impl PSCredentials {
15    /// Returns a map of parameters to use to request a grant.
16    pub fn to_map(&self) -> HashMap<&'static str, String> {
17        match self {
18            Self::ClientCredentials { id, secret } => {
19                let mut map = HashMap::new();
20                map.insert("grant_type", "client_credentials".to_string());
21                map.insert("client_id", id.clone());
22                map.insert("client_secret", secret.clone());
23                map
24            }
25        }
26    }
27}
28
29#[derive(Debug, Clone)]
30/// Temporary access token for making calls to psapi.
31pub struct PSToken {
32    pub token: String,
33    pub expiry: DateTime<Utc>,
34    pub header: HeaderValue,
35}
36
37impl PSToken {
38    /// Creates a PSToken that will expire in the given number of seconds.
39    pub fn expires_in(token: String, seconds: i64) -> PSResult<PSToken> {
40        let header = match HeaderValue::from_str(&format!("Bearer {}", token)) {
41            Err(err) => {
42                return Err(PSError::TokenError {
43                    msg: format!("Invalid token {}", err),
44                })
45            }
46            Ok(header) => header,
47        };
48
49        Ok(PSToken {
50            token,
51            expiry: Utc::now() + Duration::seconds(seconds),
52            header,
53        })
54    }
55}
56
57#[derive(Deserialize)]
58pub struct TokenResponse {
59    pub access_token: String,
60    pub expires_in: i64,
61    pub token_type: String,
62    pub scope: Option<String>,
63}