opentalk_client_shared/request/
authorized.rs

1// SPDX-FileCopyrightText: OpenTalk GmbH <mail@opentalk.eu>
2//
3// SPDX-License-Identifier: EUPL-1.2
4
5use http::StatusCode;
6use http_request_derive::HttpRequest;
7
8use crate::Authorization;
9
10/// Wrapper type that adds authorization information to a request
11#[derive(Debug)]
12pub struct Authorized<A: Authorization, R: HttpRequest> {
13    authorization: A,
14    request: R,
15}
16
17impl<A: Authorization, R: HttpRequest> Authorized<A, R> {
18    /// Create a new authorized request
19    pub const fn new(authorization: A, request: R) -> Self {
20        Self {
21            authorization,
22            request,
23        }
24    }
25}
26
27impl<A: Authorization, R: HttpRequest> HttpRequest for Authorized<A, R> {
28    type Response = R::Response;
29
30    type Query = R::Query;
31
32    type Body = R::Body;
33
34    const METHOD: http::Method = R::METHOD;
35
36    fn path(&self) -> String {
37        self.request.path()
38    }
39
40    fn query(&self) -> Option<&Self::Query> {
41        self.request.query()
42    }
43
44    fn body(&self) -> Option<&Self::Body> {
45        self.request.body()
46    }
47
48    fn apply_headers(&self, headers: &mut http::HeaderMap) {
49        self.request.apply_headers(headers);
50        self.authorization.apply_authorization_headers(headers);
51    }
52
53    fn read_response(
54        response: http::Response<bytes::Bytes>,
55    ) -> Result<Self::Response, http_request_derive::Error> {
56        match response.status() {
57            StatusCode::UNAUTHORIZED => Err(http_request_derive::Error::Unauthorized),
58            _ => R::read_response(response),
59        }
60    }
61}