Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expose endpoint for google auth url #590

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ssr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ release-lib = [
"cloudflare",
"redis-kv",
"backend-admin",
"dep:openidconnect",
"oauth-hydrate",
"ga4",
]
Expand Down
19 changes: 15 additions & 4 deletions ssr/src/app.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::page::icpump::ai::ICPumpAi;
use crate::page::icpump::ICPumpLanding;

use crate::utils::host::show_preview_component;
// use crate::page::wallet::TestIndex;
use crate::{
component::{base_route::BaseRoute, nav::NavBar},
Expand Down Expand Up @@ -47,8 +48,13 @@ fn GoogleAuthRedirectHandlerRoute() -> impl IntoView {
let path = "/auth/google_redirect";
#[cfg(any(feature = "oauth-ssr", feature = "oauth-hydrate"))]
{
use crate::page::google_redirect::GoogleRedirectHandler;
view! { <Route path view=GoogleRedirectHandler/> }
if show_preview_component() {
use crate::page::google_redirect::PreviewGoogleRedirectHandler;
view! { <Route path view=PreviewGoogleRedirectHandler/> }
} else {
use crate::page::google_redirect::GoogleRedirectHandler;
view! { <Route path view=GoogleRedirectHandler/> }
}
}
#[cfg(not(any(feature = "oauth-ssr", feature = "oauth-hydrate")))]
{
Expand All @@ -61,8 +67,13 @@ fn GoogleAuthRedirectorRoute() -> impl IntoView {
let path = "/auth/perform_google_redirect";
#[cfg(any(feature = "oauth-ssr", feature = "oauth-hydrate"))]
{
use crate::page::google_redirect::GoogleRedirector;
view! { <Route path view=GoogleRedirector/> }
if show_preview_component() {
use crate::page::google_redirect::PreviewGoogleRedirector;
view! { <Route path view=PreviewGoogleRedirector/> }
} else {
use crate::page::google_redirect::GoogleRedirector;
view! { <Route path view=GoogleRedirector/> }
}
}
#[cfg(not(any(feature = "oauth-ssr", feature = "oauth-hydrate")))]
{
Expand Down
26 changes: 21 additions & 5 deletions ssr/src/auth/server_impl/google.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use openidconnect::{
core::CoreAuthenticationFlow, reqwest::async_http_client, AuthorizationCode, CsrfToken, Nonce,
PkceCodeChallenge, PkceCodeVerifier, Scope,
};
use serde::{Deserialize, Serialize};
use web_time::Duration;

use crate::auth::{
Expand All @@ -25,19 +26,33 @@ use super::{set_cookies, store::KVStoreImpl};
const PKCE_VERIFIER_COOKIE: &str = "google-pkce-verifier";
const CSRF_TOKEN_COOKIE: &str = "google-csrf-token";

#[derive(Serialize, Deserialize)]
struct OAuthState {
pub csrf_token: CsrfToken,
pub client_redirect_uri: Option<String>,
}

pub async fn google_auth_url_impl(
oauth2: openidconnect::core::CoreClient,
client_redirect_uri: Option<String>,
) -> Result<String, ServerFnError> {
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
let (auth_url, csrf_token, _) = oauth2

let oauth_state = OAuthState {
csrf_token: CsrfToken::new_random(),
client_redirect_uri,
};

let oauth2_request = oauth2
.authorize_url(
CoreAuthenticationFlow::AuthorizationCode,
CsrfToken::new_random,
move || CsrfToken::new(serde_json::to_string(&oauth_state).unwrap()),
Nonce::new_random,
)
.add_scope(Scope::new("openid".into()))
.set_pkce_challenge(pkce_challenge)
.url();
.set_pkce_challenge(pkce_challenge);

let (auth_url, oauth_csrf_token, _) = oauth2_request.url();

let key: Key = expect_context();
let mut jar: PrivateCookieJar = extract_with_state(&key).await?;
Expand All @@ -49,7 +64,8 @@ pub async fn google_auth_url_impl(
.max_age(cookie_life)
.build();
jar = jar.add(pkce_cookie);
let csrf_cookie = Cookie::build((CSRF_TOKEN_COOKIE, csrf_token.secret().clone()))

let csrf_cookie = Cookie::build((CSRF_TOKEN_COOKIE, oauth_csrf_token.secret().clone()))
.same_site(SameSite::None)
.path("/")
.max_age(cookie_life)
Expand Down
168 changes: 159 additions & 9 deletions ssr/src/page/google_redirect.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use leptos::*;
use leptos_router::*;
use openidconnect::CsrfToken;
use serde::{Deserialize, Serialize};
use server_fn::codec::Json;
use server_fn::codec::{GetUrl, Json};

use crate::{component::loading::Loading, utils::route::go_to_root};
use yral_types::delegated_identity::DelegatedIdentityWire;
Expand All @@ -21,11 +22,50 @@ async fn google_auth_redirector() -> Result<(), ServerFnError> {
let oauth_clients: CoreClients = expect_context();
let oauth2 = oauth_clients.get_oauth_client(host);

let url = google_auth_url_impl(oauth2).await?;
let url = google_auth_url_impl(oauth2, None).await?;
leptos_axum::redirect(&url);
Ok(())
}

#[server]
async fn preview_google_auth_redirector() -> Result<(), ServerFnError> {
use http::header::HeaderMap;
use leptos_axum::extract;

let headers: HeaderMap = extract().await?;
let host = headers.get("Host").unwrap().to_str().unwrap();
let client_redirect_uri = format!("{}/auth/google_redirect", host);

let client = reqwest::Client::new();
let url = format!(
"https://yral.com/api/google_auth_url?client_redirect_uri={}",
client_redirect_uri
);

let redirect_url: String = client.get(url).send().await?.json().await?;

leptos_axum::redirect(&redirect_url);

Ok(())
}

#[server(endpoint = "google_auth_url", input = GetUrl, output = Json)]
async fn google_auth_url(client_redirect_uri: String) -> Result<String, ServerFnError> {
use crate::auth::core_clients::CoreClients;
use crate::auth::server_impl::google::google_auth_url_impl;
use http::header::HeaderMap;
use leptos_axum::extract;

let headers: HeaderMap = extract().await?;

let host = headers.get("Host").unwrap().to_str().unwrap();
let oauth_clients: CoreClients = expect_context();
let oauth2 = oauth_clients.get_oauth_client(host);
let url = google_auth_url_impl(oauth2, Some(client_redirect_uri)).await?;

Ok(url)
}

#[server(endpoint = "perform_google_auth", input = Json, output = Json)]
async fn perform_google_auth(oauth: OAuthQuery) -> Result<DelegatedIdentityWire, ServerFnError> {
use crate::auth::core_clients::CoreClients;
Expand Down Expand Up @@ -76,22 +116,63 @@ pub fn IdentitySender(identity_res: GoogleAuthMessage) -> impl IntoView {
}
}

async fn handle_oauth_query(query: Result<OAuthQuery, ParamsError>) -> GoogleAuthMessage {
let Ok(oauth_query) = query else {
go_to_root();
return Err("Invalid query".to_string());
};
async fn handle_oauth_query(oauth_query: OAuthQuery) -> GoogleAuthMessage {
let delegated = perform_google_auth(oauth_query)
.await
.map_err(|e| e.to_string())?;
Ok(delegated)
}

#[server]
async fn preview_handle_oauth_query(
oauth_query: OAuthQuery,
) -> Result<DelegatedIdentityWire, ServerFnError> {
let client = reqwest::Client::new();

let yral_url = "https://yral.com/api/perform_google_auth".to_string();

let response = client.post(yral_url).json(&oauth_query).send().await?;

let result: DelegatedIdentityWire = response.json().await?;
Ok(result)
}

#[server]
async fn handle_oauth_query_for_external_client(
client_redirect_uri: String,
oauth_query: OAuthQuery,
) -> Result<(), ServerFnError> {
leptos_axum::redirect(&format!(
"{}?oauth={}",
client_redirect_uri,
serde_json::to_string(&oauth_query).unwrap()
));
Ok(())
}

#[derive(Serialize, Deserialize, Clone)]
enum RedirectHandlerReturnType {
Identity(GoogleAuthMessage),
ExternalClient(Result<(), String>),
}

#[derive(Serialize, Deserialize)]
struct OAuthState {
pub csrf_token: CsrfToken,
pub client_redirect_uri: Option<String>,
}

#[component]
pub fn GoogleRedirectHandler() -> impl IntoView {
pub fn PreviewGoogleRedirectHandler() -> impl IntoView {
let query = use_query::<OAuthQuery>();
let identity_resource = create_blocking_resource(query, |query_res| async move {
handle_oauth_query(query_res).await
let Ok(oauth_query) = query_res else {
return Err("Invalid Params".to_string());
};

preview_handle_oauth_query(oauth_query)
.await
.map_err(|e| e.to_string())
});

view! {
Expand All @@ -106,6 +187,75 @@ pub fn GoogleRedirectHandler() -> impl IntoView {
}
}

#[component]
pub fn GoogleRedirectHandler() -> impl IntoView {
let query = use_query::<OAuthQuery>();
let identity_resource = create_blocking_resource(query, |query_res| async move {
let Ok(oauth_query) = query_res else {
return RedirectHandlerReturnType::Identity(Err("Invalid query".to_string()));
};

let Ok(oauth_state) = serde_json::from_str::<OAuthState>(&oauth_query.state) else {
return RedirectHandlerReturnType::Identity(Err("Invalid OAuth State".to_string()));
};

if oauth_state.client_redirect_uri.is_some() {
let res = handle_oauth_query_for_external_client(
oauth_state.client_redirect_uri.unwrap(),
oauth_query,
)
.await
.map_err(|e| e.to_string());
RedirectHandlerReturnType::ExternalClient(res)
} else {
let res = handle_oauth_query(oauth_query).await;
RedirectHandlerReturnType::Identity(res)
}
});

view! {
<Loading text="Logging out...".to_string()>
<Suspense>
{move || {
identity_resource()
.map(|identity_res: RedirectHandlerReturnType| match identity_res {
RedirectHandlerReturnType::Identity(identity_res) => {
view! { <IdentitySender identity_res/> }.into_view()
}
RedirectHandlerReturnType::ExternalClient(_) => view! {}.into_view(),
})
}}

</Suspense>
</Loading>
}
}

#[component]
pub fn PreviewGoogleRedirector() -> impl IntoView {
let google_redirect = create_blocking_resource(|| {}, |_| preview_google_auth_redirector());
let do_close = create_rw_signal(false);
create_effect(move |_| {
if !do_close() {
return;
}
let window = window();
_ = window.close();
});

view! {
<Suspense>
{move || {
if let Some(Err(_)) = google_redirect() {
do_close.set(true);
}
None::<()>
}}

</Suspense>
}
}

#[component]
pub fn GoogleRedirector() -> impl IntoView {
let google_redirect = create_blocking_resource(|| (), |_| google_auth_redirector());
Expand Down
5 changes: 5 additions & 0 deletions ssr/src/utils/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ pub fn show_cdao_page() -> bool {
show_cdao_condition(host)
}

pub fn show_preview_component() -> bool {
let host = get_host();
host.contains("yral-dapp-hot-or-not-web-leptos-ssr.fly.dev")
}

pub fn show_cdao_condition(host: String) -> bool {
host == "icpump.fun"
// || host == "localhost:3000"
Expand Down
Loading