Skip to content

Commit

Permalink
Merge pull request #827 from hanbings/update-oauth2
Browse files Browse the repository at this point in the history
Updated oauth2 crates to version 5.0.0.
  • Loading branch information
benjamin-747 authored Feb 6, 2025
2 parents 0321a89 + de4497b commit 767cd35
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 19 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ home = "0.5.9"
ring = "0.17.8"
cedar-policy = "4.3.1"
secp256k1 = "0.30.0"
oauth2 = "4.4.2"
oauth2 = "5.0.0"
base64 = "0.22.1"
encoding_rs = "0.8.31"

Expand Down
31 changes: 28 additions & 3 deletions mono/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ use std::path::PathBuf;

use async_session::MemoryStore;
use axum::extract::FromRef;
use oauth2::basic::BasicClient;
use oauth2::{
basic::{
BasicErrorResponse, BasicRevocationErrorResponse, BasicTokenIntrospectionResponse,
BasicTokenResponse,
},
Client, EndpointNotSet, EndpointSet, StandardRevocableToken,
};

use ceres::{
api_service::{
Expand All @@ -24,11 +30,30 @@ pub mod mr;
pub mod oauth;
pub mod user;

pub type GithubClient<
HasAuthUrl = EndpointSet,
HasDeviceAuthUrl = EndpointNotSet,
HasIntrospectionUrl = EndpointNotSet,
HasRevocationUrl = EndpointNotSet,
HasTokenUrl = EndpointSet,
> = Client<
BasicErrorResponse,
BasicTokenResponse,
BasicTokenIntrospectionResponse,
StandardRevocableToken,
BasicRevocationErrorResponse,
HasAuthUrl,
HasDeviceAuthUrl,
HasIntrospectionUrl,
HasRevocationUrl,
HasTokenUrl,
>;

#[derive(Clone)]
pub struct MonoApiServiceState {
pub context: Context,
pub common: CommonOptions,
pub oauth_client: Option<BasicClient>,
pub oauth_client: Option<GithubClient>,
// TODO: Replace MemoryStore
pub store: Option<MemoryStore>,
}
Expand All @@ -39,7 +64,7 @@ impl FromRef<MonoApiServiceState> for MemoryStore {
}
}

impl FromRef<MonoApiServiceState> for BasicClient {
impl FromRef<MonoApiServiceState> for GithubClient {
fn from_ref(state: &MonoApiServiceState) -> Self {
state.oauth_client.clone().unwrap()
}
Expand Down
36 changes: 21 additions & 15 deletions mono/src/api/oauth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use callisto::user;
use chrono::{Duration, Utc};
use http::{header, request::Parts, StatusCode};
use oauth2::{
basic::BasicClient, reqwest::async_http_client, AuthUrl, AuthorizationCode, ClientId,
ClientSecret, CsrfToken, RedirectUrl, Scope, TokenResponse, TokenUrl,
AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, RedirectUrl, Scope,
TokenResponse, TokenUrl,
};

use common::config::OauthConfig;
Expand All @@ -23,6 +23,8 @@ use model::{GitHubUserJson, LoginUser, OauthCallbackParams};
use crate::api::error::ApiError;
use crate::api::MonoApiServiceState;

use super::GithubClient;

pub mod model;

static COOKIE_NAME: &str = "SESSION";
Expand All @@ -34,7 +36,7 @@ pub fn routers() -> Router<MonoApiServiceState> {
.route("/logout", get(logout))
}

async fn github_auth(State(client): State<BasicClient>) -> impl IntoResponse {
async fn github_auth(State(client): State<GithubClient>) -> impl IntoResponse {
// Issue for adding check to this example https://github.com/tokio-rs/axum/issues/2511
let (auth_url, _csrf_token) = client
.authorize_url(CsrfToken::new_random)
Expand All @@ -46,14 +48,19 @@ async fn github_auth(State(client): State<BasicClient>) -> impl IntoResponse {
async fn login_authorized(
Query(query): Query<OauthCallbackParams>,
State(state): State<MonoApiServiceState>,
State(oauth_client): State<BasicClient>,
State(oauth_client): State<GithubClient>,
) -> Result<impl IntoResponse, ApiError> {
let store: MemoryStore = MemoryStore::from_ref(&state);
let config = state.context.config.oauth.as_ref().unwrap();

let http_client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;

// Get an auth token
let token = oauth_client
.exchange_code(AuthorizationCode::new(query.code.clone()))
.request_async(async_http_client)
.request_async(&http_client)
.await
.context("failed in sending request request to authorization server")?;

Expand Down Expand Up @@ -160,7 +167,7 @@ async fn logout(
Ok((headers, Redirect::to(&config.ui_domain)))
}

pub fn oauth_client(oauth_config: OauthConfig) -> Result<BasicClient, ApiError> {
pub fn oauth_client(oauth_config: OauthConfig) -> Result<GithubClient, ApiError> {
let client_id = oauth_config.github_client_id;
let client_secret = oauth_config.github_client_secret;
let ui_domain = oauth_config.ui_domain;
Expand All @@ -171,15 +178,14 @@ pub fn oauth_client(oauth_config: OauthConfig) -> Result<BasicClient, ApiError>

let token_url = "https://github.com/login/oauth/access_token".to_string();

Ok(BasicClient::new(
ClientId::new(client_id),
Some(ClientSecret::new(client_secret)),
AuthUrl::new(auth_url).context("failed to create new authorization server URL")?,
Some(TokenUrl::new(token_url).context("failed to create new token endpoint URL")?),
)
.set_redirect_uri(
RedirectUrl::new(redirect_url).context("failed to create new redirection URL")?,
))
let client = GithubClient::new(ClientId::new(client_id))
.set_client_secret(ClientSecret::new(client_secret))
.set_auth_uri(AuthUrl::new(auth_url)?)
.set_token_uri(TokenUrl::new(token_url)?)
// Set the URL the user will be redirected to after the authorization process.
.set_redirect_uri(RedirectUrl::new(redirect_url)?);

Ok(client)
}

pub struct AuthRedirect;
Expand Down

1 comment on commit 767cd35

@vercel
Copy link

@vercel vercel bot commented on 767cd35 Feb 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

mega – ./

mega-gitmono.vercel.app
www.gitmega.dev
mega-git-main-gitmono.vercel.app
gitmega.dev

Please sign in to comment.