mirror of
https://github.com/Shadowfita/docmost.git
synced 2025-11-18 18:51:05 +10:00
Refactoring
* replace TypeORM with Kysely query builder * refactor migrations * other changes and fixes
This commit is contained in:
@ -1,94 +0,0 @@
|
||||
import {
|
||||
BeforeInsert,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
Unique,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { Workspace } from '../../workspace/entities/workspace.entity';
|
||||
import { Page } from '../../page/entities/page.entity';
|
||||
import { Comment } from '../../comment/entities/comment.entity';
|
||||
import { Space } from '../../space/entities/space.entity';
|
||||
import { SpaceMember } from '../../space/entities/space-member.entity';
|
||||
|
||||
@Entity('users')
|
||||
@Unique(['email', 'workspaceId'])
|
||||
export class User {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ length: 255, nullable: true })
|
||||
name: string;
|
||||
|
||||
@Column({ length: 255 })
|
||||
email: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
emailVerifiedAt: Date;
|
||||
|
||||
@Column()
|
||||
password: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
avatarUrl: string;
|
||||
|
||||
@Column({ nullable: true, length: 100 })
|
||||
role: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
workspaceId: string;
|
||||
|
||||
@ManyToOne(() => Workspace, (workspace) => workspace.users, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
workspace: Workspace;
|
||||
|
||||
@Column({ length: 100, nullable: true })
|
||||
locale: string;
|
||||
|
||||
@Column({ length: 300, nullable: true })
|
||||
timezone: string;
|
||||
|
||||
@Column({ type: 'jsonb', nullable: true })
|
||||
settings: any;
|
||||
|
||||
@Column({ nullable: true })
|
||||
lastLoginAt: Date;
|
||||
|
||||
@Column({ length: 100, nullable: true })
|
||||
lastLoginIp: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
|
||||
@OneToMany(() => Page, (page) => page.creator)
|
||||
createdPages: Page[];
|
||||
|
||||
@OneToMany(() => Comment, (comment) => comment.creator)
|
||||
comments: Comment[];
|
||||
|
||||
@OneToMany(() => Space, (space) => space.creator)
|
||||
createdSpaces: Space[];
|
||||
|
||||
@OneToMany(() => SpaceMember, (spaceMembership) => spaceMembership.user)
|
||||
spaces: SpaceMember[];
|
||||
|
||||
toJSON() {
|
||||
delete this.password;
|
||||
return this;
|
||||
}
|
||||
|
||||
@BeforeInsert()
|
||||
async hashPassword() {
|
||||
const saltRounds = 12;
|
||||
this.password = await bcrypt.hash(this.password, saltRounds);
|
||||
}
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { User } from '../entities/user.entity';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class UserRepository extends Repository<User> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(User, dataSource.createEntityManager());
|
||||
}
|
||||
async findByEmail(email: string): Promise<User> {
|
||||
const queryBuilder = this.dataSource.createQueryBuilder(User, 'user');
|
||||
return await queryBuilder.where('user.email = :email', { email }).getOne();
|
||||
}
|
||||
|
||||
async findById(userId: string): Promise<User> {
|
||||
const queryBuilder = this.dataSource.createQueryBuilder(User, 'user');
|
||||
return await queryBuilder.where('user.id = :id', { id: userId }).getOne();
|
||||
}
|
||||
|
||||
async findOneByEmail(email: string, workspaceId: string): Promise<User> {
|
||||
const queryBuilder = this.dataSource.createQueryBuilder(User, 'user');
|
||||
return await queryBuilder
|
||||
.where('user.email = :email', { email })
|
||||
.andWhere('user.workspaceId = :workspaceId', { workspaceId })
|
||||
.getOne();
|
||||
}
|
||||
|
||||
async findOneByIdx(userId: string, workspaceId: string): Promise<User> {
|
||||
const queryBuilder = this.dataSource.createQueryBuilder(User, 'user');
|
||||
return await queryBuilder
|
||||
.where('user.id = :id', { id: userId })
|
||||
.andWhere('user.workspaceId = :workspaceId', { workspaceId })
|
||||
.getOne();
|
||||
}
|
||||
}
|
||||
@ -8,20 +8,28 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { AuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
import { UserRepo } from '@docmost/db/repos/user/user.repo';
|
||||
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
|
||||
import { User, Workspace } from '@docmost/db/types/entity.types';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('users')
|
||||
export class UserController {
|
||||
constructor(private readonly userService: UserService) {}
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private userRepo: UserRepo,
|
||||
) {}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('me')
|
||||
async getUser(@AuthUser() authUser: User) {
|
||||
const user: User = await this.userService.findById(authUser.id);
|
||||
async getUser(
|
||||
@AuthUser() authUser: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
const user = await this.userRepo.findById(authUser.id, workspace.id);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Invalid user');
|
||||
@ -35,7 +43,8 @@ export class UserController {
|
||||
async updateUser(
|
||||
@Body() updateUserDto: UpdateUserDto,
|
||||
@AuthUser() user: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.userService.update(user.id, updateUserDto);
|
||||
return this.userService.update(updateUserDto, user.id, workspace.id);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,14 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { UserController } from './user.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UserRepository } from './repositories/user.repository';
|
||||
import { UserRepo } from '@docmost/db/repos/user/user.repo';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([User])],
|
||||
controllers: [UserController],
|
||||
providers: [UserService, UserRepository],
|
||||
exports: [UserService, UserRepository],
|
||||
providers: [UserService, UserRepo],
|
||||
exports: [UserService, UserRepo],
|
||||
})
|
||||
export class UserModule {}
|
||||
|
||||
@ -1,77 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UserService } from './user.service';
|
||||
import { UserRepository } from './repositories/user.repository';
|
||||
import { User } from './entities/user.entity';
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { CreateUserDto } from '../auth/dto/create-user.dto';
|
||||
|
||||
describe('UserService', () => {
|
||||
let userService: UserService;
|
||||
let userRepository: any;
|
||||
|
||||
const mockUserRepository = () => ({
|
||||
findByEmail: jest.fn(),
|
||||
save: jest.fn(),
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
UserService,
|
||||
{
|
||||
provide: UserRepository,
|
||||
useFactory: mockUserRepository,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
userService = module.get<UserService>(UserService);
|
||||
userRepository = module.get<UserRepository>(UserRepository);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(userService).toBeDefined();
|
||||
expect(userRepository).toBeDefined();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
const createUserDto: CreateUserDto = {
|
||||
name: 'John Doe',
|
||||
email: 'test@test.com',
|
||||
password: 'password',
|
||||
};
|
||||
|
||||
it('should throw an error if a user with this email already exists', async () => {
|
||||
userRepository.findByEmail.mockResolvedValue(new User());
|
||||
await expect(userService.create(createUserDto)).rejects.toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should create the user if it does not already exist', async () => {
|
||||
const savedUser = {
|
||||
...createUserDto,
|
||||
id: expect.any(String),
|
||||
createdAt: expect.any(Date),
|
||||
updatedAt: expect.any(Date),
|
||||
lastLoginAt: expect.any(Date),
|
||||
locale: 'en',
|
||||
emailVerifiedAt: null,
|
||||
avatar_url: null,
|
||||
timezone: null,
|
||||
settings: null,
|
||||
lastLoginIp: null,
|
||||
};
|
||||
|
||||
//userRepository.findByEmail.mockResolvedValue(undefined);
|
||||
userRepository.save.mockResolvedValue(savedUser);
|
||||
|
||||
const result = await userService.create(createUserDto);
|
||||
expect(result).toMatchObject(savedUser);
|
||||
|
||||
expect(userRepository.save).toHaveBeenCalledWith(
|
||||
expect.objectContaining(createUserDto),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -4,19 +4,23 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UserRepository } from './repositories/user.repository';
|
||||
import { UserRepo } from '@docmost/db/repos/user/user.repo';
|
||||
import { hashPassword } from '../../helpers/utils';
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(private userRepository: UserRepository) {}
|
||||
constructor(private userRepo: UserRepo) {}
|
||||
|
||||
async findById(userId: string) {
|
||||
return this.userRepository.findById(userId);
|
||||
async findById(userId: string, workspaceId: string) {
|
||||
return this.userRepo.findById(userId, workspaceId);
|
||||
}
|
||||
|
||||
async update(userId: string, updateUserDto: UpdateUserDto) {
|
||||
const user = await this.userRepository.findById(userId);
|
||||
async update(
|
||||
updateUserDto: UpdateUserDto,
|
||||
userId: string,
|
||||
workspaceId: string,
|
||||
) {
|
||||
const user = await this.userRepo.findById(userId, workspaceId);
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
@ -27,7 +31,7 @@ export class UserService {
|
||||
|
||||
// todo need workspace scoping
|
||||
if (updateUserDto.email && user.email != updateUserDto.email) {
|
||||
if (await this.userRepository.findByEmail(updateUserDto.email)) {
|
||||
if (await this.userRepo.findByEmail(updateUserDto.email, workspaceId)) {
|
||||
throw new BadRequestException('A user with this email already exists');
|
||||
}
|
||||
user.email = updateUserDto.email;
|
||||
@ -37,6 +41,11 @@ export class UserService {
|
||||
user.avatarUrl = updateUserDto.avatarUrl;
|
||||
}
|
||||
|
||||
return this.userRepository.save(user);
|
||||
if (updateUserDto.password) {
|
||||
updateUserDto.password = await hashPassword(updateUserDto.password);
|
||||
}
|
||||
|
||||
await this.userRepo.updateUser(updateUserDto, userId, workspaceId);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user