Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Remove SQLx crate from torii-core #10

Merged
merged 1 commit into from
Feb 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions torii-auth-email/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,14 @@ mod tests {
let mut manager = PluginManager::new(user_storage.clone(), session_storage.clone());
manager.register(EmailPasswordPlugin::new(storage));

user_storage.migrate().await?;
session_storage.migrate().await?;
user_storage
.migrate()
.await
.map_err(|_| Error::Storage("Failed to migrate user storage".to_string()))?;
session_storage
.migrate()
.await
.map_err(|_| Error::Storage("Failed to migrate session storage".to_string()))?;

Ok((manager,))
}
Expand Down
31 changes: 11 additions & 20 deletions torii-auth-oauth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, RedirectUrl, Scope,
TokenResponse,
};
use torii_core::storage::OAuthStorage;
use torii_core::{storage::Storage, Error, NewUser, Plugin, Session, SessionStorage, User, UserId};
use torii_storage_sqlite::{OAuthAccount, OAuthStorage};
use uuid::Uuid;

/// The core oauth plugin struct, responsible for handling oauth authentication flow.
Expand All @@ -18,14 +18,16 @@
/// # Examples
/// ```rust
/// // Using the builder pattern
/// let plugin = oauthPlugin::builder("google")
/// use std::env;
/// use torii_auth_oauth::OAuthPlugin;
/// let plugin = OAuthPlugin::builder("google")
/// .client_id(env::var("GOOGLE_CLIENT_ID")?)
/// .client_secret(env::var("GOOGLE_CLIENT_SECRET")?)
/// .redirect_uri("http://localhost:8080/callback")
/// .build();
///
/// // Using preset for Google
/// let plugin = oauthPlugin::google(
/// let plugin = OAuthPlugin::google(
/// env::var("GOOGLE_CLIENT_ID")?,
/// env::var("GOOGLE_CLIENT_SECRET")?,
/// "http://localhost:8080/callback".to_string(),
Expand Down Expand Up @@ -280,7 +282,7 @@
.get_user(&oauth_account.user_id)
.await
.map_err(|_| Error::InternalServerError)?
.ok_or_else(|| Error::UserNotFound)?;
.ok_or(Error::UserNotFound)?;

Check warning on line 285 in torii-auth-oauth/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

torii-auth-oauth/src/lib.rs#L285

Added line #L285 was not covered by tests

return Ok(user);
}
Expand All @@ -301,13 +303,7 @@
// Create link between user and provider
storage
.user_storage()
.create_oauth_account(&OAuthAccount {
user_id: user.id.clone(),
provider: self.provider.clone(),
subject: subject.clone(),
created_at: Utc::now(),
updated_at: Utc::now(),
})
.create_oauth_account(&self.provider, &subject, &user.id)
.await
.map_err(|_| Error::InternalServerError)?;

Expand Down Expand Up @@ -389,9 +385,7 @@
tracing::info!("Successfully exchanged code for token response");

// Get id token from token response
let id_token = token_response
.id_token()
.ok_or_else(|| Error::InvalidCredentials)?;
let id_token = token_response.id_token().ok_or(Error::InvalidCredentials)?;

Check warning on line 388 in torii-auth-oauth/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

torii-auth-oauth/src/lib.rs#L388

Added line #L388 was not covered by tests

tracing::info!("Successfully got id token from token response");

Expand Down Expand Up @@ -420,15 +414,12 @@
tracing::info!(claims = ?claims, "Verified id token");

let subject = claims.subject().to_string();
let email = claims
.email()
.ok_or_else(|| Error::InvalidCredentials)?
.to_string();
let email = claims.email().ok_or(Error::InvalidCredentials)?.to_string();

Check warning on line 417 in torii-auth-oauth/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

torii-auth-oauth/src/lib.rs#L417

Added line #L417 was not covered by tests
let name = claims
.name()
.ok_or_else(|| Error::InvalidCredentials)?
.ok_or(Error::InvalidCredentials)?

Check warning on line 420 in torii-auth-oauth/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

torii-auth-oauth/src/lib.rs#L420

Added line #L420 was not covered by tests
.get(None)
.ok_or_else(|| Error::InvalidCredentials)?
.ok_or(Error::InvalidCredentials)?

