use diesel::{dsl::insert_into, prelude::*};
use crate::biome::oauth::store::{
diesel::{
models::{InsertableOAuthUserSessionModel, OAuthUserModel, OAuthUserSessionModel},
schema::{oauth_user_sessions, oauth_users},
},
InsertableOAuthUserSession, OAuthUser, OAuthUserSessionStoreError,
};
use crate::error::{ConstraintViolationError, ConstraintViolationType};
use super::OAuthUserSessionStoreOperations;
pub trait OAuthUserSessionStoreAddSession {
fn add_session(
&self,
session: InsertableOAuthUserSession,
) -> Result<(), OAuthUserSessionStoreError>;
}
#[cfg(feature = "sqlite")]
impl<'a> OAuthUserSessionStoreAddSession
for OAuthUserSessionStoreOperations<'a, diesel::sqlite::SqliteConnection>
{
fn add_session(
&self,
session: InsertableOAuthUserSession,
) -> Result<(), OAuthUserSessionStoreError> {
self.conn.transaction::<_, _, _>(|| {
if oauth_user_sessions::table
.find(session.splinter_access_token())
.first::<OAuthUserSessionModel>(self.conn)
.optional()?
.is_some()
{
return Err(OAuthUserSessionStoreError::ConstraintViolation(
ConstraintViolationError::with_violation_type(ConstraintViolationType::Unique),
));
}
if oauth_users::table
.find(session.subject())
.first::<OAuthUserModel>(self.conn)
.optional()?
.is_none()
{
let user = OAuthUser::new(session.subject().to_string());
insert_into(oauth_users::table)
.values(OAuthUserModel::from(user))
.execute(self.conn)
.map_err(OAuthUserSessionStoreError::from)?;
}
insert_into(oauth_user_sessions::table)
.values(InsertableOAuthUserSessionModel::from(session))
.execute(self.conn)
.map(|_| ())
.map_err(OAuthUserSessionStoreError::from)
})
}
}
#[cfg(feature = "postgres")]
impl<'a> OAuthUserSessionStoreAddSession
for OAuthUserSessionStoreOperations<'a, diesel::pg::PgConnection>
{
fn add_session(
&self,
session: InsertableOAuthUserSession,
) -> Result<(), OAuthUserSessionStoreError> {
self.conn.transaction::<_, _, _>(|| {
if oauth_user_sessions::table
.find(session.splinter_access_token())
.first::<OAuthUserSessionModel>(self.conn)
.optional()?
.is_some()
{
return Err(OAuthUserSessionStoreError::ConstraintViolation(
ConstraintViolationError::with_violation_type(ConstraintViolationType::Unique),
));
}
if oauth_users::table
.find(session.subject())
.first::<OAuthUserModel>(self.conn)
.optional()?
.is_none()
{
let user = OAuthUser::new(session.subject().to_string());
insert_into(oauth_users::table)
.values(OAuthUserModel::from(user))
.execute(self.conn)
.map_err(OAuthUserSessionStoreError::from)?;
}
insert_into(oauth_user_sessions::table)
.values(InsertableOAuthUserSessionModel::from(session))
.execute(self.conn)
.map(|_| ())
.map_err(OAuthUserSessionStoreError::from)
})
}
}