Skip to main content

pib_client/
authenticated_client.rs

1// SPDX-FileCopyrightText: Politik im Blick developers
2// SPDX-FileCopyrightText: Wolfgang Silbermayr <wolfgang@silbermayr.at>
3//
4// SPDX-License-Identifier: AGPL-3.0-or-later OR EUPL-1.2
5
6use bytes::Bytes;
7use http::{HeaderValue, Method, Request, Response, header::AUTHORIZATION};
8use http_request_derive::{Error, HttpRequest};
9use url::Url;
10
11use crate::Authorization;
12
13/// A client authenticated to the OIDC provider.
14#[derive(Debug)]
15pub struct AuthenticatedClient<C, A> {
16    inner: C,
17    authorization: A,
18}
19
20impl<C, A> AuthenticatedClient<C, A> {
21    /// Create a new [AuthenticatedClient] with a valid authorization.
22    pub fn new(inner: C, authorization: A) -> Self {
23        Self {
24            inner,
25            authorization,
26        }
27    }
28}
29
30impl<C: Clone, A: Clone> Clone for AuthenticatedClient<C, A> {
31    fn clone(&self) -> Self {
32        Self {
33            inner: self.inner.clone(),
34            authorization: self.authorization.clone(),
35        }
36    }
37}
38
39#[async_trait::async_trait(?Send)]
40impl<C: http_request_derive_client::Client, A: Authorization + Sync>
41    http_request_derive_client::Client for AuthenticatedClient<C, A>
42{
43    /// An error that can be returned during request execution by the [`AuthenticatedClient`].
44    type ClientError = C::ClientError;
45
46    /// Execute a [`http_request_derive::HttpRequest`], and read the typed response.
47    async fn execute<R: HttpRequest + Send>(
48        &self,
49        request: R,
50    ) -> Result<R::Response, Self::ClientError> {
51        let bearer_token = self.authorization.get_access_token().await.unwrap();
52
53        let request = AuthenticatedRequest {
54            request,
55            bearer_token,
56        };
57        self.inner.execute(request).await
58    }
59}
60
61struct AuthenticatedRequest<R> {
62    request: R,
63    bearer_token: String,
64}
65
66impl<R: HttpRequest> HttpRequest for AuthenticatedRequest<R> {
67    type Response = R::Response;
68    type Query = R::Query;
69    type Body = R::Body;
70
71    const METHOD: Method = R::METHOD;
72
73    fn path(&self) -> String {
74        self.request.path()
75    }
76
77    fn query(&self) -> Option<&Self::Query> {
78        self.request.query()
79    }
80
81    fn body(&self) -> Option<&Self::Body> {
82        self.request.body()
83    }
84
85    fn to_http_request(&self, base_url: &Url) -> Result<Request<Vec<u8>>, Error> {
86        let mut request = self.request.to_http_request(base_url)?;
87        _ = request.headers_mut().insert(
88            AUTHORIZATION,
89            HeaderValue::from_str(&format!("Bearer {}", self.bearer_token)).unwrap(),
90        );
91        Ok(request)
92    }
93
94    fn read_response(response: Response<Bytes>) -> Result<Self::Response, Error> {
95        R::read_response(response)
96    }
97}