-
Notifications
You must be signed in to change notification settings - Fork 4k
feat(dashboard,api-service): add self-hosted-auth #7755
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
Draft
djabarovgeorge
wants to merge
14
commits into
next
Choose a base branch
from
self-hosted-auth
base: next
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
7d1d507
feat(dashboard,api-service): add self-hosted-auth
djabarovgeorge 5806874
fix:
scopsy 2b694ce
fix: opted in status
scopsy 92a8620
Merge branch 'next' into self-hosted-auth
djabarovgeorge 03c53a4
refactor(api-service,dashaboard): integrate SystemOrganizationService…
djabarovgeorge 15a96d4
refactor(api-service): rename variable 'admins' to 'users' for clarit…
djabarovgeorge 4b699ab
refactor(dashboard): update self-hosted configuration and remove unus…
djabarovgeorge f085a27
refactor(dashboard): export OrganizationSwitcher from self-hosted uti…
djabarovgeorge e48c021
refactor(dashboard): export UserButton from self-hosted utils and cle…
djabarovgeorge 0fe32b2
refactor(dashboard, api): enhance error handling in content-templates…
djabarovgeorge 9716462
refactor(dashboard): implement navigation for self-hosted environment…
djabarovgeorge d6df4e5
refactor(dashboard): update workflow row and general settings for sel…
djabarovgeorge d9685f5
refactor(api, dashboard): enhance organization creation with API serv…
djabarovgeorge 19ca2db
refactor(dashboard): update activity filters to use API service level…
djabarovgeorge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
157 changes: 157 additions & 0 deletions
157
apps/api/src/app/auth/services/system-organization.service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
import { Inject, Injectable, OnModuleInit } from '@nestjs/common'; | ||
import { CommunityOrganizationRepository, MemberRepository, UserEntity, UserRepository } from '@novu/dal'; | ||
import { PinoLogger } from '@novu/application-generic'; | ||
import { ApiServiceLevelEnum } from '@novu/shared'; | ||
import { CreateOrganization } from '../../organization/usecases/create-organization/create-organization.usecase'; | ||
import { CreateOrganizationCommand } from '../../organization/usecases/create-organization/create-organization.command'; | ||
import { UserRegister } from '../usecases/register/user-register.usecase'; | ||
import { UserRegisterCommand } from '../usecases/register/user-register.command'; | ||
import { SwitchOrganization } from '../usecases/switch-organization/switch-organization.usecase'; | ||
import { SwitchOrganizationCommand } from '../usecases/switch-organization/switch-organization.command'; | ||
|
||
@Injectable() | ||
export class SystemOrganizationService implements OnModuleInit { | ||
private readonly E11000_DUPLICATE_KEY_ERROR_CODE = 'E11000'; | ||
private readonly SYSTEM_ORGANIZATION_NAME = 'System Organization'; | ||
private readonly SYSTEM_USER_EMAIL = '[email protected]'; | ||
|
||
constructor( | ||
private memberRepository: MemberRepository, | ||
@Inject('ORGANIZATION_REPOSITORY') | ||
private organizationRepository: CommunityOrganizationRepository, | ||
private createOrganizationUsecase: CreateOrganization, | ||
private userRegisterUsecase: UserRegister, | ||
private switchOrganizationUsecase: SwitchOrganization, | ||
private userRepository: UserRepository, | ||
private logger: PinoLogger | ||
) {} | ||
|
||
async onModuleInit() { | ||
try { | ||
await this.initializeSystemOrganization(); | ||
} catch (error) { | ||
this.logger.error({ err: error }, 'Failed to initialize Self-Hosted System Setup during module init'); | ||
throw error; | ||
} | ||
} | ||
|
||
private async initializeSystemOrganization(): Promise<void> { | ||
await this.organizationRepository.withTransaction(async () => { | ||
let systemOrg = await this.organizationRepository.findOne({ name: 'System Organization' }); | ||
|
||
if (systemOrg) { | ||
this.logger.info( | ||
`Self Hosted is already initialized, skipping System Organization creation. Organization already exists with ID: ${systemOrg._id}` | ||
); | ||
|
||
return; | ||
} | ||
|
||
this.logger.info('System Organization not found, creating it'); | ||
|
||
try { | ||
let user = await this.userRepository.findByEmail(this.SYSTEM_USER_EMAIL); | ||
if (!user) { | ||
user = await this.createSystemUser(); | ||
} | ||
|
||
this.logger.debug(`Retrieved System User with ID: ${user._id}`); | ||
|
||
const organization = await this.createOrganizationUsecase.execute( | ||
CreateOrganizationCommand.create({ | ||
userId: user._id, | ||
name: this.SYSTEM_ORGANIZATION_NAME, | ||
apiServiceLevel: ApiServiceLevelEnum.UNLIMITED, | ||
}) | ||
); | ||
|
||
this.logger.debug(`Retrieved System Organization with ID: ${organization?._id}`); | ||
} catch (error) { | ||
const isDuplicateKeyError = | ||
error instanceof Error && | ||
error.message.includes(this.E11000_DUPLICATE_KEY_ERROR_CODE) && | ||
error.message.includes(this.SYSTEM_ORGANIZATION_NAME); | ||
|
||
if (!isDuplicateKeyError) { | ||
throw error; | ||
} | ||
|
||
this.logger.warn('Duplicate key error, another instance may have created the System Organization'); | ||
systemOrg = await this.organizationRepository.findOne({ name: 'System Organization' }); | ||
if (!systemOrg) { | ||
this.logger.error('Failed to retrieve System Organization after duplicate key error'); | ||
throw error; | ||
} | ||
|
||
this.logger.info(`Retrieved System Organization created by another instance with ID: ${systemOrg._id}`); | ||
} | ||
}); | ||
} | ||
|
||
private async createSystemUser(): Promise<UserEntity> { | ||
try { | ||
const { user } = await this.userRegisterUsecase.execute( | ||
UserRegisterCommand.create({ | ||
email: this.SYSTEM_USER_EMAIL, | ||
firstName: 'System', | ||
lastName: 'User', | ||
password: 'systemUser1q@W#', | ||
}) | ||
); | ||
|
||
if (!user?._id) { | ||
throw new Error('Failed to create system user'); | ||
} | ||
|
||
return user; | ||
} catch (error) { | ||
const isDuplicateKeyDatabaseError = | ||
error instanceof Error && | ||
error.message.includes(this.E11000_DUPLICATE_KEY_ERROR_CODE) && | ||
error.message.includes(this.SYSTEM_USER_EMAIL); | ||
const isUserAlreadyExistsUsecaseError = error.message.includes('User already exists'); | ||
|
||
if (!isDuplicateKeyDatabaseError && !isUserAlreadyExistsUsecaseError) { | ||
throw error; | ||
} | ||
|
||
this.logger.warn('Duplicate key error, another instance may have created the System User'); | ||
const user = await this.userRepository.findByEmail(this.SYSTEM_USER_EMAIL); | ||
if (!user) { | ||
this.logger.error('Failed to retrieve System User after duplicate key error'); | ||
throw error; | ||
} | ||
|
||
this.logger.info(`Retrieved System User created by another instance with ID: ${user._id}`); | ||
|
||
if (!user?._id) { | ||
throw new Error('Failed to create system user'); | ||
} | ||
|
||
return user; | ||
} | ||
} | ||
|
||
async getSystemOrganizationToken() { | ||
const systemOrg = await this.organizationRepository.findOne({ name: 'System Organization' }); | ||
|
||
if (!systemOrg) { | ||
throw new Error('System Organization not found'); | ||
} | ||
|
||
const users = await this.memberRepository.getOrganizationMembers(systemOrg._id); | ||
|
||
if (!users || users.length === 0) { | ||
throw new Error('No admin users found for System Organization'); | ||
} | ||
|
||
const token = await this.switchOrganizationUsecase.execute( | ||
SwitchOrganizationCommand.create({ | ||
newOrganizationId: systemOrg._id!, | ||
userId: users[0]._userId, | ||
}) | ||
); | ||
|
||
return { token }; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is there any specific reason we're using request scope in the app? (there other providers in this PR that i update)
it’s currently limiting me from injecting certain providers into SystemOrganizationService, since it’s a singleton, and you can’t inject a request-scoped provider into a singleton.
cc @scopsy