Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

refactor: clean up auth and organisation controllers, add pagination to organisation service

Blue Mouse707073090fb2
diff --git a/backend/apps/cloud/src/auth/auth.controller.ts b/backend/apps/cloud/src/auth/auth.controller.ts
index 348e71002..039657955 100644
--- a/backend/apps/cloud/src/auth/auth.controller.ts
+++ b/backend/apps/cloud/src/auth/auth.controller.ts
@@ -155,7 +155,6 @@ export class AuthController {
await this.authService.sendTelegramNotification(user.id, headers, ip)
- console.log('before:', user)
if (user.isTwoFactorAuthenticationEnabled) {
// @ts-expect-error
user = _pick(user, ['isTwoFactorAuthenticationEnabled', 'email'])
@@ -163,8 +162,6 @@ export class AuthController {
user = await this.authService.getSharedProjectsForUser(user)
}
- console.log('after:', user)
-
return {
...jwtTokens,
user: this.userService.omitSensitiveData(user as User),
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
index 660d7bd12..ab28215b6 100644
--- a/backend/apps/cloud/src/organisation/organisation.controller.ts
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -10,9 +10,12 @@ import {
NotFoundException,
HttpCode,
Headers,
+ Get,
+ Query,
} from '@nestjs/common'
-import { ApiBearerAuth, ApiResponse } from '@nestjs/swagger'
+import { ApiBearerAuth, ApiQuery, ApiResponse } from '@nestjs/swagger'
import { isEmpty as _isEmpty, find as _find } from 'lodash'
+import { FindOptionsWhere, ILike } from 'typeorm'
import { JwtAccessTokenGuard } from '../auth/guards/jwt-access-token.guard'
import { RolesGuard } from '../auth/guards/roles.guard'
@@ -33,6 +36,8 @@ import {
import { OrganisationRole } from './entity/organisation-member.entity'
import { AppLoggerService } from '../logger/logger.service'
import { LetterTemplate } from '../mailer/letter'
+import { Auth } from '../auth/decorators'
+import { Pagination } from '../common/pagination'
const ORGANISATION_INVITE_EXPIRE = 7 * 24 // 7 days in hours
const { PRODUCTION_ORIGIN, isDevelopment } = process.env
@@ -47,11 +52,52 @@ export class OrganisationController {
private readonly logger: AppLoggerService,
) {}
+ @ApiBearerAuth()
+ @Get('/')
+ @ApiQuery({ name: 'take', required: false })
+ @ApiQuery({ name: 'skip', required: false })
+ @ApiQuery({ name: 'search', required: false, type: String })
+ @ApiResponse({ status: 200, type: [Organisation] })
+ @Auth([], true)
+ async get(
+ @CurrentUserId() userId: string,
+ @Query('take') take: number | undefined,
+ @Query('skip') skip: number | undefined,
+ @Query('search') search: string | undefined,
+ ): Promise<Pagination<Organisation> | Organisation[] | object> {
+ this.logger.log({ userId, take, skip }, 'GET /organisation')
+
+ let where: FindOptionsWhere<Organisation> | FindOptionsWhere<Organisation>[]
+
+ if (search) {
+ where = {
+ owner: {
+ id: userId,
+ },
+ name: ILike(`%${search}%`),
+ }
+ } else {
+ where = {
+ owner: {
+ id: userId,
+ },
+ } as FindOptionsWhere<Organisation>
+ }
+
+ const paginated = await this.organisationService.paginate(
+ { take, skip },
+ where,
+ )
+
+ return paginated
+ }
+
@ApiBearerAuth()
@Post('/')
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 200, type: Organisation })
+ @Auth([], true)
async create(
@Body() createOrgDTO: CreateOrganisationDTO,
@CurrentUserId() uid: string,
@@ -71,6 +117,7 @@ export class OrganisationController {
@HttpCode(200)
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth([], true)
async inviteMember(
@Param('orgId') orgId: string,
@Body() inviteDTO: InviteMemberDTO,
@@ -167,6 +214,7 @@ export class OrganisationController {
@HttpCode(200)
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth([], true)
async updateMemberRole(
@Param('memberId') memberId: string,
@Body() updateDTO: UpdateMemberRoleDTO,
@@ -211,6 +259,7 @@ export class OrganisationController {
@HttpCode(204)
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Auth([], true)
async removeMember(
@Param('memberId') memberId: string,
@CurrentUserId() uid: string,
diff --git a/backend/apps/cloud/src/organisation/organisation.service.ts b/backend/apps/cloud/src/organisation/organisation.service.ts
index bc2bf6528..b0afbf620 100644
--- a/backend/apps/cloud/src/organisation/organisation.service.ts
+++ b/backend/apps/cloud/src/organisation/organisation.service.ts
@@ -1,6 +1,6 @@
import { Injectable, ForbiddenException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
-import { Repository } from 'typeorm'
+import { FindOptionsWhere, Repository } from 'typeorm'
import { find as _find } from 'lodash'
import { Organisation } from './entity/organisation.entity'
@@ -8,6 +8,7 @@ import {
OrganisationMember,
OrganisationRole,
} from './entity/organisation-member.entity'
+import { Pagination, PaginationOptionsInterface } from '../common/pagination'
@Injectable()
export class OrganisationService {
@@ -69,4 +70,24 @@ export class OrganisationService {
)
}
}
+
+ async paginate(
+ options: PaginationOptionsInterface,
+ where?: FindOptionsWhere<Organisation> | FindOptionsWhere<Organisation>[],
+ ): Promise<Pagination<Organisation>> {
+ const [results, total] = await this.organisationRepository.findAndCount({
+ take: options.take || 100,
+ skip: options.skip || 0,
+ where,
+ order: {
+ name: 'ASC',
+ },
+ relations: ['owner', 'members'],
+ })
+
+ return new Pagination<Organisation>({
+ results,
+ total,
+ })
+ }
}
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index 9436341c9..ee652fb59 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -170,7 +170,6 @@ export class ProjectController {
isAnalyticsProject: !isCaptcha,
name: ILike(`%${search}%`),
isArchived: showArchived,
- // name: ILike(`%${mysql.escape(search).slice(1, 0).slice(0, -1)}%`),
},
{
admin: {
@@ -180,7 +179,6 @@ export class ProjectController {
isAnalyticsProject: !isCaptcha,
id: ILike(`%${search}%`),
isArchived: showArchived,
- // id: ILike(`%${mysql.escape(search).slice(1, 0).slice(0, -1)}%`),
},
] as FindOptionsWhere<Project>[]
} else {
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index 7fc6dd1c4..e1a580a22 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -420,6 +420,41 @@ export class ProjectService {
})
}
+ // async paginateAll(
+ // options: PaginationOptionsInterface,
+ // where: FindOptionsWhere<Project> | FindOptionsWhere<Project>[],
+ // ): Promise<Pagination<Project>> {
+ // // Create query builder starting from Project
+ // const queryBuilder = this.projectsRepository
+ // .createQueryBuilder('project')
+ // .leftJoinAndSelect('project.admin', 'admin')
+ // .leftJoinAndSelect('project.share', 'share')
+ // .leftJoinAndSelect('share.user', 'sharedUser')
+ // .leftJoinAndSelect('project.funnels', 'funnels')
+ // // Add isOwner flag using CASE expression
+ // .addSelect(
+ // `
+ // CASE
+ // WHEN admin.id = :userId THEN true
+ // ELSE false
+ // END`,
+ // 'project_isOwner',
+ // )
+ // .where('admin.id = :userId', { userId })
+ // .orWhere('share.user.id = :userId', { userId })
+ // .orderBy('project.name', 'ASC')
+ // .skip(options.skip || 0)
+ // .take(options.take || 100)
+
+ // // Execute count and results queries
+ // const [results, total] = await queryBuilder.getManyAndCount()
+
+ // return new Pagination<Project>({
+ // results: processProjectsUser(results),
+ // total,
+ // })
+ // }
+
async count(): Promise<number> {
return this.projectsRepository.count()
}