use fastauth_core::adapter::Transaction;
use fastauth_core::plugin_prelude::*;
use fastauth_core::routes::Status;
use serde_json::{Map, Value as JsonValue};
use super::{
active_organization, find_member, find_organization, find_organization_by_slug, nullable,
organization, plugin, requested_organization, require_text, set_active, slug_taken,
user_not_found, with_users,
};
use crate::access::OWNER;
use crate::model::{Invitation, Member, MemberWithUser, OrganizationRow, OrganizationSession};
use crate::{MemberAdded, Organization, OrganizationCreated, OrganizationError};
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateOrganizationInput {
pub name: String,
pub slug: String,
pub logo: Option<String>,
pub metadata: Option<Map<String, JsonValue>>,
#[serde(default)]
pub keep_current_active_organization: bool,
#[serde(skip)]
pub user_id: Option<Id>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct OrganizationWithMembers {
#[serde(flatten)]
pub organization: OrganizationRow,
pub members: Vec<Member>,
}
#[derive(Clone, Copy, Debug)]
pub struct CreateOrganization {
trusted: bool,
}
impl CreateOrganization {
pub fn client() -> Self {
Self { trusted: false }
}
pub fn server() -> Self {
Self { trusted: true }
}
}
impl<D: Adapter> Endpoint<D> for CreateOrganization {
const METHOD: Method = Method::POST;
const PATH: &'static str = "/organization/create";
type Access = MaybeAuthenticated;
type Input = CreateOrganizationInput;
type Output = OrganizationWithMembers;
async fn call(
&self,
ctx: Ctx<D, MaybeAuthenticated>,
mut input: CreateOrganizationInput,
) -> Result<OrganizationWithMembers, AuthError> {
if self.trusted {
let user_id = input.user_id.take().ok_or_else(AuthError::unauthorized)?;
let user = ctx
.internal()
.find_user_by_id(&user_id)
.await?
.ok_or_else(user_not_found)?;
return create(&ctx, &user.id, input).await;
}
let session = ctx.session().ok_or_else(AuthError::unauthorized)?;
if !plugin(&ctx).allow_user_to_create_organization {
return Err(OrganizationError::YouAreNotAllowedToCreateANewOrganization.into());
}
let keep_active = input.keep_current_active_organization;
let created = create(&ctx, &session.user.id, input).await?;
if !keep_active {
set_active(&ctx, session, Some(&created.organization.id)).await?;
}
Ok(created)
}
}
async fn create<D: Adapter, A>(
ctx: &Ctx<D, A>,
user_id: &Id,
input: CreateOrganizationInput,
) -> Result<OrganizationWithMembers, AuthError> {
require_text(&input.name, "name")?;
require_text(&input.slug, "slug")?;
if let Some(limit) = plugin(ctx).organization_limit {
let owned = ctx
.db()
.count::<Member>(Member::USER_ID.eq(user_id))
.await?;
if owned >= limit {
return Err(OrganizationError::YouHaveReachedTheMaximumNumberOfOrganizations.into());
}
}
if find_organization_by_slug(ctx, &input.slug).await?.is_some() {
return Err(OrganizationError::OrganizationAlreadyExists.into());
}
let now = ctx.now();
let organization = OrganizationRow {
id: ctx.new_id()?,
name: input.name,
slug: input.slug,
logo: input.logo,
metadata: input.metadata.map(Json),
created_at: now,
};
let member = Member {
id: ctx.new_id()?,
organization_id: organization.id.clone(),
user_id: user_id.clone(),
role: OWNER.to_owned(),
created_at: now,
};
let tx = ctx.adapter().begin().await?;
let db = ctx.db_on(&tx);
let organization = db.insert(&organization).await.map_err(slug_taken)?;
let member = db.insert(&member).await?;
tx.commit().await?;
ctx.emit(OrganizationCreated {
organization_id: organization.id.clone(),
user_id: user_id.clone(),
});
ctx.emit(MemberAdded {
organization_id: organization.id.clone(),
user_id: user_id.clone(),
member_id: member.id.clone(),
role: member.role.clone(),
});
Ok(OrganizationWithMembers {
organization,
members: vec![member],
})
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateOrganizationData {
pub name: Option<String>,
pub slug: Option<String>,
#[serde(default, deserialize_with = "nullable")]
pub logo: Option<Option<String>>,
pub metadata: Option<Map<String, JsonValue>>,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateOrganizationInput {
pub data: UpdateOrganizationData,
pub organization_id: Option<String>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct UpdateOrganization;
impl<D: Adapter> Endpoint<D> for UpdateOrganization {
const METHOD: Method = Method::POST;
const PATH: &'static str = "/organization/update";
type Access = Authenticated;
type Input = UpdateOrganizationInput;
type Output = OrganizationRow;
async fn call(
&self,
ctx: Ctx<D, Authenticated>,
input: UpdateOrganizationInput,
) -> Result<OrganizationRow, AuthError> {
let session = ctx.session();
let organization_id = requested_organization(session, input.organization_id.as_deref())?
.ok_or(OrganizationError::OrganizationNotFound)?;
let member = find_member(&ctx, &organization_id, &session.user.id)
.await?
.ok_or(OrganizationError::UserIsNotAMemberOfTheOrganization)?;
if !plugin(&ctx)
.roles
.allows(&member.role, &[("organization", &["update"])])
{
return Err(OrganizationError::YouAreNotAllowedToUpdateThisOrganization.into());
}
let data = input.data;
if let Some(slug) = &data.slug {
require_text(slug, "slug")?;
if find_organization_by_slug(&ctx, slug)
.await?
.is_some_and(|o| o.id != organization_id)
{
return Err(OrganizationError::OrganizationSlugAlreadyTaken.into());
}
}
let mut update = ctx
.db()
.update::<OrganizationRow>(OrganizationRow::ID.eq(&organization_id));
let mut changed = false;
if let Some(name) = data.name {
require_text(&name, "name")?;
update = update.set(OrganizationRow::NAME, name);
changed = true;
}
if let Some(slug) = data.slug {
update = update.set(OrganizationRow::SLUG, slug);
changed = true;
}
if let Some(logo) = data.logo {
update = update.set(OrganizationRow::LOGO, logo);
changed = true;
}
if let Some(metadata) = data.metadata {
update = update.set(OrganizationRow::METADATA, Some(Json(metadata)));
changed = true;
}
if changed {
update.exec().await.map_err(slug_taken)?;
}
organization(&ctx, &organization_id).await
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteOrganizationInput {
pub organization_id: String,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DeleteOrganization;
impl<D: Adapter> Endpoint<D> for DeleteOrganization {
const METHOD: Method = Method::POST;
const PATH: &'static str = "/organization/delete";
type Access = Authenticated;
type Input = DeleteOrganizationInput;
type Output = OrganizationRow;
async fn call(
&self,
ctx: Ctx<D, Authenticated>,
input: DeleteOrganizationInput,
) -> Result<OrganizationRow, AuthError> {
let session = ctx.session();
let organization_id = Id::from(input.organization_id);
let member = find_member(&ctx, &organization_id, &session.user.id)
.await?
.ok_or(OrganizationError::UserIsNotAMemberOfTheOrganization)?;
if !plugin(&ctx)
.roles
.allows(&member.role, &[("organization", &["delete"])])
{
return Err(OrganizationError::YouAreNotAllowedToDeleteThisOrganization.into());
}
let deleted = organization(&ctx, &organization_id).await?;
delete(&ctx, &organization_id).await?;
if active_organization(session)?.as_ref() == Some(&organization_id) {
ctx.delete_cookie(super::SESSION_CACHE_COOKIE);
}
Ok(deleted)
}
}
pub(crate) async fn delete<D: Adapter, A>(ctx: &Ctx<D, A>, id: &Id) -> Result<(), AuthError> {
let tx = ctx.adapter().begin().await?;
let db = ctx.db_on(&tx);
db.delete::<Invitation>(Invitation::ORGANIZATION_ID.eq(id))
.await?;
db.delete::<Member>(Member::ORGANIZATION_ID.eq(id)).await?;
db.delete::<OrganizationRow>(OrganizationRow::ID.eq(id))
.await?;
db.update::<Session>(OrganizationSession::ACTIVE_ORGANIZATION_ID.eq(Some(id.clone())))
.set(OrganizationSession::ACTIVE_ORGANIZATION_ID, None::<Id>)
.exec()
.await?;
tx.commit().await?;
Ok(())
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ListOrganizations;
impl<D: Adapter> Endpoint<D> for ListOrganizations {
const METHOD: Method = Method::GET;
const PATH: &'static str = "/organization/list";
type Access = Authenticated;
type Input = Empty;
type Output = Vec<OrganizationRow>;
async fn call(
&self,
ctx: Ctx<D, Authenticated>,
_input: Empty,
) -> Result<Vec<OrganizationRow>, AuthError> {
let memberships = ctx
.db()
.find::<Member>(Member::USER_ID.eq(&ctx.session().user.id))
.order_by(Member::CREATED_AT.asc())
.all()
.await?;
if memberships.is_empty() {
return Ok(Vec::new());
}
let organizations = ctx
.db()
.find::<OrganizationRow>(
OrganizationRow::ID.in_(memberships.iter().map(|m| m.organization_id.clone())),
)
.all()
.await?;
Ok(memberships
.iter()
.filter_map(|m| {
organizations
.iter()
.find(|o| o.id == m.organization_id)
.cloned()
})
.collect())
}
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFullOrganizationQuery {
pub organization_id: Option<String>,
pub organization_slug: Option<String>,
pub members_limit: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct FullOrganization {
#[serde(flatten)]
pub organization: OrganizationRow,
pub members: Vec<MemberWithUser>,
pub invitations: Vec<Invitation>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct GetFullOrganization;
impl<D: Adapter> Endpoint<D> for GetFullOrganization {
const METHOD: Method = Method::GET;
const PATH: &'static str = "/organization/get-full-organization";
type Access = Authenticated;
type Input = GetFullOrganizationQuery;
type Output = Option<FullOrganization>;
async fn call(
&self,
ctx: Ctx<D, Authenticated>,
input: GetFullOrganizationQuery,
) -> Result<Option<FullOrganization>, AuthError> {
let session = ctx.session();
let active = active_organization(session)?;
let found = match (&input.organization_slug, &input.organization_id, &active) {
(Some(slug), _, _) => find_organization_by_slug(&ctx, slug).await?,
(None, Some(id), _) => find_organization(&ctx, &Id::from(id.as_str())).await?,
(None, None, Some(id)) => find_organization(&ctx, id).await?,
(None, None, None) => return Ok(None),
};
let organization = found.ok_or(OrganizationError::OrganizationNotFound)?;
let Some(member) = find_member(&ctx, &organization.id, &session.user.id).await? else {
if active.as_ref() == Some(&organization.id) {
set_active(&ctx, session, None).await?;
}
return Err(OrganizationError::UserIsNotAMemberOfTheOrganization
.with_status(StatusCode::FORBIDDEN));
};
let mut members = ctx
.db()
.find::<Member>(Member::ORGANIZATION_ID.eq(&organization.id))
.order_by(Member::CREATED_AT.asc());
if let Some(limit) = input.members_limit {
members = members.limit(limit);
}
let members = with_users(&ctx, members.all().await?).await?;
let invitations = visible_invitations(&ctx, plugin(&ctx), &member).await?;
Ok(Some(FullOrganization {
organization,
members,
invitations,
}))
}
}
pub(crate) async fn visible_invitations<D: Adapter, A>(
ctx: &Ctx<D, A>,
plugin: &Organization,
member: &Member,
) -> Result<Vec<Invitation>, AuthError> {
if !plugin
.roles
.allows(&member.role, &[("invitation", &["create"])])
{
return Ok(Vec::new());
}
let invitations = ctx
.db()
.find::<Invitation>(Invitation::ORGANIZATION_ID.eq(&member.organization_id))
.order_by(Invitation::CREATED_AT.asc())
.all()
.await?;
let is_owner = member.has_role(OWNER);
Ok(invitations
.into_iter()
.filter(|i| is_owner || !crate::access::role_list(&i.role).any(|r| r == OWNER))
.collect())
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetActiveOrganizationInput {
#[serde(default, deserialize_with = "nullable")]
pub organization_id: Option<Option<String>>,
pub organization_slug: Option<String>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SetActiveOrganization;
impl<D: Adapter> Endpoint<D> for SetActiveOrganization {
const METHOD: Method = Method::POST;
const PATH: &'static str = "/organization/set-active";
type Access = Authenticated;
type Input = SetActiveOrganizationInput;
type Output = Option<OrganizationRow>;
async fn call(
&self,
ctx: Ctx<D, Authenticated>,
input: SetActiveOrganizationInput,
) -> Result<Option<OrganizationRow>, AuthError> {
let session = ctx.session();
let active = active_organization(session)?;
let organization_id = match (input.organization_id, input.organization_slug) {
(Some(None), _) => {
if active.is_some() {
set_active(&ctx, session, None).await?;
}
return Ok(None);
}
(Some(Some(id)), _) => Id::from(id),
(None, Some(slug)) => {
find_organization_by_slug(&ctx, &slug)
.await?
.ok_or(OrganizationError::OrganizationNotFound)?
.id
}
(None, None) => match &active {
Some(id) => id.clone(),
None => return Ok(None),
},
};
if find_member(&ctx, &organization_id, &session.user.id)
.await?
.is_none()
{
if active.is_some() {
set_active(&ctx, session, None).await?;
}
return Err(OrganizationError::UserIsNotAMemberOfTheOrganization
.with_status(StatusCode::FORBIDDEN));
}
let organization = organization(&ctx, &organization_id).await?;
set_active(&ctx, session, Some(&organization.id)).await?;
Ok(Some(organization))
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct CheckSlugInput {
pub slug: String,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct CheckSlug;
impl<D: Adapter> Endpoint<D> for CheckSlug {
const METHOD: Method = Method::POST;
const PATH: &'static str = "/organization/check-slug";
type Access = Authenticated;
type Input = CheckSlugInput;
type Output = Status;
async fn call(
&self,
ctx: Ctx<D, Authenticated>,
input: CheckSlugInput,
) -> Result<Status, AuthError> {
if find_organization_by_slug(&ctx, &input.slug)
.await?
.is_some()
{
return Err(OrganizationError::OrganizationSlugAlreadyTaken.into());
}
Ok(Status { status: true })
}
}