1
0
Fork 0
forked from 2sys/shoutdotdev

extract PopulatedTeamMembership into a dedicated struct

This commit is contained in:
Brent Schroeter 2025-04-12 23:04:05 -07:00
parent 3f7e0018c3
commit a07aff5008
2 changed files with 40 additions and 31 deletions

View file

@ -4,7 +4,10 @@ use diesel::prelude::*;
use uuid::Uuid;
use crate::{
app_error::AppError, csrf::validate_csrf_token, team_memberships::TeamMembership, teams::Team,
app_error::AppError,
csrf::validate_csrf_token,
team_memberships::{PopulatedTeamMembership, TeamMembership},
teams::Team,
users::User,
};
@ -17,27 +20,23 @@ pub async fn require_team_membership(
team_id: &Uuid,
db_conn: &Connection,
) -> Result<Team, AppError> {
let maybe_team = {
let current_user_id = current_user.id;
let team_id = *team_id;
db_conn
.interact::<_, Result<Option<(Team, _)>>>(move |conn| {
TeamMembership::all()
.filter(TeamMembership::with_user_id(&current_user_id))
.filter(TeamMembership::with_team_id(&team_id))
.first(conn)
.optional()
.map_err(Into::into)
})
.await
.unwrap()?
};
match maybe_team {
Some((team, _)) => Ok(team),
None => Err(AppError::Forbidden(
"not a member of requested team".to_string(),
)),
}
let current_user_id = current_user.id;
let team_id = *team_id;
db_conn
.interact::<_, Result<Option<PopulatedTeamMembership>>>(move |conn| {
PopulatedTeamMembership::all()
.filter(TeamMembership::with_user_id(&current_user_id))
.filter(TeamMembership::with_team_id(&team_id))
.first(conn)
.optional()
.map_err(Into::into)
})
.await
.unwrap()?
.map(|team_membership| team_membership.team)
.ok_or(AppError::Forbidden(
"not a member of requested team".to_owned(),
))
}
/// Returns a ForbiddenError if the CSRF token parameters do not match an entry

View file

@ -21,15 +21,6 @@ pub struct TeamMembership {
}
impl TeamMembership {
#[diesel::dsl::auto_type(no_type_alias)]
pub fn all() -> _ {
let select: AsSelect<(Team, User), Pg> = <(Team, User)>::as_select();
team_memberships::table
.inner_join(teams::table)
.inner_join(users::table)
.select(select)
}
#[auto_type(no_type_alias)]
pub fn with_team_id<'a>(id: &'a Uuid) -> _ {
team_memberships::team_id.eq(id)
@ -40,3 +31,22 @@ impl TeamMembership {
team_memberships::user_id.eq(id)
}
}
#[derive(Clone, Debug, Queryable, Selectable)]
pub struct PopulatedTeamMembership {
#[diesel(embed)]
pub team: Team,
#[diesel(embed)]
pub user: User,
}
impl PopulatedTeamMembership {
#[auto_type(no_type_alias)]
pub fn all() -> _ {
let select: AsSelect<Self, Pg> = Self::as_select();
team_memberships::table
.inner_join(teams::table)
.inner_join(users::table)
.select(select)
}
}