Skip to content

Commit

Permalink
Merge pull request #71 from go-bazzinga/login-system-workflow-change
Browse files Browse the repository at this point in the history
on auth_init load process request
  • Loading branch information
rosarp-gobazzinga authored Mar 15, 2024
2 parents 7fab487 + 169b25f commit 26e33bd
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 94 deletions.
8 changes: 4 additions & 4 deletions src/auth/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ pub fn key_pair() -> Result<KeyPair, String> {
.public_key()
.to_string()
.replace('\n', "")
// .strip_prefix("-----BEGIN PUBLIC KEY-----")
// .unwrap()
// .strip_suffix("-----END PUBLIC KEY-----")
// .unwrap()
.strip_prefix("-----BEGIN PUBLIC KEY-----")
.unwrap()
.strip_suffix("-----END PUBLIC KEY-----")
.unwrap()
.to_owned();
let private_key = secret.to_bytes().to_vec();
let pem = secret
Expand Down
1 change: 0 additions & 1 deletion src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@ pub struct AppConfig {

#[derive(Debug, Deserialize, Clone)]
pub struct AuthConfig {
pub cookie_domain: String,
pub ic_url: String,
pub sign_key: String,
pub auth_domain: String,
Expand Down
5 changes: 2 additions & 3 deletions src/page/anonymous.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@ pub fn AnonymousIdentity() -> impl IntoView {
}
Err(error) => error.to_string(),
};
let window = use_window();
let opener = window.as_ref().unwrap().parent().unwrap().unwrap();
let parent = use_window().as_ref().unwrap().parent().unwrap().unwrap();
// TODO: skip for window.self
match opener.post_message(&JsValue::from_str(&message), constants::APP_DOMAIN.as_str())
match parent.post_message(&JsValue::from_str(&message), constants::APP_DOMAIN.as_str())
{
Err(error) => log!("post result: {:?}", error),
Ok(_) => {}
Expand Down
102 changes: 43 additions & 59 deletions src/page/auth_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,65 +7,51 @@ use leptos::{
use leptos_use::{use_event_listener, use_window};
use reqwest::Url;
use wasm_bindgen::JsValue;
use web_sys::Window;

#[component]
pub fn staging() -> impl IntoView {
_ = use_event_listener(use_window(), ev::message, move |msg| {
let message = msg.data().as_string();
let url_origin = Url::parse(&msg.origin());
if url_origin
.clone()
.map(|u| u.origin() != constants::APP_DOMAIN.origin())
.unwrap_or_default()
{
match message.as_deref() {
Some("login") => {
let url = create_local_resource(move || (), |_| get_redirect_url());
create_effect(move |_| match url.get() {
Some(Ok(u)) => {
let window = use_window();
let window = window.as_ref().unwrap();
let _ = window.open_with_url_and_target(&u, "_blank");
let url = create_local_resource(move || (), |_| get_redirect_url());
create_effect(move |_| match url.get() {
Some(Ok(u)) => {
let window = use_window();
let window = window.as_ref().unwrap();
let _new_window = window.open_with_url_and_target(&u, "_blank");

let _ = use_event_listener(use_window(), ev::message, move |msg| {
let message = msg.data().as_string();

if Url::parse(&msg.origin())
.map(|u| u.origin() == constants::AUTH_DOMAIN.origin())
.unwrap_or_default()
{
match message.as_deref() {
Some("Invalid parameters") | Some("Invalid credentials") => {
// TODO: send back error message to ssr
error!("{}", message.unwrap());
}
Some(session) => {
log!("session received: {}", session.len());
let parent = use_window().as_ref().unwrap().parent().unwrap().unwrap();
match parent.post_message(
&JsValue::from_str(&session),
constants::APP_DOMAIN.as_str(),
) {
Err(error) => error!(
"post result to app failed: {}",
error.as_string().unwrap_or("".to_owned())
),
Ok(_) => log!("session posted"),
}
}
None => {
// no action
}
Some(Err(error)) => warn!("Failed to generate url: {}", error),
None => error!("No url generated"),
});
}
_ => {
// no action
}
}
} else if url_origin
.map(|u| u.origin() != constants::AUTH_DOMAIN.origin())
.unwrap_or_default()
{
match message.as_deref() {
Some("Invalid parameters")
| Some("Invalid credentials")
| Some("No server response") => {
// TODO: send back error message to ssr
}
Some(session) => {
let window = use_window();
let window = window.as_ref().unwrap();
let opener = window.opener().unwrap();
let opener = Window::from(opener);
match opener
.post_message(&JsValue::from_str(&session), constants::APP_DOMAIN.as_str())
{
Err(error) => log!(
"post result to app failed: {}",
error.as_string().unwrap_or("".to_owned())
),
Ok(_) => {}
}
}
_ => {
// no action
}
}
});
}
Some(Err(error)) => warn!("Failed to generate url: {}", error),
None => {}
});

view! {
Expand Down Expand Up @@ -94,12 +80,10 @@ pub async fn get_redirect_url() -> Result<String, ServerFnError> {
let user_identity = URL_SAFE.encode(user_identity.value());
let expiration = URL_SAFE.encode(expiration.value());

let url = format!(
"{}/verify_creds?u={}&e={}",
app_state.auth_domain.as_str(),
user_identity,
expiration
);
let mut url = app_state.auth_domain.join("verify_creds").unwrap();
url.set_query(Some(
format!("u={}&e={}", user_identity, expiration).as_str(),
));

Ok(url)
Ok(url.as_str().to_owned())
}
44 changes: 28 additions & 16 deletions src/page/verify_creds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,22 @@ use leptos::{logging::error, *};

#[component]
pub fn verify_creds() -> impl IntoView {
use leptos_router::use_params_map;
use leptos_router::use_query_map;
use leptos_use::use_window;

let params = use_params_map();
let user_identity = move || params.with(|params| params.get("u").cloned());
let expiration = move || params.with(|params| params.get("e").cloned());
let params = use_query_map();
let user_identity = move || params.with_untracked(|params| params.get("u").cloned());
let expiration = move || params.with_untracked(|params| params.get("e").cloned());

if user_identity().is_none() || expiration().is_none() {
handle_error("Invalid parameters");
handle_error(
format!(
"Invalid parameters: u: {} e: {}",
user_identity().is_some(),
expiration().is_some()
)
.as_str(),
);
}

let resource = create_local_resource(
Expand All @@ -36,10 +43,7 @@ pub fn verify_creds() -> impl IntoView {
error!("Error verifying credentials: {}", error.to_string());
handle_error("Invalid credentials");
}
None => {
error!("No server response!");
handle_error("No server response");
}
None => {}
});

view! {
Expand All @@ -52,18 +56,26 @@ fn handle_error(message: &str) {
use crate::constants;
use leptos_use::use_window;
use wasm_bindgen::JsValue;
use web_sys::Window;

error!("handle error: {}", message);

let window = use_window();
let window = window.as_ref().unwrap();
let opener = window.parent().unwrap().unwrap();
let opener = window.opener().unwrap();
let opener = Window::from(opener);
match opener.post_message(
&JsValue::from_str(&message),
&constants::AUTH_DOMAIN.host_str().unwrap(),
&constants::AUTH_DOMAIN.as_str(),
) {
Err(error) => error!("post result: {:?}", error),
Ok(_) => {}
Err(error) => {
error!("post result: {:?}", error);
let _ = window.close();
}
Ok(_) => {
let _ = window.close();
}
}
let _ = window.close();
}

#[server]
Expand Down Expand Up @@ -96,13 +108,13 @@ pub async fn verify_payload(
"user_identity",
user_identity,
auth_domain.to_owned(),
SameSite::Strict,
SameSite::None,
)
.await;
jar = jar.add(user_cookie);

let expiration =
cookie::create_cookie("expiration", expiration, auth_domain, SameSite::Strict).await;
cookie::create_cookie("expiration", expiration, auth_domain, SameSite::None).await;
jar = jar.add(expiration);

let jar_into_response = jar.into_response();
Expand Down
24 changes: 14 additions & 10 deletions src/providers/google.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ async fn google_auth_url() -> Result<String, ServerFnError> {
// enable after integration
let signed_jar: SignedCookieJar =
leptos_axum::extract_with_state::<SignedCookieJar<Key>, AppState>(&app_state).await?;
let _user_identity = match signed_jar.get("user_identity") {
let user_identity = match signed_jar.get("user_identity") {
Some(val) => Some(val.value().to_owned()),
None => None,
}
Expand Down Expand Up @@ -68,7 +68,7 @@ async fn google_auth_url() -> Result<String, ServerFnError> {
"pkce_verifier",
pkce_verifier.to_owned(),
auth_domain.to_owned(),
SameSite::Strict,
SameSite::None,
)
.await;
// jar = jar.remove(Cookie::from("pkce_verifier"));
Expand All @@ -77,7 +77,7 @@ async fn google_auth_url() -> Result<String, ServerFnError> {
"csrf_token",
csrf_token.to_owned(),
auth_domain,
SameSite::Strict,
SameSite::None,
)
.await;
// jar = jar.remove(Cookie::from("csrf_token"));
Expand Down Expand Up @@ -270,7 +270,7 @@ pub fn OAuth2Response() -> impl IntoView {
if let Some(Ok(session_response)) = handle_oauth2_redirect.value().get() {
let message = match serde_json::to_string(&session_response) {
Ok(session) => {
leptos::logging::log!("Session: {}", session.len());
log!("Session: {}", session.len());
session
}
Err(error) => error.to_string(),
Expand All @@ -283,13 +283,17 @@ pub fn OAuth2Response() -> impl IntoView {
&JsValue::from_str(&message),
constants::AUTH_DOMAIN.as_str(),
) {
Err(error) => log!(
"post result to auth failed: {}",
error.as_string().unwrap_or("".to_owned())
),
Ok(_) => {}
Err(error) => {
log!(
"post result to auth failed: {}",
error.as_string().unwrap_or("".to_owned())
);
// let _ = window.close();
}
Ok(_) => {
let _ = window.close();
}
}
let _ = window.close();
}
});

Expand Down
2 changes: 1 addition & 1 deletion src/store/cloudflare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub async fn delete_kv(key_name: &str, cloudflare_config: &ApiClientConfig) -> O
match cloudflare_config.cloudflare_client.send(end_point).await {
Ok(result) => {
info!("delete: {:?}", result);
Some(result.result.unwrap())
result.result
}
Err(error) => {
error!("delete error: {}", error);
Expand Down

0 comments on commit 26e33bd

Please sign in to comment.