Check warning on line 422 in torii-auth-oauth/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

torii-auth-oauth/src/lib.rs#L422

Added line #L422 was not covered by tests
.to_string();

tracing::info!(
Expand Down
1 change: 0 additions & 1 deletion torii-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ derive_builder.workspace = true
downcast-rs = "2.0.1"
futures.workspace = true
serde.workspace = true
sqlx.workspace = true
thiserror.workspace = true
tracing.workspace = true
uuid.workspace = true
Expand Down
4 changes: 0 additions & 4 deletions torii-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ use thiserror::Error;

#[derive(Debug, Error)]
pub enum Error {
// Database errors
#[error("Database error: {0}")]
Database(#[from] sqlx::Error),

// Plugin errors
#[error("Plugin error: {0}")]
Plugin(String),
Expand Down
2 changes: 1 addition & 1 deletion torii-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ pub use error::Error;
pub use plugin::{Plugin, PluginManager};
pub use session::Session;
pub use storage::{NewUser, SessionStorage, UserStorage};
pub use user::{User, UserId};
pub use user::{OAuthAccount, User, UserId};
5 changes: 2 additions & 3 deletions torii-core/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ use derive_builder::Builder;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, sqlx::Type)]
#[sqlx(transparent)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SessionId(String);

impl SessionId {
Expand Down Expand Up @@ -67,7 +66,7 @@ impl std::fmt::Display for SessionId {
}
}

#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow, Builder)]
#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
pub struct Session {
/// The unique identifier for the session.
#[builder(default = "SessionId::new_random()")]
Expand Down
33 changes: 27 additions & 6 deletions torii-core/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use chrono::{DateTime, Utc};
use derive_builder::Builder;
use serde::{Deserialize, Serialize};

use crate::{session::SessionId, Error, Session, User, UserId};
use crate::{session::SessionId, Error, OAuthAccount, Session, User, UserId};

#[async_trait]
pub trait StoragePlugin: Send + Sync + 'static {
Expand Down Expand Up @@ -54,18 +54,39 @@ pub trait EmailPasswordStorage: UserStorage {
/// Storage methods specific to OAuth authentication
#[async_trait]
pub trait OAuthStorage: UserStorage {
async fn create_oauth_account(
&self,
provider: &str,
subject: &str,
user_id: &UserId,
) -> Result<OAuthAccount, Self::Error>;

async fn get_user_by_provider_and_subject(
&self,
provider: &str,
subject: &str,
) -> Result<Option<User>, Self::Error>;

async fn get_oauth_account_by_provider_and_subject(
&self,
provider: &str,
subject: &str,
) -> Result<Option<OAuthAccount>, Self::Error>;

async fn link_oauth_account(
&self,
user_id: &UserId,
provider: &str,
provider_user_id: &str,
subject: &str,
) -> Result<(), Self::Error>;

async fn get_user_by_oauth(
async fn get_nonce(&self, id: &str) -> Result<Option<String>, Self::Error>;
async fn save_nonce(
&self,
provider: &str,
provider_user_id: &str,
) -> Result<Option<User>, Self::Error>;
id: &str,
value: &str,
expires_at: &DateTime<Utc>,
) -> Result<(), Self::Error>;
}

#[derive(Debug, Clone)]
Expand Down
20 changes: 17 additions & 3 deletions torii-core/src/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// A unique, stable identifier for a specific user
#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type, Serialize, Deserialize, Hash)]
#[sqlx(transparent)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct UserId(String);

impl UserId {
Expand Down Expand Up @@ -70,7 +69,7 @@ impl std::fmt::Display for UserId {
///
/// Many of these fields are optional, as they may not be available from the authentication provider,
/// or may not be known at the time of authentication.
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow, Builder)]
#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
pub struct User {
// The unique identifier for the user.
#[builder(default = "UserId::new_random()")]
Expand Down Expand Up @@ -101,6 +100,21 @@ impl User {
}
}

#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
pub struct OAuthAccount {
pub user_id: UserId,
pub provider: String,
pub subject: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}

impl OAuthAccount {
pub fn builder() -> OAuthAccountBuilder {
OAuthAccountBuilder::default()
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading