oauth2_bitbucket/
authorization_code_grant.rs

1use oauth2_client::{
2    re_exports::{ClientId, ClientSecret, RedirectUri, Url, UrlParseError},
3    Provider, ProviderExtAuthorizationCodeGrant,
4};
5
6use crate::{BitbucketScope, AUTHORIZATION_URL, TOKEN_URL};
7
8#[derive(Debug, Clone)]
9pub struct BitbucketProviderWithWebApplication {
10    client_id: ClientId,
11    client_secret: ClientSecret,
12    redirect_uri: RedirectUri,
13    //
14    token_endpoint_url: Url,
15    authorization_endpoint_url: Url,
16}
17impl BitbucketProviderWithWebApplication {
18    pub fn new(
19        client_id: ClientId,
20        client_secret: ClientSecret,
21        redirect_uri: RedirectUri,
22    ) -> Result<Self, UrlParseError> {
23        Ok(Self {
24            client_id,
25            client_secret,
26            redirect_uri,
27            token_endpoint_url: TOKEN_URL.parse()?,
28            authorization_endpoint_url: AUTHORIZATION_URL.parse()?,
29        })
30    }
31}
32impl Provider for BitbucketProviderWithWebApplication {
33    type Scope = BitbucketScope;
34
35    fn client_id(&self) -> Option<&ClientId> {
36        Some(&self.client_id)
37    }
38
39    fn client_secret(&self) -> Option<&ClientSecret> {
40        Some(&self.client_secret)
41    }
42
43    fn token_endpoint_url(&self) -> &Url {
44        &self.token_endpoint_url
45    }
46}
47impl ProviderExtAuthorizationCodeGrant for BitbucketProviderWithWebApplication {
48    fn redirect_uri(&self) -> Option<&RedirectUri> {
49        Some(&self.redirect_uri)
50    }
51
52    fn scopes_default(&self) -> Option<Vec<<Self as Provider>::Scope>> {
53        Some(vec![BitbucketScope::Email, BitbucketScope::Account])
54    }
55
56    fn authorization_endpoint_url(&self) -> &Url {
57        &self.authorization_endpoint_url
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    use oauth2_client::{
66        authorization_code_grant::AccessTokenEndpoint,
67        re_exports::{Endpoint as _, Response},
68    };
69
70    #[test]
71    fn access_token_response() -> Result<(), Box<dyn std::error::Error>> {
72        let provider = BitbucketProviderWithWebApplication::new(
73            "CLIENT_ID".to_owned(),
74            "CLIENT_SECRET".to_owned(),
75            RedirectUri::new("https://client.example.com/cb")?,
76        )?;
77
78        let response_body = include_str!(
79            "../tests/response_body_json_files/access_token_with_authorization_code_grant.json"
80        );
81        let body_ret = AccessTokenEndpoint::new(&provider, "CODE".to_owned())
82            .parse_response(Response::builder().body(response_body.as_bytes().to_vec())?)?;
83
84        match body_ret {
85            Ok(_body) => {}
86            Err(body) => panic!("{body:?}"),
87        }
88
89        Ok(())
90    }
91}