Skip to content

Commit

Permalink
Use ArcStr instead of Arc<str>
Browse files Browse the repository at this point in the history
  • Loading branch information
CharlesTaylor7 committed May 13, 2024
1 parent 7183b09 commit 65dcd2a
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 28 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ log = "0.4.20"
env_logger = { version = "0.10.1", features = ["color"] }
rand_xoshiro = "0.6.0"
rand_core = { version = "0.6.4", features = ["getrandom"] }
serde = { version = "1.0.195", features = ["derive","rc"] }
serde = { version = "1.0.195", features = ["derive"] }
serde_json = "1.0.111"
time = "0.3.31"
dotenv = { version = "0.15.0", optional = true }
Expand All @@ -35,6 +35,7 @@ reqwest = { version = "0.12.4", features = ["json"], default-features = false }
anyhow = { version = "1.0.83", default-features = true }
axum-macros = { version = "0.4.1", optional = true}
maud = { version = "0.26.0", features = ["axum"], default-features = false}
arcstr = { version = "1.2.0", features = ["serde"], default-features = false }

[features]
dev = ["dep:axum-macros"]
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ pub mod roles;
pub mod server;
pub mod templates;
pub mod types;
pub mod utils;
24 changes: 14 additions & 10 deletions src/server/auth.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use super::supabase::SignInResponse;
use crate::server::{state::AppState, supabase::EmailCreds};
use arcstr::ArcStr;
use axum_extra::extract::{cookie::Cookie, PrivateCookieJar};
use std::borrow::Cow;
use std::{collections::HashMap, sync::Arc};
use std::collections::HashMap;

#[derive(Clone)]
pub struct Session {
pub access_token: Arc<str>,
pub refresh_token: Arc<str>,
pub access_token: ArcStr,
pub refresh_token: ArcStr,
}

impl Session {
Expand All @@ -18,7 +18,7 @@ impl Session {
}

#[derive(Default)]
pub struct Sessions(pub HashMap<Arc<str>, Session>);
pub struct Sessions(pub HashMap<ArcStr, Session>);

impl Sessions {
pub fn session_from_cookies(&self, cookies: &PrivateCookieJar) -> Option<Session> {
Expand Down Expand Up @@ -56,9 +56,10 @@ pub async fn login(
let session = state.supabase.signin_email(creds).await?;
log::info!("Setting session cookie with 1 week expiry");

let user_id = session.user.id.as_ref().to_owned();
let mut cookie = Cookie::new("session_id", user_id);
cookie.set_max_age(time::Duration::WEEK);
let cookie = Cookie::build(("session_id", session.user.id.to_string()))
.max_age(time::Duration::WEEK)
.secure(true)
.http_only(true);
cookies = cookies.add(cookie);
state.add_session(session).await;
}
Expand All @@ -76,8 +77,11 @@ pub async fn signup(
anyhow::bail!("Already has a session cookie");
}
let session = state.supabase.signup_email(creds).await?;
let cookie = Cookie::build(("session_id", String::from(session.user.id.as_ref())))
.max_age(time::Duration::WEEK);

let cookie = Cookie::build(("session_id", session.user.id.to_string()))
.max_age(time::Duration::WEEK)
.secure(true)
.http_only(true);
cookies = cookies.add(cookie);
state.add_session(session).await;
Ok(cookies)
Expand Down
3 changes: 1 addition & 2 deletions src/server/routes.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::auth;
use crate::actions::{ActionSubmission, ActionTag};
use crate::districts::DistrictName;
use crate::game::Game;
Expand Down Expand Up @@ -25,8 +26,6 @@ use std::collections::{HashMap, HashSet};
use tower_http::services::ServeDir;
use tower_http::trace::TraceLayer;

use super::auth;

pub fn get_router(state: AppState) -> Router {
Router::new()
.route("/", get(get_index))
Expand Down
23 changes: 11 additions & 12 deletions src/server/supabase.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use crate::utils::infer;
use arcstr::ArcStr;
use reqwest::Response;
use serde::{Deserialize, Serialize};
use std::env;
use std::sync::Arc;

use super::auth::Session;

#[derive(Serialize)]
pub struct EmailCreds<'a> {
Expand All @@ -18,15 +17,15 @@ pub struct RefreshToken<'a> {

#[derive(Deserialize)]
pub struct SignInResponse {
pub access_token: Arc<str>,
pub refresh_token: Arc<str>,
pub access_token: ArcStr,
pub refresh_token: ArcStr,
pub expires_in: u64,
pub user: UserSignInResponse,
}

#[derive(Deserialize)]
pub struct UserSignInResponse {
pub id: Arc<str>,
pub id: ArcStr,
}

#[derive(Clone)]
Expand Down Expand Up @@ -55,8 +54,8 @@ impl<T> std::fmt::Debug for Secret<T> {
#[derive(Clone, Debug)]
pub struct SupabaseAnonClient {
pub client: reqwest::Client,
pub url: Arc<str>,
pub api_key: Arc<str>,
pub url: ArcStr,
pub api_key: ArcStr,
}

impl SupabaseAnonClient {
Expand All @@ -72,7 +71,7 @@ impl SupabaseAnonClient {
let response: Response = self
.client
.post(&format!("{}/auth/v1/signup", self.url))
.header("apikey", self.api_key.as_ref())
.header("apikey", infer::<&str>(self.api_key.as_ref()))
.header("Content-Type", "application/json")
.json(creds)
.send()
Expand All @@ -85,7 +84,7 @@ impl SupabaseAnonClient {
let response = self
.client
.post(&format!("{}/auth/v1/token?grant_type=password", self.url))
.header("apikey", self.api_key.as_ref())
.header::<_, &str>("apikey", self.api_key.as_ref())
.header("Content-Type", "application/json")
.json(creds)
.send()
Expand All @@ -101,7 +100,7 @@ impl SupabaseAnonClient {
"{}/auth/v1/token?grant_type=refresh_token",
self.url
))
.header("apikey", self.api_key.as_ref())
.header("apikey", self.api_key.as_str())
.header("Content-Type", "application/json")
.json(&RefreshToken { refresh_token })
.send()
Expand All @@ -114,7 +113,7 @@ impl SupabaseAnonClient {
pub async fn logout(&self, access_token: &str) -> anyhow::Result<()> {
self.client
.post(&format!("{}/auth/v1/logout", self.url))
.header("apikey", self.api_key.as_ref())
.header("apikey", self.api_key.as_str())
.header("Content-Type", "application/json")
.bearer_auth(access_token)
.send()
Expand Down
6 changes: 3 additions & 3 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use arcstr::ArcStr;
use serde::{Deserialize, Serialize};
use std::borrow::Borrow;
use std::fmt::{self, Debug, Display};
use std::sync::Arc;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum CardSuit {
Expand Down Expand Up @@ -68,15 +68,15 @@ pub type PlayerId = String;
pub type Result<T> = std::result::Result<T, &'static str>;

#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Hash)]
pub struct PlayerName(pub Arc<str>);
pub struct PlayerName(pub ArcStr);

impl Borrow<str> for PlayerName {
fn borrow(&self) -> &str {
self.0.borrow()
}
}

impl<T: Into<Arc<str>>> From<T> for PlayerName {
impl<T: Into<ArcStr>> From<T> for PlayerName {
fn from(str: T) -> Self {
PlayerName(str.into())
}
Expand Down
5 changes: 5 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// for when the types are too ambiguous
#[inline]
pub fn infer<T>(t: T) -> T {
t
}

0 comments on commit 65dcd2a

Please sign in to comment.