Skip to content

Commit

Permalink
chore: Add tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
Brayan-724 committed Sep 14, 2024
1 parent 7300a88 commit cdaa09e
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 10 deletions.
7 changes: 7 additions & 0 deletions crates/backend/src/auth/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,11 @@ pub async fn callback(
ctx: &RouterContext,
req: oauth2::HttpRequest,
) -> Result<oauth2::HttpResponse, worker::Error> {
worker::console_log!("[GITHUB] ClientId and ClientSecret obtain");
let client_id = client_id(ctx);
let client_secret = client_secret(ctx);

worker::console_log!("[GITHUB] Getting token");
let urlencoded_id: String = form_urlencoded::byte_serialize(client_id.as_bytes()).collect();
let urlencoded_secret: String =
form_urlencoded::byte_serialize(client_secret.secret().as_bytes()).collect();
Expand All @@ -136,8 +138,10 @@ pub async fn callback(
)
.unwrap();

worker::console_log!("[GITHUB] Getting access token");
let res = worker::Fetch::Request(req).send().await?;

worker::console_log!("[GITHUB] Parse response");
let res = worker::response_from_wasm(res.into())?;

Result::<oauth2::HttpResponse, worker::Error>::Ok(res_worker_to_oauth2(res).await)
Expand Down Expand Up @@ -195,12 +199,15 @@ pub async fn get_user(token: GithubToken) -> Result<GithubUser, worker::Response
)
.map_err(IntoResponse::into_response)?;

worker::console_log!("[GITHUB] Getting user data");
let mut res = worker::Fetch::Request(req)
.send()
.await
.map_err(IntoResponse::into_response)?;

let res = res.text().await.map_err(IntoResponse::into_response)?;

worker::console_log!("[REMOVE] Test response: {res}"); // XXX: Remove this
let user = serde_json::from_str::<GithubUser>(&res).map_err(IntoResponse::into_response)?;

Ok(user)
Expand Down
2 changes: 2 additions & 0 deletions crates/backend/src/auth/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ where
let route = route.clone();

async move {
worker::console_log!("Someone is trying to login");

let query_pairs = req.url().unwrap();
let query_pairs = query_pairs.query_pairs();

Expand Down
12 changes: 9 additions & 3 deletions crates/backend/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,17 @@ pub fn get_device_id(req: &worker::Request) -> Option<String> {
.ok()
.flatten()
.or_else(|| req.headers().get("x-forwarded-for").ok().flatten())
.or_else(|| req.cf().and_then(|cf| cf.city()))?;
.or_else(|| req.cf().and_then(|cf| cf.city()))
.inspect(|x| worker::console_log!("DeviceID-SiteID: {x:?}"))?;

let user_agent = req.headers().get("user-agent").ok().flatten()?;
let user_agent = req
.headers()
.get("user-agent")
.ok()
.flatten()
.inspect(|x| worker::console_log!("DeviceID-UserAgent: {x:?}"))?;

worker::console_log!("{site_id} + {user_agent}");
worker::console_log!("DeviceID: {site_id} + {user_agent}");

Some(site_id + &user_agent)
}
Expand Down
9 changes: 7 additions & 2 deletions crates/shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,18 @@ impl IntoResponse for serde_json::Error {
fn into_response(self) -> worker::Response {
worker::console_error!("{self}");

// TODO: Manage errors with more detail
let errors = match self.classify() {
serde_json::error::Category::Io => format!("{:?}, {:?}", "Cannot read IO", self.to_string()),
serde_json::error::Category::Syntax => format!("{:?}, {:?}", "Cannot deserialize: Syntax error", self.to_string()),
serde_json::error::Category::Data => format!("{:?}, {:?}", "Cannot deserialize: Invalid data", self.to_string()),
serde_json::error::Category::Eof => format!("{:?}", "Cannot deserialize: End of file. Corrupted data"),
};

ResponseBuilder::new()
.with_status(400)
.with_header(CONTENT_TYPE, "application/json; charset=utf-8")
.unwrap()
.fixed(format!(r#"{{"errors":[{:?}],"success":false}}"#, self.to_string()).into_bytes())
.fixed(format!(r#"{{"errors":[{errors}],"success":false}}"#).into_bytes())
}
}

Expand Down
17 changes: 12 additions & 5 deletions frontend/src/routes/form/[slug]/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { ApiResponse } from "$lib/models/api";
import { error, redirect } from "@sveltejs/kit";

export async function load(
{ url, params, platform, cookies }: App.LoadServerEvent<{ slug: string }>,
{ url, params, platform, cookies, request }: App.LoadServerEvent<{ slug: string }>,
) {
if (url.searchParams.has("code")) {
const code = url.searchParams.get("code")!;
Expand All @@ -20,9 +20,11 @@ export async function load(
console.log(`Loading form ${params.slug} from: ${FORM_URL}`);
const form_res = await fetch(FORM_URL);
const form = await form_res.json() as ApiResponse<Form>;
console.log("Form loaded:", form);

if (form.success) {
const code = cookies.get("external-code");
console.log("User has code: ", !!code)

if (form.data.require_login && !code) {
return {
Expand All @@ -31,15 +33,20 @@ export async function load(
};
}

console.log(`Loading session from: ${FORM_URL}/session`);
const session_res = await fetch(`${FORM_URL}/session`, {
headers: code
? {
"Authorization": `Bearer ${code}`,
"user-agent": request.headers.get("user-agent"),
}
: {},
: {
"user-agent": request.headers.get("user-agent"),
},
});

const session = await session_res.json() as ApiResponse<string>;
console.log("Session loaded:", session);

if (session.success) {
const user = session.data!;
Expand All @@ -65,10 +72,10 @@ export async function load(
user,
answers: [],
};
}

if (session_res.status === 403) {
} else if (session_res.status === 403) {
return error(session_res.status, "Already answered");
} else if (!session.success) {
return error(session_res.status, session.errors[0]);
}

return {
Expand Down

0 comments on commit cdaa09e

Please sign in to comment.