aboutsummaryrefslogtreecommitdiffstats
path: root/lib/auth/src/lib.rs
blob: 2a1390e73eb13c56c1e238dcb6dfd602eff1a1b1 (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
use bon::Builder;
use oauth2::{AuthUrl, ClientId, ClientSecret, EndpointNotSet, EndpointSet, RedirectUrl, TokenUrl};
use secrecy::{ExposeSecret, SecretString};
use thiserror::Error;

#[derive(Builder)]
pub struct ClientOptions {
    client_id: String,
    client_secret: SecretString,
    token_url: String,
    auth_url: String,
    redirect_url: String,
}

#[derive(Error, Debug)]
pub enum OauthError {
    #[error("invalid url")]
    InvalidUrl(#[from] url::ParseError),
}

pub type OauthClient = oauth2::basic::BasicClient<
    EndpointSet,
    EndpointNotSet,
    EndpointNotSet,
    EndpointNotSet,
    EndpointSet,
>;

pub fn oauth_client(opts: &ClientOptions) -> Result<OauthClient, OauthError> {
    let redirect_url = RedirectUrl::new(opts.redirect_url.to_owned())?;
    let client_id = ClientId::new(opts.client_id.to_owned());
    let auth_url = AuthUrl::new(opts.auth_url.to_owned())?;
    let token_url = TokenUrl::new(opts.token_url.to_owned())?;
    let client_secret = ClientSecret::new(opts.client_secret.expose_secret().to_string());

    Ok(oauth2::basic::BasicClient::new(client_id)
        .set_client_secret(client_secret)
        .set_auth_uri(auth_url)
        .set_token_uri(token_url)
        .set_redirect_uri(redirect_url))
}