twitter_v2/authorization/
mod.rs

1#[cfg(feature = "oauth2")]
2mod oauth2;
3
4use crate::error::{Error, Result};
5use async_trait::async_trait;
6use reqwest::header::HeaderValue;
7use reqwest::Request;
8use std::collections::BTreeSet;
9use std::fmt;
10
11#[cfg(feature = "oauth2")]
12pub use self::oauth2::*;
13
14#[async_trait]
15pub trait Authorization {
16    async fn header(&self, request: &Request) -> Result<HeaderValue>;
17}
18
19#[derive(Clone)]
20pub struct BearerToken(String);
21
22impl BearerToken {
23    pub fn new(bearer: impl ToString) -> Self {
24        Self(bearer.to_string())
25    }
26}
27
28impl fmt::Debug for BearerToken {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        f.debug_tuple("Bearer").finish()
31    }
32}
33
34#[async_trait]
35impl Authorization for BearerToken {
36    async fn header(&self, _request: &Request) -> Result<HeaderValue> {
37        format!("Bearer {}", self.0)
38            .parse()
39            .map_err(Error::InvalidAuthorizationHeader)
40    }
41}
42
43#[derive(Clone)]
44pub struct Oauth1aToken(oauth1::Token);
45
46impl Oauth1aToken {
47    pub fn new(
48        consumer_key: impl ToString,
49        consumer_secret: impl ToString,
50        token: impl ToString,
51        secret: impl ToString,
52    ) -> Self {
53        Self(oauth1::Token::from_parts(
54            consumer_key.to_string(),
55            consumer_secret.to_string(),
56            token.to_string(),
57            secret.to_string(),
58        ))
59    }
60}
61impl fmt::Debug for Oauth1aToken {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.debug_struct("Oauth1a")
64            .field("consumer_key", &self.0.client.identifier)
65            .field("token", &self.0.token.identifier)
66            .finish()
67    }
68}
69
70#[async_trait]
71impl Authorization for Oauth1aToken {
72    async fn header(&self, request: &Request) -> Result<HeaderValue> {
73        let method = request.method().as_str();
74        let url = {
75            let mut url = request.url().clone();
76            url.set_query(None);
77            url.set_fragment(None);
78            url
79        };
80        let request = request.url().query_pairs().collect::<BTreeSet<_>>();
81        oauth1::authorize(method, url, &request, &self.0, oauth1::HmacSha1)
82            .parse()
83            .map_err(Error::InvalidAuthorizationHeader)
84    }
85}