Skip to content

Commit

Permalink
feat: remove unneeded logic
Browse files Browse the repository at this point in the history
  • Loading branch information
speed2exe committed Oct 8, 2024
1 parent c477931 commit 1a694df
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 76 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion admin_frontend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,3 @@ rand = "0.8.5"
sha2 = "0.10.8"
base64 = "0.22.1"
urlencoding = "2.1.3"
serde_urlencoded = "0.7.1"
5 changes: 4 additions & 1 deletion admin_frontend/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,17 @@ pub struct WebAppOAuthLoginRequest {

// Use actions (with params) after login
pub action: Option<OAuthLoginAction>,

// Workspace Invitation
pub workspace_invitation_id: Option<String>,
pub workspace_name: Option<String>,
pub workspace_icon: Option<String>,
pub user_name: Option<String>,
pub user_icon: Option<String>,
pub workspace_member_count: Option<String>,

// pub redirect
// Redirect
pub redirect_to: Option<String>,

// Errors
pub error: Option<String>,
Expand Down
63 changes: 3 additions & 60 deletions admin_frontend/src/session.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use std::{
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use std::time::{SystemTime, UNIX_EPOCH};

use axum::{
async_trait,
extract::{FromRequestParts, OriginalUri},
http::{header, request::Parts, HeaderMap, StatusCode},
http::request::Parts,
response::{IntoResponse, Redirect},
};
use axum_extra::extract::{cookie::Cookie, CookieJar};
Expand All @@ -16,7 +13,7 @@ use jwt::{Claims, Header};
use redis::{aio::ConnectionManager, AsyncCommands, FromRedisValue, ToRedisArgs};
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::{ext::api::verify_token_cloud, AppState};
use crate::AppState;

static SESSION_EXPIRATION: usize = 60 * 60 * 24; // 1 day

Expand Down Expand Up @@ -159,60 +156,6 @@ impl FromRequestParts<AppState> for UserSession {
.get::<OriginalUri>()
.map(|uri| urlencoding::encode(&uri.to_string()).to_string());

// attempt to redirect after setting new session
if let Some(p) = parts.uri.query() {
match serde_urlencoded::from_str::<HashMap<String, String>>(p) {
Ok(params) => {
if let Some(refresh_token) = params.get("refresh_token") {
match state
.gotrue_client
.token(&gotrue::grant::Grant::RefreshToken(
gotrue::grant::RefreshTokenGrant {
refresh_token: refresh_token.to_string(),
},
))
.await
{
Ok(token) => {
match verify_token_cloud(
token.access_token.as_str(),
state.appflowy_cloud_url.as_str(),
)
.await
{
Ok(()) => {
let new_session_id = uuid::Uuid::new_v4();
let new_session = UserSession {
session_id: new_session_id.to_string(),
token,
};
state
.session_store
.put_user_session(&new_session)
.await
.unwrap();

let session_cookie = jar.add(new_session_cookie(new_session_id));

if let Some(original_url) = original_url {
let mut headers = HeaderMap::new();
headers.insert(header::LOCATION, original_url.parse().unwrap());
return Err((StatusCode::SEE_OTHER, headers, session_cookie).into_response());
}
},
Err(err) => {
tracing::warn!("failed to verify token: {}", format!("{:?}", err))
},
}
},
Err(err) => tracing::error!("failed to refresh token: {}", err),
};
}
},
Err(err) => tracing::error!("failed to parse query params: {}", err),
}
}

match original_url {
Some(url) => Err(Redirect::to(&format!("/web/login?redirect_to={}", url)).into_response()),
None => Err(Redirect::to("/web/login").into_response()),
Expand Down
1 change: 1 addition & 0 deletions admin_frontend/src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ pub struct ChangePassword;
pub struct Login<'a> {
pub oauth_providers: &'a [&'a str],
pub redirect_to: Option<&'a str>,
pub oauth_redirect_to: Option<&'a str>,
}

#[derive(Template)]
Expand Down
16 changes: 7 additions & 9 deletions admin_frontend/src/web_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -580,15 +580,13 @@ async fn session_login(
};
state.session_store.put_user_session(&new_session).await?;

let decoded_redirect_to = redirect_to
.map(|s| match urlencoding::decode(s) {
Ok(r) => Some(r),
Err(err) => {
tracing::error!("failed to decode redirect_to: {}", err);
None
},
})
.flatten();
let decoded_redirect_to = redirect_to.and_then(|s| match urlencoding::decode(s) {
Ok(r) => Some(r),
Err(err) => {
tracing::error!("failed to decode redirect_to: {}", err);
None
},
});

Ok(
(
Expand Down
27 changes: 24 additions & 3 deletions admin_frontend/src/web_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,22 @@ async fn login_callback_query_handler(
return Ok(redirect_html.into_response());
};
let open_or_dl_html = render_template(templates::OpenAppFlowyOrDownload {})?;
return Ok((jar, open_or_dl_html).into_response());
Ok((jar, open_or_dl_html).into_response())
},
},
None => home_handler(State(state), new_session, jar).await,
None => match query.redirect_to {
Some(redirect_url) => match urlencoding::decode(&redirect_url).map(String::from) {
Ok(redirect_url) => {
let redirect_html = render_template(templates::Redirect { redirect_url })?;
Ok((jar, redirect_html).into_response())
},
Err(err) => {
tracing::error!("Error decoding redirect_url: {:?}", err);
home_handler(State(state), new_session, jar).await
},
},
None => home_handler(State(state), new_session, jar).await,
},
}
}

Expand Down Expand Up @@ -351,13 +363,22 @@ async fn login_handler(
) -> Result<Html<String>, WebAppError> {
let redirect_to = login
.redirect_to
.map(|r| urlencoding::encode(&r).to_string());
.as_ref()
.map(|r| urlencoding::encode(r).to_string());
let oauth_redirect_to = login.redirect_to.as_ref().map(|r| {
urlencoding::encode(&format!(
"/web/login-callback?redirect_to={}",
urlencoding::encode(r)
))
.to_string()
});

let external = state.gotrue_client.settings().await?.external;
let oauth_providers = external.oauth_providers();
render_template(templates::Login {
oauth_providers: &oauth_providers,
redirect_to: redirect_to.as_deref(),
oauth_redirect_to: oauth_redirect_to.as_deref(),
})
}

Expand Down
2 changes: 1 addition & 1 deletion admin_frontend/templates/pages/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ <h3>OAuth Login</h3>
<div id="oauth-container">
{% for provider in oauth_providers %}
<div class="oauth-icon">
<a href="/gotrue/authorize?provider={{ provider|escape }}&redirect_to={{ redirect_to|default("/web/login-callback")|escape }}">
<a href="/gotrue/authorize?provider={{ provider|escape }}&redirect_to={{ oauth_redirect_to|default("/web/login-callback")|escape }}">
<div
hx-get="../assets/{{ provider|escape }}/logo.html"
hx-trigger="load"
Expand Down

0 comments on commit 1a694df

Please sign in to comment.