Skip to content

Commit

Permalink
feat: secure cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
112batuhan committed Dec 2, 2024
1 parent 2f81b76 commit 1f23449
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 16 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ path = "src/main.rs"
name = "convert"
path = "src/conversion.rs"

[[bin]]
name = "import_users"
path = "src/user_import.rs"

[dependencies]
aide = { version = "0.13", features = ["axum", "axum-extra", "macros"] }
async-trait = "0.1.83"
Expand Down
24 changes: 23 additions & 1 deletion src/conversion.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
use futures::future::join_all;
use hashlink::LinkedHashSet;
use mapper_influences_backend_rs::daily_update::update_once;
use mapper_influences_backend_rs::database::{numerical_thing, DatabaseClient};
use mapper_influences_backend_rs::osu_api::credentials_grant::CredentialsGrantClient;
use mapper_influences_backend_rs::osu_api::request::OsuApiRequestClient;
use mapper_influences_backend_rs::osu_api::Group;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::BufReader;
use std::sync::Arc;
use std::time::Duration;
use surrealdb::sql::Thing;
use surrealdb_migrations::MigrationRunner;

Expand Down Expand Up @@ -128,6 +132,10 @@ where
async fn main() {
dotenvy::dotenv().ok();

tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();

let path = "./conversion/users.json";
let users: Vec<User> = read_json_file(path);

Expand Down Expand Up @@ -201,7 +209,7 @@ async fn main() {

let mut handlers = Vec::new();
let arc_db = db.clone();
for user in full_users {
for user in full_users.clone() {
let order_vec: Vec<u32> = user
.user
.influence_order
Expand All @@ -224,5 +232,19 @@ async fn main() {
join_all(handlers).await;
println!("custom order insertion done");

let user_ids = full_users.into_iter().map(|user| user.user.id).collect();
let request_client = Arc::new(OsuApiRequestClient::new(100));
let credentials_grant_client = CredentialsGrantClient::new(request_client).await.unwrap();

let unsuccessfuls = update_once(
credentials_grant_client,
db,
user_ids,
Duration::from_millis(100),
)
.await;

dbg!(unsuccessfuls);

println!("done");
}
7 changes: 6 additions & 1 deletion src/daily_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,22 @@ pub async fn update_once(
database: Arc<DatabaseClient>,
users_to_update: Vec<u32>,
wait_duration: Duration,
) {
) -> Vec<u32> {
let mut interval = tokio::time::interval(wait_duration);

let mut unsuccessfull_ids = Vec::new();
for user_id in users_to_update {
interval.tick().await;
let Ok(user) = client.get_user_osu(user_id).await else {
unsuccessfull_ids.push(user_id);
tracing::error!(
"Failed to request {} from osu! API for daily update",
user_id
);
continue;
};
let Ok(_) = database.upsert_user(user).await else {
unsuccessfull_ids.push(user_id);
tracing::error!(
"Failed to insert user {} to database for daily update",
user_id
Expand All @@ -29,6 +33,7 @@ pub async fn update_once(
};
tracing::debug!("Requested and inserted user {} for daily update", user_id);
}
unsuccessfull_ids
}

pub async fn update_routine(
Expand Down
29 changes: 15 additions & 14 deletions src/handlers/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ static POST_LOGIN_REDIRECT_URI: LazyLock<String> = LazyLock::new(|| {
static ADMIN_PASSWORD: LazyLock<String> = LazyLock::new(|| {
std::env::var("ADMIN_PASSWORD").expect("Missing ADMIN_PASSWORD environment variable")
});
static SECURE_COOKIE: LazyLock<bool> = LazyLock::new(|| {
std::env::var("SECURE_COOKIE").is_ok_and(|value| value.to_lowercase() == "true")
});

#[derive(Deserialize, JsonSchema)]
pub struct AuthQuery {
Expand Down Expand Up @@ -62,21 +65,19 @@ pub async fn osu_oauth2_redirect(
)?;
let mut redirect_response = Redirect::to(POST_LOGIN_REDIRECT_URI.as_str()).into_response();
let headers = redirect_response.headers_mut();
headers.append(
SET_COOKIE,
format!(
"user_token={}; HttpOnly; Max-Age=86400; Path=/; SameSite=lax",
token
)
.parse()
.unwrap(),
);
headers.append(
SET_COOKIE,
"logged_in=true;Max-Age=86400; Path=/; SameSite=lax"
.parse()
.unwrap(),
let mut user_token_cookie_string = format!(
"user_token={};HttpOnly;Max-Age=86400;Path=/;SameSite=lax;Secure",
token
);
let mut logged_in_cookie_string =
"logged_in=true;Max-Age=86400;Path=/;SameSite=lax;Secure".to_string();
if *SECURE_COOKIE {
user_token_cookie_string += "Secure";
logged_in_cookie_string += "Secure";
}

headers.append(SET_COOKIE, user_token_cookie_string.parse().unwrap());
headers.append(SET_COOKIE, logged_in_cookie_string.parse().unwrap());

// TODO: maybe fix authorized thing to be in the same query later?
let osu_user_id = osu_user.id;
Expand Down
36 changes: 36 additions & 0 deletions src/user_import.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use std::{sync::Arc, time::Duration};

use mapper_influences_backend_rs::{
daily_update::update_once,
database::DatabaseClient,
osu_api::{credentials_grant::CredentialsGrantClient, request::OsuApiRequestClient},
};

#[tokio::main]
async fn main() {
dotenvy::dotenv().ok();

tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();

let url = std::env::var("SURREAL_URL").expect("Missing SURREAL_URL environment variable");
let db = DatabaseClient::new(&url)
.await
.expect("failed to initialize db connection");

let users = db.get_users_to_update().await.unwrap();

let request_client = Arc::new(OsuApiRequestClient::new(100));
let credentials_grant_client = CredentialsGrantClient::new(request_client).await.unwrap();

let unsuccessfuls = update_once(
credentials_grant_client,
db,
users,
Duration::from_millis(300),
)
.await;

dbg!(unsuccessfuls);
}

0 comments on commit 1f23449

Please sign in to comment.