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!

Added basic 'project' backends & minor improvements

Blaumaus3fc45874fb88
diff --git a/src/app.module.ts b/src/app.module.ts
index 22440d04b..fefc4e1e3 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -6,6 +6,8 @@ import { ScheduleModule } from '@nestjs/schedule'
import { AuthModule } from './auth/auth.module'
import { UserModule } from './user/user.module'
import { User } from './user/entities/user.entity'
+import { Project } from './project/entity/project.entity'
+import { ProjectModule } from './project/project.module'
import { MailerModule } from './mailer/mailer.module'
import { ActionTokensModule } from './action-tokens/action-tokens.module'
import { ActionToken } from './action-tokens/action-token.entity'
@@ -22,7 +24,7 @@ import { TaskManagerModule } from './task-manager/task-manager.module'
password: process.env.MYSQL_ROOT_PASSWORD || '123123123',
database: process.env.MYSQL_DATABASE || 'analytics',
synchronize: true,
- entities: [User, ActionToken],
+ entities: [User, ActionToken, Project],
}),
ScheduleModule.forRoot(),
TaskManagerModule,
@@ -30,6 +32,7 @@ import { TaskManagerModule } from './task-manager/task-manager.module'
UserModule,
MailerModule,
ActionTokensModule,
+ ProjectModule,
],
})
diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts
index f8f442e9b..b095c4672 100644
--- a/src/auth/auth.controller.ts
+++ b/src/auth/auth.controller.ts
@@ -34,7 +34,7 @@ export class AuthController {
@Get('/me')
@UseGuards(RolesGuard)
- @Roles(UserType.FREE)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
async me(@CurrentUserId() user_id: string): Promise<User> {
this.logger.log({ user_id }, 'GET /auth/me')
return this.userService.findOneWhere({ id: user_id })
diff --git a/src/project/dto/project.dto.ts b/src/project/dto/project.dto.ts
new file mode 100644
index 000000000..3484f3e97
--- /dev/null
+++ b/src/project/dto/project.dto.ts
@@ -0,0 +1,20 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty } from 'class-validator'
+
+export class ProjectDTO {
+ @ApiProperty({
+ example: 'Your awesome project',
+ required: true,
+ description: 'A display name for your project'
+ })
+ @IsNotEmpty()
+ name: string
+
+ @ApiProperty({
+ example: 'aUn1quEid-3',
+ required: true,
+ description: 'A unique project ID'
+ })
+ @IsNotEmpty()
+ id: string
+}
\ No newline at end of file
diff --git a/src/project/entity/project.entity.ts b/src/project/entity/project.entity.ts
new file mode 100644
index 000000000..ad417f881
--- /dev/null
+++ b/src/project/entity/project.entity.ts
@@ -0,0 +1,19 @@
+import { Entity, Column, PrimaryColumn, ManyToOne } from 'typeorm'
+import { ApiProperty } from '@nestjs/swagger'
+
+import { User } from '../../user/entities/user.entity'
+
+@Entity()
+export class Project {
+ @ApiProperty()
+ @PrimaryColumn('varchar', { unique: true })
+ id: string
+
+ @ApiProperty()
+ @Column('varchar', { length: 80 })
+ name: string
+
+ @ApiProperty({ type: () => User })
+ @ManyToOne(() => User, user => user.projects)
+ admin: User
+}
\ No newline at end of file
diff --git a/src/project/project.controller.spec.ts b/src/project/project.controller.spec.ts
new file mode 100644
index 000000000..8a6a365c9
--- /dev/null
+++ b/src/project/project.controller.spec.ts
@@ -0,0 +1,18 @@
+import { Test, TestingModule } from '@nestjs/testing'
+import { ProjectController } from './project.controller'
+
+describe('ProjectController', () => {
+ let controller: ProjectController
+
+ beforeEach(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ controllers: [ProjectController],
+ }).compile()
+
+ controller = module.get<ProjectController>(ProjectController)
+ })
+
+ it('should be defined', () => {
+ expect(controller).toBeDefined()
+ })
+})
diff --git a/src/project/project.controller.ts b/src/project/project.controller.ts
new file mode 100644
index 000000000..f6d1a32c4
--- /dev/null
+++ b/src/project/project.controller.ts
@@ -0,0 +1,133 @@
+import { Controller, Body, Query, Param, UseGuards, Get, Post, Put, Delete, BadRequestException,
+ HttpCode, NotFoundException } from '@nestjs/common'
+import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'
+
+import { ProjectService } from './project.service'
+import { UserType } from '../user/entities/user.entity'
+import { Roles } from '../common/decorators/roles.decorator'
+import { RolesGuard } from '../common/guards/roles.guard'
+import { Pagination } from '../common/pagination/pagination'
+import { Project } from './entity/project.entity'
+import { CurrentUserId } from '../common/decorators/current-user-id.decorator'
+import { UserService } from '../user/user.service'
+import { ProjectDTO } from './dto/project.dto'
+import { AppLoggerService } from '../logger/logger.service'
+
+@ApiTags('Project')
+@Controller('project')
+export class ProjectController {
+ constructor(
+ private readonly projectService: ProjectService,
+ private readonly userService: UserService,
+ private readonly logger: AppLoggerService,
+ ) {}
+
+ @Get('/')
+ @ApiQuery({ name: 'take', required: false })
+ @ApiQuery({ name: 'skip', required: false })
+ @ApiQuery({ name: 'relatedonly', required: false, type: Boolean })
+ @ApiResponse({status: 200, type: [Project]})
+ @UseGuards(RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async get(
+ @CurrentUserId() userId: string,
+ @Query('take') take: number | undefined,
+ @Query('skip') skip: number | undefined,): Promise<Pagination<Project> | Project[]> {
+ this.logger.log({ userId, take, skip }, 'GET /project')
+ // const user = await this.userService.findOne(userId)
+ const where = Object()
+
+ where.admin = userId
+
+ return await this.projectService.paginate({ take, skip }, where)
+ }
+
+ @Get('/:id')
+ @ApiResponse({ status: 200, type: Project })
+ async getOne(@Param('id') id: string): Promise<Project> {
+ this.logger.log({ id }, 'GET /project/:id')
+ const project = await this.projectService.findOne(id)
+
+ if (project) {
+ return project
+ } else {
+ throw new NotFoundException()
+ }
+ }
+
+ @Post('/')
+ @ApiResponse({ status: 201, type: Project })
+ @UseGuards(RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ async create(@Body() projectDTO: ProjectDTO, @CurrentUserId() userId: string): Promise<Project> {
+ this.logger.log({ projectDTO, userId }, 'POST /project')
+
+ await this.projectService.checkIfIDUnique(projectDTO.id)
+
+ try {
+ const project = await this.projectService.create(projectDTO)
+ return project
+ } catch(e) {
+ if (e.code === 'ER_DUP_ENTRY'){
+ if (e.sqlMessage.includes(projectDTO.id)){
+ throw new BadRequestException('Project with selected ID already exists')
+ }
+ }
+
+ throw new BadRequestException(e)
+ }
+ }
+
+ @Put('/:id')
+ @HttpCode(200)
+ @UseGuards(RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @ApiResponse({ status: 200, type: Project })
+ async update(@Param('id') id: string, @Body() projectDTO: ProjectDTO, @CurrentUserId() userId: string): Promise<any> {
+ this.logger.log({ projectDTO, userId, id }, 'PUT /project/:id')
+
+ const project = await this.projectService.findOneWithRelations(id)
+
+ if (!project) {
+ throw new NotFoundException()
+ }
+
+ await this.projectService.allowedToManage(project.id, userId)
+ await this.projectService.checkIfIDUnique(projectDTO.id)
+
+ try {
+ await this.projectService.update(id, projectDTO)
+ return this.projectService.findOne(id)
+ } catch(e) {
+ if (e.code === 'ER_DUP_ENTRY'){
+ if (e.sqlMessage.includes(projectDTO.id)) {
+ throw new BadRequestException('Project with selected ID already exists')
+ }
+ }
+
+ return new BadRequestException(e)
+ }
+ }
+
+ @Delete('/:id')
+ @HttpCode(204)
+ @UseGuards(RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @ApiResponse({ status: 204, description: 'Empty body' })
+ async delete(@Param('id') id: string, @CurrentUserId() userId: string): Promise<any> {
+ this.logger.log({ userId, id }, 'DELETE /project/:id')
+ const project = await this.projectService.findOneWithRelations(id)
+
+ if (!project) {
+ throw new NotFoundException(`Project with ID ${id} does not exist`)
+ }
+ await this.projectService.allowedToManage(project.id, userId)
+
+ try {
+ await this.projectService.delete(id)
+ return 'Project deleted successfully'
+ } catch(e) {
+ return e
+ }
+ }
+}
diff --git a/src/project/project.module.ts b/src/project/project.module.ts
new file mode 100644
index 000000000..9d3acaa96
--- /dev/null
+++ b/src/project/project.module.ts
@@ -0,0 +1,20 @@
+import { Module, forwardRef } from '@nestjs/common'
+import { TypeOrmModule } from '@nestjs/typeorm'
+
+import { Project } from './entity/project.entity'
+import { ProjectService } from './project.service'
+import { ProjectController } from './project.controller'
+import { UserModule } from '../user/user.module'
+import { AppLoggerModule } from '../logger/logger.module'
+
+@Module({
+ imports: [
+ TypeOrmModule.forFeature([Project]),
+ forwardRef(() => UserModule),
+ AppLoggerModule
+ ],
+ providers: [ProjectService],
+ exports: [ProjectService],
+ controllers: [ProjectController],
+})
+export class ProjectModule {}
diff --git a/src/project/project.service.spec.ts b/src/project/project.service.spec.ts
new file mode 100644
index 000000000..0905a2e79
--- /dev/null
+++ b/src/project/project.service.spec.ts
@@ -0,0 +1,18 @@
+import { Test, TestingModule } from '@nestjs/testing'
+import { ProjectService } from './project.service'
+
+describe('ProjectService', () => {
+ let service: ProjectService
+
+ beforeEach(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [ProjectService],
+ }).compile()
+
+ service = module.get<ProjectService>(ProjectService)
+ })
+
+ it('should be defined', () => {
+ expect(service).toBeDefined()
+ })
+})
diff --git a/src/project/project.service.ts b/src/project/project.service.ts
new file mode 100644
index 000000000..fb02ed6f3
--- /dev/null
+++ b/src/project/project.service.ts
@@ -0,0 +1,86 @@
+import { ForbiddenException, Injectable, BadRequestException } from '@nestjs/common'
+import { InjectRepository } from '@nestjs/typeorm'
+import { Repository } from 'typeorm'
+
+import { Pagination, PaginationOptionsInterface } from '../common/pagination'
+import { Project } from './entity/project.entity'
+import { ProjectDTO } from './dto/project.dto'
+import { User, UserType } from '../user/entities/user.entity'
+import { UserService } from '../user/user.service'
+
+@Injectable()
+export class ProjectService {
+ constructor(
+ @InjectRepository(Project)
+ private projectsRepository: Repository<Project>,
+ private readonly userService: UserService
+ ) {}
+
+ async paginate(options: PaginationOptionsInterface, where: Record<string, unknown> | undefined): Promise<Pagination<Project>> {
+ const [results, total] = await this.projectsRepository.findAndCount({
+ take: options.take || 10,
+ skip: options.skip || 0,
+ where: where,
+ order: {
+ name: 'ASC',
+ }
+ })
+
+ return new Pagination<Project>({
+ results,
+ total,
+ })
+ }
+
+ count(): Promise<number> {
+ return this.projectsRepository.count()
+ }
+
+ async create(project: ProjectDTO): Promise<Project> {
+ return this.projectsRepository.save(project)
+ }
+
+ async update(id: string, ProjectDTO: ProjectDTO): Promise<any> {
+ return this.projectsRepository.update(id, ProjectDTO)
+ }
+
+ async delete(id: string): Promise<any> {
+ return this.projectsRepository.delete(id)
+ }
+
+ findOneWithRelations(id: string): Promise<Project | null> {
+ return this.projectsRepository.findOne(id, { relations: ['user'] })
+ }
+
+ findOne(id: string): Promise<Project | null> {
+ return this.projectsRepository.findOne(id)
+ }
+
+ findOneWhere(where: Record<string, unknown>): Promise<Project> {
+ return this.projectsRepository.findOne({ where })
+ }
+
+ ifAllowedToManage(userId: string, project: Project): boolean {
+ return userId === project.admin.id
+ }
+
+ async allowedToManage(projectId: string, userId: string): Promise<void> {
+ const user = await this.userService.findOne(userId)
+ const project = await this.findOne(projectId)
+
+ // if (user.projects.some(({ id }) => project.id === id)) {
+ if (this.ifAllowedToManage(user.id, project)) {
+ return
+ } else {
+ throw new ForbiddenException('Not allowed to manage this project')
+ }
+ }
+
+ async checkIfIDUnique(projectId: string): Promise<void> {
+ const project = await this.findOne(projectId)
+
+ if (project) {
+ throw new BadRequestException('Selected project ID is already in use')
+ }
+ }
+}
diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.ts
index 97ecee518..50f3d5683 100644
--- a/src/user/entities/user.entity.ts
+++ b/src/user/entities/user.entity.ts
@@ -1,12 +1,31 @@
-import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm'
+import { Entity, Column, PrimaryGeneratedColumn, OneToMany, BeforeUpdate } from 'typeorm'
import { ActionToken } from 'src/action-tokens/action-token.entity'
+import { Project } from 'src/project/entity/project.entity'
+
+const FREE_PLAN = {
+ code: 'free',
+ displayName: 'Free plan',
+ monthlyUsageLimit: 5000,
+ stripePriceID: '',
+}
+
+const BASIC_PLAN = {
+ code: 'free',
+ displayName: 'Free plan',
+ monthlyUsageLimit: 5000,
+ stripePriceID: '',
+}
+
+const ENTERPRISE_PLAN = {
+ code: 'free',
+ displayName: 'Free plan',
+ monthlyUsageLimit: 5000,
+ stripePriceID: '',
+}
export enum UserType {
- FREE = 'free',
- TIER_1 = 'tier_1',
- TIER_2 = 'tier_2',
- ENTERPRISE = 'enterprise',
- ADMIN = 'admin'
+ CUSTOMER = 'customer',
+ ADMIN = 'admin',
}
export const MAX_EMAIL_REQUESTS = 4 // 1 confirmation email on sign up + 3 additional ones
@@ -19,14 +38,14 @@ export class User {
@Column({
type: 'set',
enum: UserType,
- default: UserType.FREE
+ default: UserType.CUSTOMER
})
roles: UserType[]
@Column('varchar', { length: 254, unique: true })
email: string
- @Column('varchar', { length: 200, default: '' })
+ @Column('varchar', { length: 60, default: '' })
password: string
@Column({ default: false })
@@ -35,9 +54,23 @@ export class User {
@Column('int', { default: 1 })
emailRequests: number
+ @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
+ created: Date;
+
+ @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
+ updated: Date;
+
+ @BeforeUpdate()
+ updateTimestamp() {
+ this.updated = new Date;
+ }
+
// @Column('datetime', { nullable: true, default: null })
// consent: Date
+ @OneToMany(() => Project, project => project.admin)
+ projects: Project[]
+
@OneToMany(() => ActionToken, actionToken => actionToken.user)
actionTokens: ActionToken[]
}
\ No newline at end of file
diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts
index 023a4e72a..80cf90ac8 100644
--- a/src/user/user.controller.ts
+++ b/src/user/user.controller.ts
@@ -89,16 +89,17 @@ export class UserController {
@Delete('/')
@HttpCode(204)
@UseGuards(RolesGuard)
- @Roles(UserType.FREE)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
async deleteSelf(@CurrentUserId() uid: string): Promise<any> {
this.logger.log({ uid }, 'DELETE /user')
+ // TODO: Delete all users projects
await this.userService.delete(uid)
return
}
@Post('/confirm_email')
@UseGuards(RolesGuard)
- @Roles(UserType.FREE)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
async sendEmailConfirmation(@CurrentUserId() id: string, @Req() request: Request): Promise<boolean> {
this.logger.log({ id }, 'POST /confirm_email')
@@ -146,7 +147,7 @@ export class UserController {
@Put('/')
@UseGuards(RolesGuard)
- @Roles(UserType.FREE)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
async updateCurrentUser(@Body() userDTO: UpdateUserProfileDTO, @CurrentUserId() id: string, @Req() request: Request): Promise<User> {
this.logger.log({ userDTO, id }, 'PUT /user')
const user = await this.userService.findOneWhere({ id })
@@ -179,7 +180,7 @@ export class UserController {
@Get('/export')
@UseGuards(RolesGuard)
- @Roles(UserType.FREE)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
async exportUserData(@CurrentUserId() user_id: string): Promise<User> {
this.logger.log({ user_id }, 'GET /user/export')
const user = await this.userService.findOneWhere({ id: user_id })
diff --git a/src/user/user.service.ts b/src/user/user.service.ts
index b3ffe765a..71bb220e6 100644
--- a/src/user/user.service.ts
+++ b/src/user/user.service.ts
@@ -42,6 +42,10 @@ export class UserService {
return this.usersRepository.findOne({ where, relations })
}
+ findOne(id: string): Promise<User> {
+ return this.findOneWhere({ id })
+ }
+
findWhere(where: Record<string, unknown>): Promise<User[]> {
return this.usersRepository.find({ where })
}
@@ -72,10 +76,10 @@ export class UserService {
search(query: string): Promise<User[]> {
return this.usersRepository
- .createQueryBuilder('user')
- .select()
- .where('email like :query', { query: `%${query}%` })
- .limit(5)
- .getMany()
+ .createQueryBuilder('user')
+ .select()
+ .where('email like :query', { query: `%${query}%` })
+ .limit(5)
+ .getMany()
}
}