Skip to main content

openauth_oauth/oauth2/
request.rs

1use std::collections::BTreeMap;
2
3use base64::engine::general_purpose::STANDARD;
4use base64::Engine;
5use url::form_urlencoded::Serializer;
6
7use super::error::OAuthError;
8use super::http::{default_http_client, OAuthHttpClient};
9use super::tokens::{get_primary_client_id, ProviderOptions};
10
11#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
12pub enum ClientAuthentication {
13    #[default]
14    Post,
15    Basic,
16}
17
18#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub struct OAuthFormRequest {
20    pub body: Vec<(String, String)>,
21    pub headers: BTreeMap<String, String>,
22}
23
24impl OAuthFormRequest {
25    pub fn new() -> Self {
26        Self {
27            body: Vec::new(),
28            headers: BTreeMap::from([
29                (
30                    "content-type".to_owned(),
31                    "application/x-www-form-urlencoded".to_owned(),
32                ),
33                ("accept".to_owned(), "application/json".to_owned()),
34            ]),
35        }
36    }
37
38    pub fn push_body(&mut self, key: impl Into<String>, value: impl Into<String>) {
39        self.body.push((key.into(), value.into()));
40    }
41
42    pub fn set_body(&mut self, key: impl Into<String>, value: impl Into<String>) {
43        let key = key.into();
44        self.body.retain(|(existing, _)| existing != &key);
45        self.body.push((key, value.into()));
46    }
47
48    pub fn has_body(&self, key: &str) -> bool {
49        self.body.iter().any(|(existing, _)| existing == key)
50    }
51
52    pub fn form_value(&self, key: &str) -> Option<&str> {
53        self.body
54            .iter()
55            .find(|(existing, _)| existing == key)
56            .map(|(_, value)| value.as_str())
57    }
58
59    pub fn form_values(&self, key: &str) -> Vec<&str> {
60        self.body
61            .iter()
62            .filter(|(existing, _)| existing == key)
63            .map(|(_, value)| value.as_str())
64            .collect()
65    }
66
67    pub fn header(&self, key: &str) -> Option<&str> {
68        self.headers
69            .get(&key.to_ascii_lowercase())
70            .map(String::as_str)
71    }
72
73    pub fn set_header(&mut self, key: impl Into<String>, value: impl Into<String>) {
74        self.headers
75            .insert(key.into().to_ascii_lowercase(), value.into());
76    }
77
78    pub fn to_form_urlencoded(&self) -> String {
79        let mut serializer = Serializer::new(String::new());
80        for (key, value) in &self.body {
81            serializer.append_pair(key, value);
82        }
83        serializer.finish()
84    }
85}
86
87pub fn apply_client_authentication(
88    request: &mut OAuthFormRequest,
89    options: &ProviderOptions,
90    authentication: ClientAuthentication,
91    require_secret: bool,
92) -> Result<(), OAuthError> {
93    let primary_client_id = get_primary_client_id(&options.client_id);
94    let client_secret = non_empty_secret(options);
95
96    match authentication {
97        ClientAuthentication::Basic => {
98            let client_id = primary_client_id.ok_or_else(|| {
99                OAuthError::InvalidClientAuthentication(
100                    "HTTP Basic authentication requires client_id".to_owned(),
101                )
102            })?;
103            let client_secret = if require_secret {
104                client_secret.ok_or(OAuthError::MissingOption("client_secret"))?
105            } else {
106                client_secret.unwrap_or("")
107            };
108            let credentials = STANDARD.encode(format!("{client_id}:{client_secret}"));
109            request.set_header("authorization", format!("Basic {credentials}"));
110        }
111        ClientAuthentication::Post => {
112            if let Some(client_id) = primary_client_id {
113                request.set_body("client_id", client_id);
114            }
115            if let Some(client_secret) = client_secret {
116                request.set_body("client_secret", client_secret);
117            } else if require_secret {
118                return Err(OAuthError::MissingOption("client_secret"));
119            }
120        }
121    }
122
123    Ok(())
124}
125
126fn non_empty_secret(options: &ProviderOptions) -> Option<&str> {
127    options
128        .client_secret
129        .as_deref()
130        .filter(|secret| !secret.is_empty())
131}
132
133pub async fn post_form(
134    token_endpoint: &str,
135    request: OAuthFormRequest,
136) -> Result<serde_json::Value, OAuthError> {
137    post_form_with_client(token_endpoint, request, &default_http_client()?).await
138}
139
140pub async fn post_form_with_client(
141    token_endpoint: &str,
142    request: OAuthFormRequest,
143    client: &OAuthHttpClient,
144) -> Result<serde_json::Value, OAuthError> {
145    client.post_form(token_endpoint, request).await
146}