Skip to content

Commit

Permalink
some auth refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
amitu committed Oct 23, 2023
1 parent 3f236e9 commit d69d021
Show file tree
Hide file tree
Showing 7 changed files with 34 additions and 81 deletions.
24 changes: 13 additions & 11 deletions fastn-core/src/auth/github.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
// TODO: This has be set while creating the GitHub OAuth Application
pub const CALLBACK_URL: &str = "/auth/github/callback/";
pub const CALLBACK_URL: &str = "/-/auth/github/callback/";
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserDetail {
pub token: String,
pub user_name: String,
}
// route: /auth/login/
pub async fn login(req: actix_web::HttpRequest) -> fastn_core::Result<fastn_core::http::Response> {

pub async fn login(
req: &fastn_core::http::Request,
) -> fastn_core::Result<fastn_core::http::Response> {
// GitHub will be redirect to this url after login process completed

let mut next_url = "/".to_string();
Expand All @@ -22,8 +24,8 @@ pub async fn login(req: actix_web::HttpRequest) -> fastn_core::Result<fastn_core

let redirect_url: String = format!(
"{}://{}{}?next={}",
req.connection_info().scheme(),
req.connection_info().host(),
req.connection_info.scheme(),
req.connection_info.host(),
CALLBACK_URL,
next_url,
);
Expand Down Expand Up @@ -56,7 +58,9 @@ pub async fn login(req: actix_web::HttpRequest) -> fastn_core::Result<fastn_core
// route: /auth/github/callback/
// In this API we are accessing
// the token and setting it to cookies
pub async fn callback(req: actix_web::HttpRequest) -> fastn_core::Result<actix_web::HttpResponse> {
pub async fn callback(
req: &fastn_core::http::Request,
) -> fastn_core::Result<actix_web::HttpResponse> {
#[derive(serde::Deserialize)]
pub struct QueryParams {
pub code: String,
Expand All @@ -66,8 +70,8 @@ pub async fn callback(req: actix_web::HttpRequest) -> fastn_core::Result<actix_w
let query = actix_web::web::Query::<QueryParams>::from_query(req.query_string())?.0;
let auth_url = format!(
"{}://{}{}",
req.connection_info().scheme(),
req.connection_info().host(),
req.connection_info.scheme(),
req.connection_info.host(),
CALLBACK_URL
);
let client = utils::github_client().set_redirect_uri(oauth2::RedirectUrl::new(auth_url)?);
Expand All @@ -90,9 +94,7 @@ pub async fn callback(req: actix_web::HttpRequest) -> fastn_core::Result<actix_w
fastn_core::auth::AuthProviders::GitHub.as_str(),
fastn_core::auth::utils::encrypt_str(&user_detail_str).await,
)
.domain(fastn_core::auth::utils::domain(
req.connection_info().host(),
))
.domain(fastn_core::auth::utils::domain(req.connection_info.host()))
.path("/")
.permanent()
// TODO: AbrarK is running on http,
Expand Down
2 changes: 1 addition & 1 deletion fastn-core/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl AuthProviders {
}

pub fn secret_key() -> String {
match std::env::var("SECRET_KEY") {
match std::env::var("FASTN_SECRET_KEY") {
Ok(secret) => secret,
Err(_e) => {
println!("WARN: SECRET_KEY not set");
Expand Down
72 changes: 15 additions & 57 deletions fastn-core/src/auth/routes.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,14 @@
// route: /auth/login/
pub async fn login(
req: actix_web::HttpRequest,
edition: Option<String>,
external_js: Vec<String>,
inline_js: Vec<String>,
external_css: Vec<String>,
inline_css: Vec<String>,
) -> fastn_core::Result<actix_web::HttpResponse> {
if fastn_core::auth::utils::is_login(&req) {
return Ok(actix_web::HttpResponse::Found()
.append_header((actix_web::http::header::LOCATION, "/".to_string()))
.finish());
// route: /-/auth/login/
pub async fn login(req: &fastn_core::http::Request) -> fastn_core::Result<actix_web::HttpResponse> {
if fastn_core::auth::utils::is_authenticated(req) {
return Ok(fastn_core::http::redirect("/".to_string()));
}

#[derive(serde::Deserialize)]
pub struct QueryParams {
pub platform: String,
}

let query = match actix_web::web::Query::<QueryParams>::from_query(req.query_string()) {
Ok(q) => q,
Err(err) => {
Expand All @@ -28,68 +20,34 @@ pub async fn login(
match query.platform.as_str() {
"github" => fastn_core::auth::github::login(req).await,
_ => {
let mut req = fastn_core::http::Request::from_actix(req, actix_web::web::Bytes::new());
req.path = "/sorry/".to_string();
fastn_core::commands::serve::serve(
req,
edition,
external_js,
inline_js,
external_css,
inline_css,
)
.await
return Ok(actix_web::HttpResponse::BadRequest()

Check failure on line 23 in fastn-core/src/auth/routes.rs

View workflow job for this annotation

GitHub Actions / Rust Checks

unneeded `return` statement
.body("Please select the platform, by which you want to login"));
} // _ => unreachable!(),
}
}

// route: /auth/logout/
pub fn logout(req: actix_web::HttpRequest) -> fastn_core::Result<actix_web::HttpResponse> {
// route: /-/auth/logout/
pub fn logout() -> fastn_core::Result<actix_web::HttpResponse> {
// TODO: Refactor, Not happy with this code, too much of repetition of similar code
// It is logging out from all the platforms

// Ideally it should capture the platform in the request and then logged out
// only from that platform
Ok(actix_web::HttpResponse::Found()
.cookie(
actix_web::cookie::Cookie::build(fastn_core::auth::AuthProviders::GitHub.as_str(), "")
.domain(fastn_core::auth::utils::domain(
req.connection_info().host(),
))
.path("/")
.expires(actix_web::cookie::time::OffsetDateTime::now_utc())
.finish(),
)
.append_header((actix_web::http::header::LOCATION, "/".to_string()))
.finish())
}

// handle: if request.url starts with /auth/
// handle: if request.url starts with /-/auth/
#[tracing::instrument(skip_all)]
pub async fn handle_auth(
req: actix_web::HttpRequest,
edition: Option<String>,
external_js: Vec<String>,
inline_js: Vec<String>,
external_css: Vec<String>,
inline_css: Vec<String>,
req: fastn_core::http::Request,
) -> fastn_core::Result<fastn_core::http::Response> {
match req.path() {
"/auth/login/" => {
login(
req,
edition,
external_js,
inline_js,
external_css,
inline_css,
)
.await
}
fastn_core::auth::github::CALLBACK_URL => fastn_core::auth::github::callback(req).await,
"/auth/logout/" => logout(req),
_ => Ok(actix_web::HttpResponse::new(
actix_web::http::StatusCode::NOT_FOUND,
)),
"/-/auth/login/" => login(&req).await,
"/-/auth/github/" => fastn_core::auth::github::callback(&req).await,
"/-/auth/logout/" => logout(),
_ => Ok(fastn_core::not_found!("route not found: {}", req.path())),
}
}
2 changes: 1 addition & 1 deletion fastn-core/src/auth/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub async fn decrypt_str(encrypted_str: &String) -> Result<String, MagicCryptErr
mc_obj.decrypt_base64_to_string(encrypted_str)
}

pub fn is_login(req: &actix_web::HttpRequest) -> bool {
pub fn is_authenticated(req: &fastn_core::http::Request) -> bool {
let mut found_cookie = false;
for auth_provider in fastn_core::auth::AuthProviders::AUTH_ITER.iter() {
dbg!(&auth_provider);
Expand Down
12 changes: 1 addition & 11 deletions fastn-core/src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -638,24 +638,14 @@ async fn route(
return Ok(default_response);
}

if req.path().starts_with("/auth/") {
return fastn_core::auth::routes::handle_auth(
req,
app_data.edition.clone(),
app_data.external_js.clone(),
app_data.inline_js.clone(),
app_data.external_css.clone(),
app_data.inline_css.clone(),
)
.await;
}
let req = fastn_core::http::Request::from_actix(req, body);
match (req.method().to_lowercase().as_str(), req.path()) {
("post", "/-/sync/") if cfg!(feature = "remote") => sync(req).await,
("post", "/-/sync2/") if cfg!(feature = "remote") => sync2(req).await,
("get", "/-/clone/") if cfg!(feature = "remote") => clone(req).await,
("get", t) if t.starts_with("/-/view-src/") => view_source(req).await,
("get", t) if t.starts_with("/-/edit-src/") => edit_source(req).await,
("get", t) if t.starts_with("/-/auth/") => fastn_core::auth::routes::handle_auth(req).await,
("post", "/-/edit/") => edit(req).await,
("post", "/-/revert/") => revert(req).await,
("get", "/-/editor-sync/") => editor_sync(req).await,
Expand Down
2 changes: 2 additions & 0 deletions fastn-core/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ pub struct Request {
ip: Option<String>,
scheme: String,
host: String,
pub connection_info: actix_web::dev::ConnectionInfo,
// path_params: Vec<(String, )>
}

Expand All @@ -107,6 +108,7 @@ impl Request {
uri: req.uri().to_string(),
path: req.path().to_string(),
query_string: req.query_string().to_string(),
connection_info: req.connection_info().clone(),
headers,
query: {
actix_web::web::Query::<std::collections::HashMap<String, serde_json::Value>>::from_query(
Expand Down
1 change: 1 addition & 0 deletions fastn-core/src/library2022/processor/user_details.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub fn process(
for auth_provider in fastn_core::auth::AuthProviders::AUTH_ITER.iter() {
if req.cookie(auth_provider.as_str()).is_some() {
found_cookie = true;
break;
}
}
found_cookie
Expand Down

0 comments on commit d69d021

Please sign in to comment.