aboutsummaryrefslogtreecommitdiffstats
path: root/lib/auth-service/src/client/mod.rs
blob: 25cf16c1fc776bd5dc0e28a0106930b4a0089e4b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use oauth2::{AuthUrl, ClientId, ClientSecret, EndpointNotSet, EndpointSet, RedirectUrl, TokenUrl};
use secrecy::{ExposeSecret, SecretString};
use tracing::debug;
use url::Url;

use crate::AuthServiceError;

pub struct OauthClient(
    oauth2::basic::BasicClient<
        EndpointSet,
        EndpointNotSet,
        EndpointNotSet,
        EndpointNotSet,
        EndpointSet,
    >,
);

pub struct ClientConfig {
    client_id: String,
    client_secret: SecretString,
    token_url: Url,
    auth_url: Url,
}

impl TryFrom<ClientConfig> for OauthClient {
    type Error = AuthServiceError;

    fn try_from(value: ClientConfig) -> Result<Self, Self::Error> {
        debug!("creating oauth client");
        Ok(Self(
            oauth2::basic::BasicClient::new(ClientId::new(value.client_id))
                .set_client_secret(ClientSecret::new(
                    value.client_secret.expose_secret().to_string(),
                ))
                .set_auth_uri(AuthUrl::from_url(value.auth_url))
                .set_token_uri(TokenUrl::from_url(value.token_url)),
        ))
    }
}

impl OauthClient {
    #[must_use]
    pub fn with_redirect_url(self, url: &Url) -> Self {
        Self(
            self.0
                .set_redirect_uri(RedirectUrl::from_url(url.to_owned())),
        )
    }
}