|
| 1 | +use std::time::Duration; |
| 2 | + |
| 3 | +use anyhow::Context; |
| 4 | +use oauth2::{ |
| 5 | + basic::{BasicClient, BasicTokenType}, reqwest::async_http_client, AccessToken, AuthType, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, RedirectUrl, RefreshToken, Scope, StandardErrorResponse, TokenResponse, TokenUrl |
| 6 | +}; |
| 7 | +use reqwest::Url; |
| 8 | + |
| 9 | +use crate::settings::OAuthConfig; |
| 10 | + |
| 11 | +#[derive(Debug)] |
| 12 | +pub struct OAuthClient { |
| 13 | + config: OAuthConfig, |
| 14 | + client: BasicClient, |
| 15 | +} |
| 16 | + |
| 17 | +impl Clone for OAuthClient { |
| 18 | + fn clone(&self) -> Self { |
| 19 | + OAuthClient { |
| 20 | + config: self.config.clone(), |
| 21 | + client: self.client.clone(), |
| 22 | + } |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl OAuthClient { |
| 27 | + pub fn new(config: OAuthConfig) -> Self { |
| 28 | + let client = BasicClient::new( |
| 29 | + ClientId::new(config.client_id.clone()), |
| 30 | + Some(ClientSecret::new(config.client_secret.clone())), |
| 31 | + AuthUrl::new(config.authorization_url.clone()).unwrap(), |
| 32 | + Some(TokenUrl::new(config.token_url.clone()).unwrap()), |
| 33 | + ) |
| 34 | + .set_auth_type(AuthType::RequestBody) |
| 35 | + .set_redirect_uri(RedirectUrl::new(config.authorization_redirect_uri.clone()).unwrap()); |
| 36 | + |
| 37 | + Self { config, client } |
| 38 | + } |
| 39 | + |
| 40 | + pub fn get_authorization_url(&self, scope: Vec<String>) -> (Url, CsrfToken) { |
| 41 | + let mut request = self.client.authorize_url(CsrfToken::new_random); |
| 42 | + if !scope.is_empty() { |
| 43 | + request = request.add_scope(Scope::new(scope.join(" "))); |
| 44 | + } |
| 45 | + |
| 46 | + let (auth_url, csrf_token) = request.url(); |
| 47 | + (auth_url, csrf_token) |
| 48 | + } |
| 49 | + |
| 50 | + pub async fn exchange_code( |
| 51 | + &self, |
| 52 | + code: String, |
| 53 | + csrf_token: String, |
| 54 | + state: String, |
| 55 | + ) -> Result<(AccessToken, Option<RefreshToken>, Option<Duration>), anyhow::Error> { |
| 56 | + if state != csrf_token { |
| 57 | + return Err(anyhow::anyhow!("Invalid state")); |
| 58 | + } |
| 59 | + |
| 60 | + let code = AuthorizationCode::new(code); |
| 61 | + let token = self.client |
| 62 | + .exchange_code(code) |
| 63 | + .request_async(async_http_client) |
| 64 | + .await |
| 65 | + .context("Failed to exchange code")?; |
| 66 | + |
| 67 | + Ok((token.access_token().clone(), token.refresh_token().cloned(), token.expires_in())) |
| 68 | + } |
| 69 | +} |
0 commit comments