mirror of
https://github.com/docmost/docmost.git
synced 2025-11-17 00:31:10 +10:00
Refactoring
* Refactor workspace membership system * Create setup endpoint * Use Passport.js * Several updates and fixes
This commit is contained in:
@ -12,18 +12,18 @@ import {
|
||||
import { AttachmentService } from './attachment.service';
|
||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { AttachmentInterceptor } from './attachment.interceptor';
|
||||
import { JwtGuard } from '../auth/guards/jwt.guard';
|
||||
import * as bytes from 'bytes';
|
||||
import { AuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { CurrentWorkspace } from '../../decorators/current-workspace.decorator';
|
||||
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
|
||||
import { Workspace } from '../workspace/entities/workspace.entity';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
|
||||
@Controller('attachments')
|
||||
export class AttachmentController {
|
||||
constructor(private readonly attachmentService: AttachmentService) {}
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@Post('upload/avatar')
|
||||
@UseInterceptors(AttachmentInterceptor)
|
||||
@ -50,7 +50,7 @@ export class AttachmentController {
|
||||
}
|
||||
}
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@Post('upload/workspace-logo')
|
||||
@UseInterceptors(AttachmentInterceptor)
|
||||
@ -58,7 +58,7 @@ export class AttachmentController {
|
||||
@Req() req: FastifyRequest,
|
||||
@Res() res: FastifyReply,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
const maxFileSize = bytes('5MB');
|
||||
|
||||
@ -79,7 +79,7 @@ export class AttachmentController {
|
||||
}
|
||||
}
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@Post('upload/file')
|
||||
@UseInterceptors(AttachmentInterceptor)
|
||||
@ -87,7 +87,7 @@ export class AttachmentController {
|
||||
@Req() req: FastifyRequest,
|
||||
@Res() res: FastifyReply,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
const maxFileSize = bytes('20MB');
|
||||
|
||||
|
||||
@ -1,11 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AttachmentService } from './attachment.service';
|
||||
import { AttachmentController } from './attachment.controller';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { StorageModule } from '../../integrations/storage/storage.module';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Attachment } from './entities/attachment.entity';
|
||||
import { AttachmentRepository } from './repositories/attachment.repository';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { UserModule } from '../user/user.module';
|
||||
import { WorkspaceModule } from '../workspace/workspace.module';
|
||||
|
||||
@ -13,7 +12,6 @@ import { WorkspaceModule } from '../workspace/workspace.module';
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Attachment]),
|
||||
StorageModule,
|
||||
AuthModule,
|
||||
UserModule,
|
||||
WorkspaceModule,
|
||||
],
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageService } from '../../integrations/storage/storage.service';
|
||||
import { MultipartFile } from '@fastify/multipart';
|
||||
import { AttachmentRepository } from './repositories/attachment.repository';
|
||||
import { Attachment } from './entities/attachment.entity';
|
||||
|
||||
@ -1,27 +1,47 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { AuthService } from './services/auth.service';
|
||||
import { CreateUserDto } from '../user/dto/create-user.dto';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { SetupGuard } from './guards/setup.guard';
|
||||
import { EnvironmentService } from '../../environment/environment.service';
|
||||
import { CreateAdminUserDto } from './dto/create-admin-user.dto';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private authService: AuthService) {}
|
||||
constructor(
|
||||
private authService: AuthService,
|
||||
private environmentService: EnvironmentService,
|
||||
) {}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('login')
|
||||
async login(@Body() loginInput: LoginDto) {
|
||||
return await this.authService.login(loginInput);
|
||||
async login(@Req() req, @Body() loginInput: LoginDto) {
|
||||
return this.authService.login(loginInput, req.raw.workspaceId);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('register')
|
||||
async register(@Body() createUserDto: CreateUserDto) {
|
||||
return await this.authService.register(createUserDto);
|
||||
async register(@Req() req, @Body() createUserDto: CreateUserDto) {
|
||||
return this.authService.register(createUserDto, req.raw.workspaceId);
|
||||
}
|
||||
|
||||
@UseGuards(SetupGuard)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('setup')
|
||||
async setupWorkspace(
|
||||
@Req() req,
|
||||
@Body() createAdminUserDto: CreateAdminUserDto,
|
||||
) {
|
||||
if (this.environmentService.isCloud()) throw new NotFoundException();
|
||||
return this.authService.setup(createAdminUserDto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,13 +4,17 @@ import { AuthService } from './services/auth.service';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { EnvironmentService } from '../../environment/environment.service';
|
||||
import { TokenService } from './services/token.service';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
import { WorkspaceModule } from '../workspace/workspace.module';
|
||||
import { SignupService } from './services/signup.service';
|
||||
import { UserModule } from '../user/user.module';
|
||||
import { SpaceModule } from '../space/space.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
JwtModule.registerAsync({
|
||||
useFactory: async (environmentService: EnvironmentService) => {
|
||||
return {
|
||||
global: true,
|
||||
secret: environmentService.getJwtSecret(),
|
||||
signOptions: {
|
||||
expiresIn: environmentService.getJwtTokenExpiresIn(),
|
||||
@ -18,10 +22,13 @@ import { TokenService } from './services/token.service';
|
||||
};
|
||||
},
|
||||
inject: [EnvironmentService],
|
||||
}),
|
||||
} as any),
|
||||
UserModule,
|
||||
WorkspaceModule,
|
||||
SpaceModule,
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, TokenService],
|
||||
providers: [AuthService, SignupService, TokenService, JwtStrategy],
|
||||
exports: [TokenService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
8
apps/server/src/core/auth/auth.utils.ts
Normal file
8
apps/server/src/core/auth/auth.utils.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
export async function comparePasswordHash(
|
||||
plainPassword: string,
|
||||
passwordHash: string,
|
||||
): Promise<boolean> {
|
||||
return bcrypt.compare(plainPassword, passwordHash);
|
||||
}
|
||||
15
apps/server/src/core/auth/dto/create-admin-user.dto.ts
Normal file
15
apps/server/src/core/auth/dto/create-admin-user.dto.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString, MaxLength, MinLength } from 'class-validator';
|
||||
import { CreateUserDto } from './create-user.dto';
|
||||
|
||||
export class CreateAdminUserDto extends CreateUserDto {
|
||||
@IsNotEmpty()
|
||||
@MinLength(3)
|
||||
@MaxLength(35)
|
||||
name: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@MinLength(4)
|
||||
@MaxLength(35)
|
||||
@IsString()
|
||||
workspaceName: string;
|
||||
}
|
||||
@ -2,13 +2,14 @@ import {
|
||||
IsEmail,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsString, MaxLength,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CreateUserDto {
|
||||
@IsOptional()
|
||||
@MinLength(3)
|
||||
@MaxLength(35)
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
16
apps/server/src/core/auth/dto/jwt-payload.ts
Normal file
16
apps/server/src/core/auth/dto/jwt-payload.ts
Normal file
@ -0,0 +1,16 @@
|
||||
export enum JwtType {
|
||||
ACCESS = 'access',
|
||||
REFRESH = 'refresh',
|
||||
}
|
||||
export type JwtPayload = {
|
||||
sub: string;
|
||||
email: string;
|
||||
workspaceId: string;
|
||||
type: 'access';
|
||||
};
|
||||
|
||||
export type JwtRefreshPayload = {
|
||||
sub: string;
|
||||
workspaceId: string;
|
||||
type: 'refresh';
|
||||
};
|
||||
@ -1,55 +0,0 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { TokenService } from '../services/token.service';
|
||||
import { UserService } from '../../user/user.service';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { IS_PUBLIC_KEY } from '../../../decorators/public.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class JwtGuard implements CanActivate {
|
||||
constructor(
|
||||
private tokenService: TokenService,
|
||||
private userService: UserService,
|
||||
private reflector: Reflector,
|
||||
) {}
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token: string = await this.tokenService.extractTokenFromHeader(
|
||||
request,
|
||||
);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Invalid jwt token');
|
||||
}
|
||||
|
||||
let payload;
|
||||
|
||||
try {
|
||||
payload = await this.tokenService.verifyJwt(token);
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Could not verify jwt token');
|
||||
}
|
||||
|
||||
try {
|
||||
//fetch user and current workspace data from db
|
||||
request['user'] = await this.userService.getUserInstance(payload.sub);
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Failed to fetch auth user');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
14
apps/server/src/core/auth/guards/setup.guard.ts
Normal file
14
apps/server/src/core/auth/guards/setup.guard.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { CanActivate, ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { WorkspaceRepository } from '../../workspace/repositories/workspace.repository';
|
||||
|
||||
@Injectable()
|
||||
export class SetupGuard implements CanActivate {
|
||||
constructor(private workspaceRepository: WorkspaceRepository) {}
|
||||
async canActivate(): Promise<boolean> {
|
||||
const workspaceCount = await this.workspaceRepository.count();
|
||||
if (workspaceCount > 0) {
|
||||
throw new ForbiddenException('Workspace setup already completed.');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -1,38 +1,57 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { LoginDto } from '../dto/login.dto';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { CreateUserDto } from '../../user/dto/create-user.dto';
|
||||
import { CreateUserDto } from '../dto/create-user.dto';
|
||||
import { UserService } from '../../user/user.service';
|
||||
import { TokenService } from './token.service';
|
||||
import { TokensDto } from '../dto/tokens.dto';
|
||||
import { UserRepository } from '../../user/repositories/user.repository';
|
||||
import { comparePasswordHash } from '../auth.utils';
|
||||
import { SignupService } from './signup.service';
|
||||
import { CreateAdminUserDto } from '../dto/create-admin-user.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private userService: UserService,
|
||||
private signupService: SignupService,
|
||||
private tokenService: TokenService,
|
||||
private userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async login(loginDto: LoginDto) {
|
||||
const user: User = await this.userService.findByEmail(loginDto.email);
|
||||
const invalidCredentialsMessage = 'email or password does not match';
|
||||
async login(loginDto: LoginDto, workspaceId: string) {
|
||||
const user = await this.userRepository.findOneByEmail(
|
||||
loginDto.email,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
if (
|
||||
!user ||
|
||||
!(await this.userService.compareHash(loginDto.password, user.password))
|
||||
!(await comparePasswordHash(loginDto.password, user.password))
|
||||
) {
|
||||
throw new UnauthorizedException(invalidCredentialsMessage);
|
||||
throw new UnauthorizedException('email or password does not match');
|
||||
}
|
||||
|
||||
user.lastLoginAt = new Date();
|
||||
await this.userRepository.save(user);
|
||||
|
||||
const tokens: TokensDto = await this.tokenService.generateTokens(user);
|
||||
return { tokens };
|
||||
}
|
||||
|
||||
async register(createUserDto: CreateUserDto, workspaceId: string) {
|
||||
const user: User = await this.signupService.signup(
|
||||
createUserDto,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
const tokens: TokensDto = await this.tokenService.generateTokens(user);
|
||||
|
||||
return { tokens };
|
||||
}
|
||||
|
||||
async register(createUserDto: CreateUserDto) {
|
||||
const user: User = await this.userService.create(createUserDto);
|
||||
async setup(createAdminUserDto: CreateAdminUserDto) {
|
||||
const user: User = await this.signupService.firstSetup(createAdminUserDto);
|
||||
|
||||
const tokens: TokensDto = await this.tokenService.generateTokens(user);
|
||||
|
||||
|
||||
121
apps/server/src/core/auth/services/signup.service.ts
Normal file
121
apps/server/src/core/auth/services/signup.service.ts
Normal file
@ -0,0 +1,121 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { CreateUserDto } from '../dto/create-user.dto';
|
||||
import { DataSource, EntityManager } from 'typeorm';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { transactionWrapper } from '../../../helpers/db.helper';
|
||||
import { UserRepository } from '../../user/repositories/user.repository';
|
||||
import { WorkspaceRepository } from '../../workspace/repositories/workspace.repository';
|
||||
import { WorkspaceService } from '../../workspace/services/workspace.service';
|
||||
import { CreateWorkspaceDto } from '../../workspace/dto/create-workspace.dto';
|
||||
import { Workspace } from '../../workspace/entities/workspace.entity';
|
||||
import { SpaceService } from '../../space/space.service';
|
||||
import { CreateAdminUserDto } from '../dto/create-admin-user.dto';
|
||||
|
||||
@Injectable()
|
||||
export class SignupService {
|
||||
constructor(
|
||||
private userRepository: UserRepository,
|
||||
private workspaceRepository: WorkspaceRepository,
|
||||
private workspaceService: WorkspaceService,
|
||||
private spaceService: SpaceService,
|
||||
private dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
prepareUser(createUserDto: CreateUserDto): User {
|
||||
const user = new User();
|
||||
user.name = createUserDto.name || createUserDto.email.split('@')[0];
|
||||
user.email = createUserDto.email.toLowerCase();
|
||||
user.password = createUserDto.password;
|
||||
user.locale = 'en';
|
||||
user.lastLoginAt = new Date();
|
||||
return user;
|
||||
}
|
||||
|
||||
async createUser(
|
||||
createUserDto: CreateUserDto,
|
||||
manager?: EntityManager,
|
||||
): Promise<User> {
|
||||
return await transactionWrapper(
|
||||
async (transactionManager: EntityManager) => {
|
||||
let user = this.prepareUser(createUserDto);
|
||||
user = await transactionManager.save(user);
|
||||
|
||||
return user;
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
async signup(
|
||||
createUserDto: CreateUserDto,
|
||||
workspaceId: string,
|
||||
manager?: EntityManager,
|
||||
): Promise<User> {
|
||||
const userCheck = await this.userRepository.findOneByEmail(
|
||||
createUserDto.email,
|
||||
workspaceId,
|
||||
);
|
||||
if (userCheck) {
|
||||
throw new BadRequestException('You have an account on this workspace');
|
||||
}
|
||||
|
||||
return await transactionWrapper(
|
||||
async (manager: EntityManager) => {
|
||||
// create user
|
||||
const user = await this.createUser(createUserDto, manager);
|
||||
|
||||
// add user to workspace
|
||||
await this.workspaceService.addUserToWorkspace(
|
||||
user,
|
||||
workspaceId,
|
||||
undefined,
|
||||
manager,
|
||||
);
|
||||
return user;
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
async createWorkspace(
|
||||
user: User,
|
||||
workspaceName,
|
||||
manager?: EntityManager,
|
||||
): Promise<Workspace> {
|
||||
return await transactionWrapper(
|
||||
async (manager: EntityManager) => {
|
||||
// for cloud
|
||||
const workspaceData: CreateWorkspaceDto = {
|
||||
name: workspaceName,
|
||||
// hostname: '', // generate
|
||||
};
|
||||
|
||||
return await this.workspaceService.create(user, workspaceData, manager);
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
async firstSetup(
|
||||
createAdminUserDto: CreateAdminUserDto,
|
||||
manager?: EntityManager,
|
||||
): Promise<User> {
|
||||
return await transactionWrapper(
|
||||
async (manager: EntityManager) => {
|
||||
// create user
|
||||
const user = await this.createUser(createAdminUserDto, manager);
|
||||
await this.createWorkspace(
|
||||
user,
|
||||
createAdminUserDto.workspaceName,
|
||||
manager,
|
||||
);
|
||||
return user;
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -2,10 +2,8 @@ import { Injectable } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { EnvironmentService } from '../../../environment/environment.service';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { TokensDto } from '../dto/tokens.dto';
|
||||
|
||||
export type JwtPayload = { sub: string; email: string };
|
||||
import { JwtPayload, JwtRefreshPayload, JwtType } from '../dto/jwt-payload';
|
||||
|
||||
@Injectable()
|
||||
export class TokenService {
|
||||
@ -13,31 +11,37 @@ export class TokenService {
|
||||
private jwtService: JwtService,
|
||||
private environmentService: EnvironmentService,
|
||||
) {}
|
||||
async generateJwt(user: User): Promise<string> {
|
||||
|
||||
async generateAccessToken(user: User): Promise<string> {
|
||||
const payload: JwtPayload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
workspaceId: user.workspaceId,
|
||||
type: JwtType.ACCESS,
|
||||
};
|
||||
return await this.jwtService.signAsync(payload);
|
||||
return this.jwtService.sign(payload);
|
||||
}
|
||||
|
||||
async generateRefreshToken(userId: string, workspaceId): Promise<string> {
|
||||
const payload: JwtRefreshPayload = {
|
||||
sub: userId,
|
||||
workspaceId,
|
||||
type: JwtType.REFRESH,
|
||||
};
|
||||
const expiresIn = '30d'; // todo: fix
|
||||
return this.jwtService.sign(payload, { expiresIn });
|
||||
}
|
||||
|
||||
async generateTokens(user: User): Promise<TokensDto> {
|
||||
return {
|
||||
accessToken: await this.generateJwt(user),
|
||||
refreshToken: null,
|
||||
accessToken: await this.generateAccessToken(user),
|
||||
refreshToken: await this.generateRefreshToken(user.id, user.workspaceId),
|
||||
};
|
||||
}
|
||||
|
||||
async verifyJwt(token: string) {
|
||||
return await this.jwtService.verifyAsync(token, {
|
||||
return this.jwtService.verifyAsync(token, {
|
||||
secret: this.environmentService.getJwtSecret(),
|
||||
});
|
||||
}
|
||||
|
||||
async extractTokenFromHeader(
|
||||
request: FastifyRequest,
|
||||
): Promise<string | undefined> {
|
||||
const [type, token] = request.headers.authorization?.split(' ') ?? [];
|
||||
return type === 'Bearer' ? token : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
64
apps/server/src/core/auth/strategies/jwt.strategy.ts
Normal file
64
apps/server/src/core/auth/strategies/jwt.strategy.ts
Normal file
@ -0,0 +1,64 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { EnvironmentService } from '../../../environment/environment.service';
|
||||
import { JwtPayload, JwtType } from '../dto/jwt-payload';
|
||||
import { AuthService } from '../services/auth.service';
|
||||
import { UserRepository } from '../../user/repositories/user.repository';
|
||||
import { UserService } from '../../user/user.service';
|
||||
import { WorkspaceRepository } from '../../workspace/repositories/workspace.repository';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
constructor(
|
||||
private authService: AuthService,
|
||||
private userService: UserService,
|
||||
private userRepository: UserRepository,
|
||||
private workspaceRepository: WorkspaceRepository,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: environmentService.getJwtSecret(),
|
||||
passReqToCallback: true,
|
||||
});
|
||||
}
|
||||
|
||||
async validate(req, payload: JwtPayload) {
|
||||
// CLOUD ENV
|
||||
if (this.environmentService.isCloud()) {
|
||||
if (req.raw.workspaceId && req.raw.workspaceId !== payload.workspaceId) {
|
||||
throw new BadRequestException('Workspace does not match');
|
||||
}
|
||||
}
|
||||
|
||||
if (!payload.workspaceId || payload.type !== JwtType.ACCESS) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
const workspace = await this.workspaceRepository.findById(
|
||||
payload.workspaceId,
|
||||
);
|
||||
|
||||
if (!workspace) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
const user = await this.userRepository.findOne({
|
||||
where: {
|
||||
id: payload.sub,
|
||||
workspaceId: payload.workspaceId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
return { user, workspace };
|
||||
}
|
||||
}
|
||||
@ -9,9 +9,8 @@ import {
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { Action } from '../ability.action';
|
||||
import { Workspace } from '../../workspace/entities/workspace.entity';
|
||||
import { WorkspaceUser } from '../../workspace/entities/workspace-user.entity';
|
||||
import { WorkspaceInvitation } from '../../workspace/entities/workspace-invitation.entity';
|
||||
import { Role } from '../../../helpers/types/permission';
|
||||
import { UserRole } from '../../../helpers/types/permission';
|
||||
import { Group } from '../../group/entities/group.entity';
|
||||
import { GroupUser } from '../../group/entities/group-user.entity';
|
||||
import { Attachment } from '../../attachment/entities/attachment.entity';
|
||||
@ -23,7 +22,6 @@ import { Comment } from '../../comment/entities/comment.entity';
|
||||
export type Subjects =
|
||||
| InferSubjects<
|
||||
| typeof Workspace
|
||||
| typeof WorkspaceUser
|
||||
| typeof WorkspaceInvitation
|
||||
| typeof Space
|
||||
| typeof SpaceUser
|
||||
@ -34,6 +32,7 @@ export type Subjects =
|
||||
| typeof Page
|
||||
| typeof User
|
||||
>
|
||||
| 'workspaceUser'
|
||||
| 'all';
|
||||
export type AppAbility = MongoAbility<[Action, Subjects]>;
|
||||
|
||||
@ -42,13 +41,13 @@ export default class CaslAbilityFactory {
|
||||
createForWorkspace(user: User, workspace: Workspace) {
|
||||
const { can, build } = new AbilityBuilder<AppAbility>(createMongoAbility);
|
||||
|
||||
const userRole = workspace?.workspaceUser.role;
|
||||
console.log(userRole);
|
||||
const userRole = user.role;
|
||||
|
||||
if (userRole === Role.OWNER) {
|
||||
if (userRole === UserRole.OWNER || userRole === UserRole.ADMIN) {
|
||||
// Workspace Users
|
||||
can<any>([Action.Manage], Workspace);
|
||||
can<any>([Action.Manage], WorkspaceUser);
|
||||
can<any>([Action.Manage], 'workspaceUser');
|
||||
|
||||
can<any>([Action.Manage], WorkspaceInvitation);
|
||||
|
||||
// Groups
|
||||
@ -59,8 +58,8 @@ export default class CaslAbilityFactory {
|
||||
can<any>([Action.Manage], Attachment);
|
||||
}
|
||||
|
||||
if (userRole === Role.MEMBER) {
|
||||
can<any>([Action.Read], WorkspaceUser);
|
||||
if (userRole === UserRole.MEMBER) {
|
||||
// can<any>([Action.Read], WorkspaceUser);
|
||||
|
||||
// Groups
|
||||
can<any>([Action.Read], Group);
|
||||
|
||||
@ -21,8 +21,8 @@ export class PoliciesGuard implements CanActivate {
|
||||
) || [];
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user = request['user'].user;
|
||||
const workspace = request['user'].workspace;
|
||||
const user = request.user.user;
|
||||
const workspace = request.user.workspace;
|
||||
|
||||
const ability = this.caslAbilityFactory.createForWorkspace(user, workspace);
|
||||
|
||||
|
||||
@ -9,16 +9,15 @@ import {
|
||||
import { CommentService } from './comment.service';
|
||||
import { CreateCommentDto } from './dto/create-comment.dto';
|
||||
import { UpdateCommentDto } from './dto/update-comment.dto';
|
||||
import { JwtGuard } from '../auth/guards/jwt.guard';
|
||||
import { CommentsInput, SingleCommentInput } from './dto/comments.input';
|
||||
import { ResolveCommentDto } from './dto/resolve-comment.dto';
|
||||
import { WorkspaceService } from '../workspace/services/workspace.service';
|
||||
import { AuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { CurrentWorkspace } from '../../decorators/current-workspace.decorator';
|
||||
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
|
||||
import { Workspace } from '../workspace/entities/workspace.entity';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('comments')
|
||||
export class CommentController {
|
||||
constructor(private readonly commentService: CommentService) {}
|
||||
@ -28,7 +27,7 @@ export class CommentController {
|
||||
async create(
|
||||
@Body() createCommentDto: CreateCommentDto,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.commentService.create(user.id, workspace.id, createCommentDto);
|
||||
}
|
||||
@ -40,7 +39,7 @@ export class CommentController {
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('view')
|
||||
@Post('info')
|
||||
findOne(@Body() input: SingleCommentInput) {
|
||||
return this.commentService.findWithCreator(input.id);
|
||||
}
|
||||
|
||||
@ -3,12 +3,11 @@ import { CommentService } from './comment.service';
|
||||
import { CommentController } from './comment.controller';
|
||||
import { CommentRepository } from './repositories/comment.repository';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { Comment } from './entities/comment.entity';
|
||||
import { PageModule } from '../page/page.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Comment]), AuthModule, PageModule],
|
||||
imports: [TypeOrmModule.forFeature([Comment]), PageModule],
|
||||
controllers: [CommentController],
|
||||
providers: [CommentService, CommentRepository],
|
||||
exports: [CommentService, CommentRepository],
|
||||
|
||||
@ -1,9 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import {
|
||||
MiddlewareConsumer,
|
||||
Module,
|
||||
NestModule,
|
||||
RequestMethod,
|
||||
} from '@nestjs/common';
|
||||
import { UserModule } from './user/user.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { WorkspaceModule } from './workspace/workspace.module';
|
||||
import { PageModule } from './page/page.module';
|
||||
import { StorageModule } from './storage/storage.module';
|
||||
import { StorageModule } from '../integrations/storage/storage.module';
|
||||
import { AttachmentModule } from './attachment/attachment.module';
|
||||
import { EnvironmentModule } from '../environment/environment.module';
|
||||
import { CommentModule } from './comment/comment.module';
|
||||
@ -11,6 +16,7 @@ import { SearchModule } from './search/search.module';
|
||||
import { SpaceModule } from './space/space.module';
|
||||
import { GroupModule } from './group/group.module';
|
||||
import { CaslModule } from './casl/casl.module';
|
||||
import { DomainMiddleware } from '../middlewares/domain.middleware';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@ -29,4 +35,11 @@ import { CaslModule } from './casl/casl.module';
|
||||
CaslModule,
|
||||
],
|
||||
})
|
||||
export class CoreModule {}
|
||||
export class CoreModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer
|
||||
.apply(DomainMiddleware)
|
||||
.exclude({ path: 'auth/setup', method: RequestMethod.POST })
|
||||
.forRoutes('*');
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,7 +20,7 @@ export class GroupUser {
|
||||
@Column()
|
||||
userId: string;
|
||||
|
||||
@ManyToOne(() => User, (user) => user.workspaceUsers, {
|
||||
@ManyToOne(() => User, (user) => user.groups, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'userId' })
|
||||
|
||||
@ -8,9 +8,8 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { GroupService } from './services/group.service';
|
||||
import { CreateGroupDto } from './dto/create-group.dto';
|
||||
import { JwtGuard } from '../auth/guards/jwt.guard';
|
||||
import { AuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { CurrentWorkspace } from '../../decorators/current-workspace.decorator';
|
||||
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { Workspace } from '../workspace/entities/workspace.entity';
|
||||
import { GroupUserService } from './services/group-user.service';
|
||||
@ -25,8 +24,9 @@ import { GroupUser } from './entities/group-user.entity';
|
||||
import { PoliciesGuard } from '../casl/guards/policies.guard';
|
||||
import { CheckPolicies } from '../casl/decorators/policies.decorator';
|
||||
import { AppAbility } from '../casl/abilities/casl-ability.factory';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('groups')
|
||||
export class GroupController {
|
||||
constructor(
|
||||
@ -39,21 +39,21 @@ export class GroupController {
|
||||
getWorkspaceGroups(
|
||||
@Body() pagination: PaginationOptions,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.groupService.getGroupsInWorkspace(workspace.id, pagination);
|
||||
return this.groupService.getWorkspaceGroups(workspace.id, pagination);
|
||||
}
|
||||
|
||||
@UseGuards(PoliciesGuard)
|
||||
@CheckPolicies((ability: AppAbility) => ability.can(Action.Read, Group))
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('/details')
|
||||
@Post('/info')
|
||||
getGroup(
|
||||
@Body() groupIdDto: GroupIdDto,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.groupService.getGroup(groupIdDto.groupId, workspace.id);
|
||||
return this.groupService.getGroupInfo(groupIdDto.groupId, workspace.id);
|
||||
}
|
||||
|
||||
@UseGuards(PoliciesGuard)
|
||||
@ -63,7 +63,7 @@ export class GroupController {
|
||||
createGroup(
|
||||
@Body() createGroupDto: CreateGroupDto,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.groupService.createGroup(user, workspace.id, createGroupDto);
|
||||
}
|
||||
@ -75,7 +75,7 @@ export class GroupController {
|
||||
updateGroup(
|
||||
@Body() updateGroupDto: UpdateGroupDto,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.groupService.updateGroup(workspace.id, updateGroupDto);
|
||||
}
|
||||
@ -87,7 +87,7 @@ export class GroupController {
|
||||
getGroupMembers(
|
||||
@Body() groupIdDto: GroupIdDto,
|
||||
@Body() pagination: PaginationOptions,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.groupUserService.getGroupUsers(
|
||||
groupIdDto.groupId,
|
||||
@ -103,7 +103,7 @@ export class GroupController {
|
||||
addGroupMember(
|
||||
@Body() addGroupUserDto: AddGroupUserDto,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.groupUserService.addUserToGroup(
|
||||
addGroupUserDto.userId,
|
||||
@ -134,7 +134,7 @@ export class GroupController {
|
||||
deleteGroup(
|
||||
@Body() groupIdDto: GroupIdDto,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.groupService.deleteGroup(groupIdDto.groupId, workspace.id);
|
||||
}
|
||||
|
||||
@ -2,7 +2,6 @@ import { Module } from '@nestjs/common';
|
||||
import { GroupService } from './services/group.service';
|
||||
import { GroupController } from './group.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { Group } from './entities/group.entity';
|
||||
import { GroupUser } from './entities/group-user.entity';
|
||||
import { GroupRepository } from './respositories/group.repository';
|
||||
@ -10,7 +9,7 @@ import { GroupUserRepository } from './respositories/group-user.repository';
|
||||
import { GroupUserService } from './services/group-user.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Group, GroupUser]), AuthModule],
|
||||
imports: [TypeOrmModule.forFeature([Group, GroupUser])],
|
||||
controllers: [GroupController],
|
||||
providers: [
|
||||
GroupService,
|
||||
|
||||
@ -6,7 +6,6 @@ import {
|
||||
import { DataSource, EntityManager } from 'typeorm';
|
||||
import { GroupUserRepository } from '../respositories/group-user.repository';
|
||||
import { PaginationOptions } from '../../../helpers/pagination/pagination-options';
|
||||
import { WorkspaceUser } from '../../workspace/entities/workspace-user.entity';
|
||||
import { transactionWrapper } from '../../../helpers/db.helper';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { GroupUser } from '../entities/group-user.entity';
|
||||
@ -55,9 +54,10 @@ export class GroupUserService {
|
||||
groupId: string,
|
||||
workspaceId: string,
|
||||
manager?: EntityManager,
|
||||
): Promise<WorkspaceUser> {
|
||||
): Promise<any> {
|
||||
let addedUser;
|
||||
|
||||
/*
|
||||
await transactionWrapper(
|
||||
async (manager) => {
|
||||
const group = await manager.findOneBy(Group, {
|
||||
@ -106,7 +106,7 @@ export class GroupUserService {
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
|
||||
*/
|
||||
return addedUser;
|
||||
}
|
||||
|
||||
|
||||
@ -49,7 +49,7 @@ export class GroupService {
|
||||
return await this.groupRepository.save(group);
|
||||
}
|
||||
|
||||
async getGroup(groupId: string, workspaceId: string): Promise<Group> {
|
||||
async getGroupInfo(groupId: string, workspaceId: string): Promise<Group> {
|
||||
const group = await this.groupRepository
|
||||
.createQueryBuilder('group')
|
||||
.where('group.id = :groupId', { groupId })
|
||||
@ -68,11 +68,11 @@ export class GroupService {
|
||||
return group;
|
||||
}
|
||||
|
||||
async getGroupsInWorkspace(
|
||||
async getWorkspaceGroups(
|
||||
workspaceId: string,
|
||||
paginationOptions: PaginationOptions,
|
||||
): Promise<PaginatedResult<Group>> {
|
||||
const [groupsInWorkspace, count] = await this.groupRepository
|
||||
const [groups, count] = await this.groupRepository
|
||||
.createQueryBuilder('group')
|
||||
.where('group.workspaceId = :workspaceId', { workspaceId })
|
||||
.loadRelationCountAndMap(
|
||||
@ -86,7 +86,7 @@ export class GroupService {
|
||||
|
||||
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
|
||||
|
||||
return new PaginatedResult(groupsInWorkspace, paginationMeta);
|
||||
return new PaginatedResult(groups, paginationMeta);
|
||||
}
|
||||
|
||||
async deleteGroup(groupId: string, workspaceId: string): Promise<void> {
|
||||
|
||||
@ -9,7 +9,6 @@ import {
|
||||
import { PageService } from './services/page.service';
|
||||
import { CreatePageDto } from './dto/create-page.dto';
|
||||
import { UpdatePageDto } from './dto/update-page.dto';
|
||||
import { JwtGuard } from '../auth/guards/jwt.guard';
|
||||
import { MovePageDto } from './dto/move-page.dto';
|
||||
import { PageDetailsDto } from './dto/page-details.dto';
|
||||
import { DeletePageDto } from './dto/delete-page.dto';
|
||||
@ -19,10 +18,11 @@ import { HistoryDetailsDto } from './dto/history-details.dto';
|
||||
import { PageHistoryDto } from './dto/page-history.dto';
|
||||
import { AuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { CurrentWorkspace } from '../../decorators/current-workspace.decorator';
|
||||
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
|
||||
import { Workspace } from '../workspace/entities/workspace.entity';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('pages')
|
||||
export class PageController {
|
||||
constructor(
|
||||
@ -32,7 +32,7 @@ export class PageController {
|
||||
) {}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('/details')
|
||||
@Post('/info')
|
||||
async getPage(@Body() input: PageDetailsDto) {
|
||||
return this.pageService.findOne(input.id);
|
||||
}
|
||||
@ -42,7 +42,7 @@ export class PageController {
|
||||
async create(
|
||||
@Body() createPageDto: CreatePageDto,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.pageService.create(user.id, workspace.id, createPageDto);
|
||||
}
|
||||
|
||||
@ -4,7 +4,6 @@ import { PageController } from './page.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Page } from './entities/page.entity';
|
||||
import { PageRepository } from './repositories/page.repository';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { WorkspaceModule } from '../workspace/workspace.module';
|
||||
import { PageOrderingService } from './services/page-ordering.service';
|
||||
import { PageOrdering } from './entities/page-ordering.entity';
|
||||
@ -15,7 +14,6 @@ import { PageHistoryRepository } from './repositories/page-history.repository';
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Page, PageOrdering, PageHistory]),
|
||||
AuthModule,
|
||||
WorkspaceModule,
|
||||
],
|
||||
controllers: [PageController],
|
||||
|
||||
@ -7,13 +7,13 @@ import {
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtGuard } from '../auth/guards/jwt.guard';
|
||||
import { SearchService } from './search.service';
|
||||
import { SearchDTO } from './dto/search.dto';
|
||||
import { CurrentWorkspace } from '../../decorators/current-workspace.decorator';
|
||||
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
|
||||
import { Workspace } from '../workspace/entities/workspace.entity';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('search')
|
||||
export class SearchController {
|
||||
constructor(private readonly searchService: SearchService) {}
|
||||
@ -23,7 +23,7 @@ export class SearchController {
|
||||
async pageSearch(
|
||||
@Query('type') type: string,
|
||||
@Body() searchDto: SearchDTO,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
if (!type || type === 'page') {
|
||||
return this.searchService.searchPage(
|
||||
|
||||
@ -1,11 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SearchController } from './search.controller';
|
||||
import { SearchService } from './search.service';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { PageModule } from '../page/page.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, PageModule],
|
||||
imports: [PageModule],
|
||||
controllers: [SearchController],
|
||||
providers: [SearchService],
|
||||
})
|
||||
|
||||
@ -9,4 +9,8 @@ export class CreateSpaceDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
8
apps/server/src/core/space/dto/space-id.dto.ts
Normal file
8
apps/server/src/core/space/dto/space-id.dto.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { IsNotEmpty, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
export class SpaceIdDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@IsUUID()
|
||||
spaceId: string;
|
||||
}
|
||||
@ -20,7 +20,7 @@ export class SpaceUser {
|
||||
@Column()
|
||||
userId: string;
|
||||
|
||||
@ManyToOne(() => User, (user) => user.spaceUsers, {
|
||||
@ManyToOne(() => User, (user) => user.spaces, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'userId' })
|
||||
@ -32,7 +32,6 @@ export class SpaceUser {
|
||||
@ManyToOne(() => Space, (space) => space.spaceUsers, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'spaceId' })
|
||||
space: Space;
|
||||
|
||||
@Column({ length: 100, nullable: true })
|
||||
|
||||
@ -6,14 +6,17 @@ import {
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
Unique,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { Workspace } from '../../workspace/entities/workspace.entity';
|
||||
import { SpaceUser } from './space-user.entity';
|
||||
import { Page } from '../../page/entities/page.entity';
|
||||
import { SpacePrivacy, SpaceRole } from '../../../helpers/types/permission';
|
||||
|
||||
@Entity('spaces')
|
||||
@Unique(['slug', 'workspaceId'])
|
||||
export class Space {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
@ -24,11 +27,17 @@ export class Space {
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
slug: string;
|
||||
|
||||
@Column({ length: 255, nullable: true })
|
||||
icon: string;
|
||||
|
||||
@Column({ length: 255, nullable: true, unique: true })
|
||||
hostname: string;
|
||||
@Column({ length: 100, default: SpacePrivacy.OPEN })
|
||||
privacy: string;
|
||||
|
||||
@Column({ length: 100, default: SpaceRole.WRITER })
|
||||
defaultRole: string;
|
||||
|
||||
@Column()
|
||||
creatorId: string;
|
||||
@ -46,7 +55,7 @@ export class Space {
|
||||
@JoinColumn({ name: 'workspaceId' })
|
||||
workspace: Workspace;
|
||||
|
||||
@OneToMany(() => SpaceUser, (workspaceUser) => workspaceUser.space)
|
||||
@OneToMany(() => SpaceUser, (spaceUser) => spaceUser.space)
|
||||
spaceUsers: SpaceUser[];
|
||||
|
||||
@OneToMany(() => Page, (page) => page.space)
|
||||
|
||||
@ -8,7 +8,11 @@ export class SpaceRepository extends Repository<Space> {
|
||||
super(Space, dataSource.createEntityManager());
|
||||
}
|
||||
|
||||
async findById(spaceId: string) {
|
||||
return this.findOneBy({ id: spaceId });
|
||||
async findById(spaceId: string, workspaceId: string): Promise<Space> {
|
||||
const queryBuilder = this.dataSource.createQueryBuilder(Space, 'space');
|
||||
return await queryBuilder
|
||||
.where('space.id = :id', { id: spaceId })
|
||||
.andWhere('space.workspaceId = :workspaceId', { workspaceId })
|
||||
.getOne();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,29 +1,72 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtGuard } from '../auth/guards/jwt.guard';
|
||||
import { SpaceService } from './space.service';
|
||||
import { AuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { CurrentWorkspace } from '../../decorators/current-workspace.decorator';
|
||||
import { AuthWorkspace } from '../../decorators/auth-workspace.decorator';
|
||||
import { Workspace } from '../workspace/entities/workspace.entity';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
import { SpaceIdDto } from './dto/space-id.dto';
|
||||
import { PaginationOptions } from '../../helpers/pagination/pagination-options';
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('spaces')
|
||||
export class SpaceController {
|
||||
constructor(private readonly spaceService: SpaceService) {}
|
||||
|
||||
// get all spaces user is a member of
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('/')
|
||||
async getUserSpaces(
|
||||
async getWorkspaceSpaces(
|
||||
@Body()
|
||||
pagination: PaginationOptions,
|
||||
@AuthUser() user: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.spaceService.getUserSpacesInWorkspace(user.id, workspace.id);
|
||||
// TODO: only show spaces user can see. e.g open and private with user being a member
|
||||
return this.spaceService.getWorkspaceSpaces(workspace.id, pagination);
|
||||
}
|
||||
|
||||
// get all spaces user is a member of
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('user')
|
||||
async getUserSpaces(
|
||||
@Body()
|
||||
pagination: PaginationOptions,
|
||||
@AuthUser() user: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.spaceService.getUserSpaces(user.id, workspace.id, pagination);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('info')
|
||||
async getSpaceInfo(
|
||||
@Body() spaceIdDto: SpaceIdDto,
|
||||
@AuthUser() user: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.spaceService.getSpaceInfo(spaceIdDto.spaceId, workspace.id);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('members')
|
||||
async getSpaceMembers(
|
||||
@Body() spaceIdDto: SpaceIdDto,
|
||||
@Body()
|
||||
pagination: PaginationOptions,
|
||||
@AuthUser() user: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.spaceService.getSpaceUsers(
|
||||
spaceIdDto.spaceId,
|
||||
workspace.id,
|
||||
pagination,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,13 +3,12 @@ import { SpaceService } from './space.service';
|
||||
import { SpaceController } from './space.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Space } from './entities/space.entity';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { SpaceUser } from './entities/space-user.entity';
|
||||
import { SpaceRepository } from './repositories/space.repository';
|
||||
import { SpaceUserRepository } from './repositories/space-user.repository';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Space, SpaceUser]), AuthModule],
|
||||
imports: [TypeOrmModule.forFeature([Space, SpaceUser])],
|
||||
controllers: [SpaceController],
|
||||
providers: [SpaceService, SpaceRepository, SpaceUserRepository],
|
||||
exports: [SpaceService, SpaceRepository, SpaceUserRepository],
|
||||
|
||||
@ -5,14 +5,15 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { CreateSpaceDto } from './dto/create-space.dto';
|
||||
import { Space } from './entities/space.entity';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { SpaceRepository } from './repositories/space.repository';
|
||||
import { SpaceUserRepository } from './repositories/space-user.repository';
|
||||
import { SpaceUser } from './entities/space-user.entity';
|
||||
import { transactionWrapper } from '../../helpers/db.helper';
|
||||
import { DataSource, EntityManager } from 'typeorm';
|
||||
import { WorkspaceUser } from '../workspace/entities/workspace-user.entity';
|
||||
import { User } from '../user/entities/user.entity';
|
||||
import { PaginationOptions } from '../../helpers/pagination/pagination-options';
|
||||
import { PaginationMetaDto } from '../../helpers/pagination/pagination-meta-dto';
|
||||
import { PaginatedResult } from '../../helpers/pagination/paginated-result';
|
||||
|
||||
@Injectable()
|
||||
export class SpaceService {
|
||||
@ -24,33 +25,26 @@ export class SpaceService {
|
||||
|
||||
async create(
|
||||
userId: string,
|
||||
workspaceId,
|
||||
workspaceId: string,
|
||||
createSpaceDto?: CreateSpaceDto,
|
||||
manager?: EntityManager,
|
||||
) {
|
||||
let space: Space;
|
||||
|
||||
await transactionWrapper(
|
||||
): Promise<Space> {
|
||||
return await transactionWrapper(
|
||||
async (manager: EntityManager) => {
|
||||
if (createSpaceDto) {
|
||||
space = plainToInstance(Space, createSpaceDto);
|
||||
} else {
|
||||
space = new Space();
|
||||
}
|
||||
|
||||
const space = new Space();
|
||||
space.name = createSpaceDto.name ?? 'untitled space ';
|
||||
space.description = createSpaceDto.description ?? '';
|
||||
space.creatorId = userId;
|
||||
space.workspaceId = workspaceId;
|
||||
|
||||
space.name = createSpaceDto?.name ?? 'untitled space';
|
||||
space.description = createSpaceDto?.description ?? null;
|
||||
space.slug = space.name.toLowerCase(); // TODO: fix
|
||||
|
||||
space = await manager.save(space);
|
||||
await manager.save(space);
|
||||
return space;
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
|
||||
return space;
|
||||
}
|
||||
|
||||
async addUserToSpace(
|
||||
@ -60,27 +54,15 @@ export class SpaceService {
|
||||
workspaceId,
|
||||
manager?: EntityManager,
|
||||
): Promise<SpaceUser> {
|
||||
let addedUser: SpaceUser;
|
||||
|
||||
await transactionWrapper(
|
||||
return await transactionWrapper(
|
||||
async (manager: EntityManager) => {
|
||||
const userExists = await manager.exists(User, {
|
||||
where: { id: userId },
|
||||
where: { id: userId, workspaceId },
|
||||
});
|
||||
if (!userExists) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
// only workspace users can be added to workspace spaces
|
||||
const workspaceUser = await manager.findOneBy(WorkspaceUser, {
|
||||
userId: userId,
|
||||
workspaceId: workspaceId,
|
||||
});
|
||||
|
||||
if (!workspaceUser) {
|
||||
throw new NotFoundException('User is not a member of this workspace');
|
||||
}
|
||||
|
||||
const existingSpaceUser = await manager.findOneBy(SpaceUser, {
|
||||
userId: userId,
|
||||
spaceId: spaceId,
|
||||
@ -94,27 +76,106 @@ export class SpaceService {
|
||||
spaceUser.userId = userId;
|
||||
spaceUser.spaceId = spaceId;
|
||||
spaceUser.role = role;
|
||||
await manager.save(spaceUser);
|
||||
|
||||
addedUser = await manager.save(spaceUser);
|
||||
return spaceUser;
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
|
||||
return addedUser;
|
||||
}
|
||||
|
||||
async getUserSpacesInWorkspace(userId: string, workspaceId: string) {
|
||||
const spaces = await this.spaceUserRepository.find({
|
||||
relations: ['space'],
|
||||
async getSpaceInfo(spaceId: string, workspaceId: string): Promise<Space> {
|
||||
const space = await this.spaceRepository
|
||||
.createQueryBuilder('space')
|
||||
.where('space.id = :spaceId', { spaceId })
|
||||
.andWhere('space.workspaceId = :workspaceId', { workspaceId })
|
||||
.loadRelationCountAndMap(
|
||||
'space.userCount',
|
||||
'space.spaceUsers',
|
||||
'spaceUsers',
|
||||
)
|
||||
.getOne();
|
||||
|
||||
if (!space) {
|
||||
throw new NotFoundException('Space not found');
|
||||
}
|
||||
|
||||
return space;
|
||||
}
|
||||
|
||||
async getWorkspaceSpaces(
|
||||
workspaceId: string,
|
||||
paginationOptions: PaginationOptions,
|
||||
): Promise<PaginatedResult<Space>> {
|
||||
const [spaces, count] = await this.spaceRepository
|
||||
.createQueryBuilder('space')
|
||||
.where('space.workspaceId = :workspaceId', { workspaceId })
|
||||
.loadRelationCountAndMap(
|
||||
'space.userCount',
|
||||
'space.spaceUsers',
|
||||
'spaceUsers',
|
||||
)
|
||||
.take(paginationOptions.limit)
|
||||
.skip(paginationOptions.skip)
|
||||
.getManyAndCount();
|
||||
|
||||
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
|
||||
|
||||
return new PaginatedResult(spaces, paginationMeta);
|
||||
}
|
||||
|
||||
async getUserSpaces(
|
||||
userId: string,
|
||||
workspaceId: string,
|
||||
paginationOptions: PaginationOptions,
|
||||
) {
|
||||
const [userSpaces, count] = await this.spaceUserRepository
|
||||
.createQueryBuilder('spaceUser')
|
||||
.leftJoinAndSelect('spaceUser.space', 'space')
|
||||
.where('spaceUser.userId = :userId', { userId })
|
||||
.andWhere('space.workspaceId = :workspaceId', { workspaceId })
|
||||
.loadRelationCountAndMap(
|
||||
'space.userCount',
|
||||
'space.spaceUsers',
|
||||
'spaceUsers',
|
||||
)
|
||||
.take(paginationOptions.limit)
|
||||
.skip(paginationOptions.skip)
|
||||
.getManyAndCount();
|
||||
|
||||
const spaces = userSpaces.map((userSpace) => userSpace.space);
|
||||
|
||||
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
|
||||
return new PaginatedResult(spaces, paginationMeta);
|
||||
}
|
||||
|
||||
async getSpaceUsers(
|
||||
spaceId: string,
|
||||
workspaceId: string,
|
||||
paginationOptions: PaginationOptions,
|
||||
) {
|
||||
const [spaceUsers, count] = await this.spaceUserRepository.findAndCount({
|
||||
relations: ['user'],
|
||||
where: {
|
||||
userId: userId,
|
||||
space: {
|
||||
workspaceId: workspaceId,
|
||||
id: spaceId,
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
take: paginationOptions.limit,
|
||||
skip: paginationOptions.skip,
|
||||
});
|
||||
|
||||
return spaces.map((userSpace: SpaceUser) => userSpace.space);
|
||||
const users = spaceUsers.map((spaceUser) => {
|
||||
delete spaceUser.user.password;
|
||||
return {
|
||||
...spaceUser.user,
|
||||
spaceRole: spaceUser.role,
|
||||
};
|
||||
});
|
||||
|
||||
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
|
||||
return new PaginatedResult(users, paginationMeta);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,2 +0,0 @@
|
||||
export const STORAGE_DRIVER_TOKEN = 'STORAGE_DRIVER_TOKEN';
|
||||
export const STORAGE_CONFIG_TOKEN = 'STORAGE_CONFIG_TOKEN';
|
||||
@ -1,2 +0,0 @@
|
||||
export { LocalDriver } from './local.driver';
|
||||
export { S3Driver } from './s3.driver';
|
||||
@ -1,71 +0,0 @@
|
||||
import {
|
||||
StorageDriver,
|
||||
LocalStorageConfig,
|
||||
StorageOption,
|
||||
} from '../interfaces';
|
||||
import { join } from 'path';
|
||||
import * as fs from 'fs-extra';
|
||||
|
||||
export class LocalDriver implements StorageDriver {
|
||||
private readonly config: LocalStorageConfig;
|
||||
|
||||
constructor(config: LocalStorageConfig) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
private _fullPath(filePath: string): string {
|
||||
return join(this.config.storagePath, filePath);
|
||||
}
|
||||
|
||||
async upload(filePath: string, file: Buffer): Promise<void> {
|
||||
try {
|
||||
await fs.outputFile(this._fullPath(filePath), file);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to upload file: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async read(filePath: string): Promise<Buffer> {
|
||||
try {
|
||||
return await fs.readFile(this._fullPath(filePath));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to read file: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async exists(filePath: string): Promise<boolean> {
|
||||
try {
|
||||
return await fs.pathExists(this._fullPath(filePath));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to check file existence: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getSignedUrl(filePath: string, expireIn: number): Promise<string> {
|
||||
throw new Error('Signed URLs are not supported for local storage.');
|
||||
}
|
||||
|
||||
getUrl(filePath: string): string {
|
||||
return this._fullPath(filePath);
|
||||
}
|
||||
|
||||
async delete(filePath: string): Promise<void> {
|
||||
try {
|
||||
await fs.remove(this._fullPath(filePath));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to delete file: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
getDriver(): typeof fs {
|
||||
return fs;
|
||||
}
|
||||
|
||||
getDriverName(): string {
|
||||
return StorageOption.LOCAL;
|
||||
}
|
||||
|
||||
getConfig(): Record<string, any> {
|
||||
return this.config;
|
||||
}
|
||||
}
|
||||
@ -1,115 +0,0 @@
|
||||
import { S3StorageConfig, StorageDriver, StorageOption } from '../interfaces';
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
HeadObjectCommand,
|
||||
NoSuchKey,
|
||||
PutObjectCommand,
|
||||
S3Client,
|
||||
} from '@aws-sdk/client-s3';
|
||||
import { streamToBuffer } from '../storage.utils';
|
||||
import { Readable } from 'stream';
|
||||
import * as mime from 'mime-types';
|
||||
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
||||
|
||||
export class S3Driver implements StorageDriver {
|
||||
private readonly s3Client: S3Client;
|
||||
private readonly config: S3StorageConfig;
|
||||
|
||||
constructor(config: S3StorageConfig) {
|
||||
this.config = config;
|
||||
this.s3Client = new S3Client(config as any);
|
||||
}
|
||||
|
||||
async upload(filePath: string, file: Buffer): Promise<void> {
|
||||
try {
|
||||
const contentType =
|
||||
mime.contentType(filePath) || 'application/octet-stream';
|
||||
|
||||
const command = new PutObjectCommand({
|
||||
Bucket: this.config.bucket,
|
||||
Key: filePath,
|
||||
Body: file,
|
||||
ContentType: contentType,
|
||||
// ACL: "public-read",
|
||||
});
|
||||
|
||||
await this.s3Client.send(command);
|
||||
// we can get the path from location
|
||||
|
||||
console.log(`File uploaded successfully: ${filePath}`);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to upload file: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async read(filePath: string): Promise<Buffer> {
|
||||
try {
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: this.config.bucket,
|
||||
Key: filePath,
|
||||
});
|
||||
|
||||
const response = await this.s3Client.send(command);
|
||||
|
||||
return streamToBuffer(response.Body as Readable);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to read file from S3: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async exists(filePath: string): Promise<boolean> {
|
||||
try {
|
||||
const command = new HeadObjectCommand({
|
||||
Bucket: this.config.bucket,
|
||||
Key: filePath,
|
||||
});
|
||||
|
||||
await this.s3Client.send(command);
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (err instanceof NoSuchKey) {
|
||||
return false;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
getUrl(filePath: string): string {
|
||||
return `${this.config.endpoint}/${this.config.bucket}/${filePath}`;
|
||||
}
|
||||
|
||||
async getSignedUrl(filePath: string, expiresIn: number): Promise<string> {
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: this.config.bucket,
|
||||
Key: filePath,
|
||||
});
|
||||
return await getSignedUrl(this.s3Client, command, { expiresIn });
|
||||
}
|
||||
|
||||
async delete(filePath: string): Promise<void> {
|
||||
try {
|
||||
const command = new DeleteObjectCommand({
|
||||
Bucket: this.config.bucket,
|
||||
Key: filePath,
|
||||
});
|
||||
|
||||
await this.s3Client.send(command);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Error deleting file ${filePath} from S3. ${err.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
getDriver(): S3Client {
|
||||
return this.s3Client;
|
||||
}
|
||||
|
||||
getDriverName(): string {
|
||||
return StorageOption.S3;
|
||||
}
|
||||
|
||||
getConfig(): Record<string, any> {
|
||||
return this.config;
|
||||
}
|
||||
}
|
||||
@ -1,2 +0,0 @@
|
||||
export * from './storage-driver.interface';
|
||||
export * from './storage.interface';
|
||||
@ -1,19 +0,0 @@
|
||||
export interface StorageDriver {
|
||||
upload(filePath: string, file: Buffer): Promise<void>;
|
||||
|
||||
read(filePath: string): Promise<Buffer>;
|
||||
|
||||
exists(filePath: string): Promise<boolean>;
|
||||
|
||||
getUrl(filePath: string): string;
|
||||
|
||||
getSignedUrl(filePath: string, expireIn: number): Promise<string>;
|
||||
|
||||
delete(filePath: string): Promise<void>;
|
||||
|
||||
getDriver(): any;
|
||||
|
||||
getDriverName(): string;
|
||||
|
||||
getConfig(): Record<string, any>;
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
import { S3ClientConfig } from '@aws-sdk/client-s3';
|
||||
|
||||
export enum StorageOption {
|
||||
LOCAL = 'local',
|
||||
S3 = 's3',
|
||||
}
|
||||
|
||||
export type StorageConfig =
|
||||
| { driver: StorageOption.LOCAL; config: LocalStorageConfig }
|
||||
| { driver: StorageOption.S3; config: S3StorageConfig };
|
||||
|
||||
export interface LocalStorageConfig {
|
||||
storagePath: string;
|
||||
}
|
||||
|
||||
export interface S3StorageConfig
|
||||
extends Omit<S3ClientConfig, 'endpoint' | 'bucket'> {
|
||||
endpoint: string; // Enforce endpoint
|
||||
bucket: string; // Enforce bucket
|
||||
baseUrl?: string; // Optional CDN URL for assets
|
||||
}
|
||||
|
||||
export interface StorageOptions {
|
||||
disk: StorageConfig;
|
||||
}
|
||||
|
||||
export interface StorageOptionsFactory {
|
||||
createStorageOptions(): Promise<StorageConfig> | StorageConfig;
|
||||
}
|
||||
|
||||
export interface StorageModuleOptions {
|
||||
imports?: any[];
|
||||
}
|
||||
@ -1,66 +0,0 @@
|
||||
import {
|
||||
STORAGE_CONFIG_TOKEN,
|
||||
STORAGE_DRIVER_TOKEN,
|
||||
} from '../constants/storage.constants';
|
||||
import { EnvironmentService } from '../../../environment/environment.service';
|
||||
import {
|
||||
LocalStorageConfig,
|
||||
S3StorageConfig,
|
||||
StorageConfig,
|
||||
StorageDriver,
|
||||
StorageOption,
|
||||
} from '../interfaces';
|
||||
import { LocalDriver, S3Driver } from '../drivers';
|
||||
|
||||
function createStorageDriver(disk: StorageConfig): StorageDriver {
|
||||
switch (disk.driver) {
|
||||
case StorageOption.LOCAL:
|
||||
return new LocalDriver(disk.config as LocalStorageConfig);
|
||||
case StorageOption.S3:
|
||||
return new S3Driver(disk.config as S3StorageConfig);
|
||||
default:
|
||||
throw new Error(`Unknown storage driver`);
|
||||
}
|
||||
}
|
||||
|
||||
export const storageDriverConfigProvider = {
|
||||
provide: STORAGE_CONFIG_TOKEN,
|
||||
useFactory: async (environmentService: EnvironmentService) => {
|
||||
const driver = environmentService.getStorageDriver();
|
||||
|
||||
if (driver === StorageOption.LOCAL) {
|
||||
return {
|
||||
driver,
|
||||
config: {
|
||||
storagePath:
|
||||
process.cwd() + '/' + environmentService.getLocalStoragePath(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (driver === StorageOption.S3) {
|
||||
return {
|
||||
driver,
|
||||
config: {
|
||||
region: environmentService.getAwsS3Region(),
|
||||
endpoint: environmentService.getAwsS3Endpoint(),
|
||||
bucket: environmentService.getAwsS3Bucket(),
|
||||
credentials: {
|
||||
accessKeyId: environmentService.getAwsS3AccessKeyId(),
|
||||
secretAccessKey: environmentService.getAwsS3SecretAccessKey(),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(`Unknown storage driver: ${driver}`);
|
||||
},
|
||||
|
||||
inject: [EnvironmentService],
|
||||
};
|
||||
|
||||
export const storageDriverProvider = {
|
||||
provide: STORAGE_DRIVER_TOKEN,
|
||||
useFactory: (config) => createStorageDriver(config),
|
||||
inject: [STORAGE_CONFIG_TOKEN],
|
||||
};
|
||||
@ -1,24 +0,0 @@
|
||||
import { DynamicModule, Global, Module } from '@nestjs/common';
|
||||
import { StorageModuleOptions } from './interfaces';
|
||||
import { StorageService } from './storage.service';
|
||||
import {
|
||||
storageDriverConfigProvider,
|
||||
storageDriverProvider,
|
||||
} from './providers/storage.provider';
|
||||
|
||||
@Global()
|
||||
@Module({})
|
||||
export class StorageModule {
|
||||
static forRootAsync(options: StorageModuleOptions): DynamicModule {
|
||||
return {
|
||||
module: StorageModule,
|
||||
imports: options.imports || [],
|
||||
providers: [
|
||||
storageDriverConfigProvider,
|
||||
storageDriverProvider,
|
||||
StorageService,
|
||||
],
|
||||
exports: [StorageService],
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -1,18 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { StorageService } from './storage.service';
|
||||
|
||||
describe('StorageService', () => {
|
||||
let service: StorageService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [StorageService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<StorageService>(StorageService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@ -1,34 +0,0 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { STORAGE_DRIVER_TOKEN } from './constants/storage.constants';
|
||||
import { StorageDriver } from './interfaces';
|
||||
|
||||
@Injectable()
|
||||
export class StorageService {
|
||||
constructor(
|
||||
@Inject(STORAGE_DRIVER_TOKEN) private storageDriver: StorageDriver,
|
||||
) {}
|
||||
|
||||
async upload(filePath: string, fileContent: Buffer | any) {
|
||||
await this.storageDriver.upload(filePath, fileContent);
|
||||
}
|
||||
|
||||
async read(filePath: string): Promise<Buffer> {
|
||||
return this.storageDriver.read(filePath);
|
||||
}
|
||||
|
||||
async exists(filePath: string): Promise<boolean> {
|
||||
return this.storageDriver.exists(filePath);
|
||||
}
|
||||
|
||||
async signedUrl(path: string, expireIn: number): Promise<string> {
|
||||
return this.storageDriver.getSignedUrl(path, expireIn);
|
||||
}
|
||||
|
||||
url(filePath: string): string {
|
||||
return this.storageDriver.getUrl(filePath);
|
||||
}
|
||||
|
||||
async delete(filePath: string): Promise<void> {
|
||||
await this.storageDriver.delete(filePath);
|
||||
}
|
||||
}
|
||||
@ -1,10 +0,0 @@
|
||||
import { Readable } from 'stream';
|
||||
|
||||
export function streamToBuffer(readableStream: Readable): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Uint8Array[] = [];
|
||||
readableStream.on('data', (chunk) => chunks.push(chunk));
|
||||
readableStream.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
readableStream.on('error', reject);
|
||||
});
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateUserDto } from './create-user.dto';
|
||||
import { CreateUserDto } from '../../auth/dto/create-user.dto';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class UpdateUserDto extends PartialType(CreateUserDto) {
|
||||
|
||||
@ -3,19 +3,22 @@ import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
Unique,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { Workspace } from '../../workspace/entities/workspace.entity';
|
||||
import { WorkspaceUser } from '../../workspace/entities/workspace-user.entity';
|
||||
import { Page } from '../../page/entities/page.entity';
|
||||
import { Comment } from '../../comment/entities/comment.entity';
|
||||
import { Space } from '../../space/entities/space.entity';
|
||||
import { SpaceUser } from '../../space/entities/space-user.entity';
|
||||
import { Group } from '../../group/entities/group.entity';
|
||||
|
||||
@Entity('users')
|
||||
@Unique(['email', 'workspaceId'])
|
||||
export class User {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
@ -23,7 +26,7 @@ export class User {
|
||||
@Column({ length: 255, nullable: true })
|
||||
name: string;
|
||||
|
||||
@Column({ length: 255, unique: true })
|
||||
@Column({ length: 255 })
|
||||
email: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
@ -35,6 +38,15 @@ export class User {
|
||||
@Column({ nullable: true })
|
||||
avatarUrl: string;
|
||||
|
||||
@Column({ nullable: true, length: 100 })
|
||||
role: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
workspaceId: string;
|
||||
|
||||
@ManyToOne(() => Workspace, (workspace) => workspace.users)
|
||||
workspace: Workspace;
|
||||
|
||||
@Column({ length: 100, nullable: true })
|
||||
locale: string;
|
||||
|
||||
@ -56,11 +68,8 @@ export class User {
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
|
||||
@OneToMany(() => Workspace, (workspace) => workspace.creator)
|
||||
workspaces: Workspace[];
|
||||
|
||||
@OneToMany(() => WorkspaceUser, (workspaceUser) => workspaceUser.user)
|
||||
workspaceUsers: WorkspaceUser[];
|
||||
@OneToMany(() => Group, (group) => group.creator)
|
||||
groups: Group[];
|
||||
|
||||
@OneToMany(() => Page, (page) => page.creator)
|
||||
createdPages: Page[];
|
||||
@ -69,10 +78,10 @@ export class User {
|
||||
comments: Comment[];
|
||||
|
||||
@OneToMany(() => Space, (space) => space.creator)
|
||||
spaces: Space[];
|
||||
createdSpaces: Space[];
|
||||
|
||||
@OneToMany(() => SpaceUser, (spaceUser) => spaceUser.user)
|
||||
spaceUsers: SpaceUser[];
|
||||
spaces: SpaceUser[];
|
||||
|
||||
toJSON() {
|
||||
delete this.password;
|
||||
@ -85,8 +94,3 @@ export class User {
|
||||
this.password = await bcrypt.hash(this.password, saltRounds);
|
||||
}
|
||||
}
|
||||
|
||||
export type UserRole = {
|
||||
role: string;
|
||||
};
|
||||
export type UserWithRole = User & UserRole;
|
||||
|
||||
@ -7,11 +7,29 @@ export class UserRepository extends Repository<User> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(User, dataSource.createEntityManager());
|
||||
}
|
||||
async findByEmail(email: string) {
|
||||
return this.findOneBy({ email: email });
|
||||
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) {
|
||||
return this.findOneBy({ id: userId });
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,20 +1,19 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
UseGuards,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
UnauthorizedException,
|
||||
Post,
|
||||
Body,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { JwtGuard } from '../auth/guards/jwt.guard';
|
||||
import { User } from './entities/user.entity';
|
||||
import { Workspace } from '../workspace/entities/workspace.entity';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { AuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('users')
|
||||
export class UserController {
|
||||
constructor(private readonly userService: UserService) {}
|
||||
@ -28,16 +27,13 @@ export class UserController {
|
||||
throw new UnauthorizedException('Invalid user');
|
||||
}
|
||||
|
||||
return { user };
|
||||
return user;
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('info')
|
||||
async getUserInfo(@AuthUser() user: User) {
|
||||
const data: { workspace: Workspace; user: User } =
|
||||
await this.userService.getUserInstance(user.id);
|
||||
|
||||
return data;
|
||||
return await this.userService.getUserInstance(user.id);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
|
||||
@ -1,15 +1,12 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
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 { AuthModule } from '../auth/auth.module';
|
||||
import { WorkspaceModule } from '../workspace/workspace.module';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([User]), AuthModule, WorkspaceModule],
|
||||
imports: [TypeOrmModule.forFeature([User])],
|
||||
controllers: [UserController],
|
||||
providers: [UserService, UserRepository],
|
||||
exports: [UserService, UserRepository],
|
||||
|
||||
@ -3,7 +3,7 @@ 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 './dto/create-user.dto';
|
||||
import { CreateUserDto } from '../auth/dto/create-user.dto';
|
||||
|
||||
describe('UserService', () => {
|
||||
let userService: UserService;
|
||||
@ -63,7 +63,7 @@ describe('UserService', () => {
|
||||
lastLoginIp: null,
|
||||
};
|
||||
|
||||
userRepository.findByEmail.mockResolvedValue(undefined);
|
||||
//userRepository.findByEmail.mockResolvedValue(undefined);
|
||||
userRepository.save.mockResolvedValue(savedUser);
|
||||
|
||||
const result = await userService.create(createUserDto);
|
||||
|
||||
@ -3,92 +3,31 @@ import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UserRepository } from './repositories/user.repository';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { WorkspaceService } from '../workspace/services/workspace.service';
|
||||
import { DataSource, EntityManager } from 'typeorm';
|
||||
import { transactionWrapper } from '../../helpers/db.helper';
|
||||
import { CreateWorkspaceDto } from '../workspace/dto/create-workspace.dto';
|
||||
import { Workspace } from '../workspace/entities/workspace.entity';
|
||||
|
||||
export type UserWithWorkspace = {
|
||||
user: User;
|
||||
workspace: Workspace;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(
|
||||
private userRepository: UserRepository,
|
||||
private workspaceService: WorkspaceService,
|
||||
private dataSource: DataSource,
|
||||
) {}
|
||||
async create(
|
||||
createUserDto: CreateUserDto,
|
||||
manager?: EntityManager,
|
||||
): Promise<User> {
|
||||
let user: User;
|
||||
|
||||
const existingUser: User = await this.findByEmail(createUserDto.email);
|
||||
|
||||
if (existingUser) {
|
||||
throw new BadRequestException('A user with this email already exists');
|
||||
}
|
||||
|
||||
await transactionWrapper(
|
||||
async (manager: EntityManager) => {
|
||||
user = plainToInstance(User, createUserDto);
|
||||
user.locale = 'en';
|
||||
user.lastLoginAt = new Date();
|
||||
user.name = createUserDto.email.split('@')[0];
|
||||
|
||||
user = await manager.save(User, user);
|
||||
|
||||
const createWorkspaceDto: CreateWorkspaceDto = {
|
||||
name: 'My Workspace',
|
||||
};
|
||||
|
||||
await this.workspaceService.createOrJoinWorkspace(
|
||||
user.id,
|
||||
createWorkspaceDto,
|
||||
manager,
|
||||
);
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
async getUserInstance(userId: string): Promise<UserWithWorkspace> {
|
||||
const user: User = await this.findById(userId);
|
||||
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
let workspace;
|
||||
|
||||
try {
|
||||
workspace = await this.workspaceService.getUserCurrentWorkspace(userId);
|
||||
} catch (error) {
|
||||
//console.log(error);
|
||||
}
|
||||
|
||||
return { user, workspace };
|
||||
}
|
||||
constructor(private userRepository: UserRepository) {}
|
||||
|
||||
async findById(userId: string) {
|
||||
return this.userRepository.findById(userId);
|
||||
}
|
||||
|
||||
async findByEmail(email: string) {
|
||||
return this.userRepository.findByEmail(email);
|
||||
async getUserInstance(userId: string): Promise<any> {
|
||||
const user: User = await this.userRepository.findOne({
|
||||
relations: ['workspace'],
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
async update(userId: string, updateUserDto: UpdateUserDto) {
|
||||
@ -101,6 +40,7 @@ export class UserService {
|
||||
user.name = updateUserDto.name;
|
||||
}
|
||||
|
||||
// todo need workspace scoping
|
||||
if (updateUserDto.email && user.email != updateUserDto.email) {
|
||||
if (await this.userRepository.findByEmail(updateUserDto.email)) {
|
||||
throw new BadRequestException('A user with this email already exists');
|
||||
@ -114,11 +54,4 @@ export class UserService {
|
||||
|
||||
return this.userRepository.save(user);
|
||||
}
|
||||
|
||||
async compareHash(
|
||||
plainPassword: string,
|
||||
passwordHash: string,
|
||||
): Promise<boolean> {
|
||||
return await bcrypt.compare(plainPassword, passwordHash);
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,18 +7,14 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { WorkspaceService } from '../services/workspace.service';
|
||||
import { JwtGuard } from '../../auth/guards/jwt.guard';
|
||||
import { UpdateWorkspaceDto } from '../dto/update-workspace.dto';
|
||||
import { DeleteWorkspaceDto } from '../dto/delete-workspace.dto';
|
||||
import { UpdateWorkspaceUserRoleDto } from '../dto/update-workspace-user-role.dto';
|
||||
import { RemoveWorkspaceUserDto } from '../dto/remove-workspace-user.dto';
|
||||
import { AddWorkspaceUserDto } from '../dto/add-workspace-user.dto';
|
||||
import { AuthUser } from '../../../decorators/auth-user.decorator';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { CurrentWorkspace } from '../../../decorators/current-workspace.decorator';
|
||||
import { AuthWorkspace } from '../../../decorators/auth-workspace.decorator';
|
||||
import { Workspace } from '../entities/workspace.entity';
|
||||
import { PaginationOptions } from '../../../helpers/pagination/pagination-options';
|
||||
import { WorkspaceUserService } from '../services/workspace-user.service';
|
||||
import { WorkspaceInvitationService } from '../services/workspace-invitation.service';
|
||||
import { Public } from '../../../decorators/public.decorator';
|
||||
import {
|
||||
@ -27,14 +23,15 @@ import {
|
||||
RevokeInviteDto,
|
||||
} from '../dto/invitation.dto';
|
||||
import { Action } from '../../casl/ability.action';
|
||||
import { WorkspaceUser } from '../entities/workspace-user.entity';
|
||||
import { WorkspaceInvitation } from '../entities/workspace-invitation.entity';
|
||||
import { CheckPolicies } from '../../casl/decorators/policies.decorator';
|
||||
import { AppAbility } from '../../casl/abilities/casl-ability.factory';
|
||||
import { PoliciesGuard } from '../../casl/guards/policies.guard';
|
||||
import { WorkspaceUserService } from '../services/workspace-user.service';
|
||||
import { JwtAuthGuard } from '../../../guards/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@Controller('workspaces')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('workspace')
|
||||
export class WorkspaceController {
|
||||
constructor(
|
||||
private readonly workspaceService: WorkspaceService,
|
||||
@ -43,33 +40,21 @@ export class WorkspaceController {
|
||||
) {}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('/')
|
||||
async getUserWorkspaces(
|
||||
@Body()
|
||||
pagination: PaginationOptions,
|
||||
@Post('/info')
|
||||
async getWorkspace(
|
||||
@AuthUser() user: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.workspaceService.getUserWorkspaces(user.id, pagination);
|
||||
return this.workspaceService.getWorkspaceInfo(workspace.id);
|
||||
}
|
||||
|
||||
/*
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('create')
|
||||
async createWorkspace(
|
||||
@Body() createWorkspaceDto: CreateWorkspaceDto,
|
||||
@AuthUser() user: User,
|
||||
) {
|
||||
return this.workspaceService.create(user.id, createWorkspaceDto);
|
||||
}
|
||||
*/
|
||||
|
||||
@UseGuards(PoliciesGuard)
|
||||
@CheckPolicies((ability: AppAbility) => ability.can(Action.Manage, Workspace))
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('update')
|
||||
async updateWorkspace(
|
||||
@Body() updateWorkspaceDto: UpdateWorkspaceDto,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.workspaceService.update(workspace.id, updateWorkspaceDto);
|
||||
}
|
||||
@ -79,19 +64,19 @@ export class WorkspaceController {
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('delete')
|
||||
async deleteWorkspace(@Body() deleteWorkspaceDto: DeleteWorkspaceDto) {
|
||||
return this.workspaceService.delete(deleteWorkspaceDto);
|
||||
// return this.workspaceService.delete(deleteWorkspaceDto);
|
||||
}
|
||||
|
||||
@UseGuards(PoliciesGuard)
|
||||
@CheckPolicies((ability: AppAbility) =>
|
||||
ability.can(Action.Read, WorkspaceUser),
|
||||
ability.can(Action.Read, 'workspaceUser'),
|
||||
)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('members')
|
||||
async getWorkspaceMembers(
|
||||
@Body()
|
||||
pagination: PaginationOptions,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.workspaceUserService.getWorkspaceUsers(
|
||||
workspace.id,
|
||||
@ -100,48 +85,25 @@ export class WorkspaceController {
|
||||
}
|
||||
|
||||
@UseGuards(PoliciesGuard)
|
||||
@CheckPolicies((ability: AppAbility) =>
|
||||
ability.can(Action.Manage, WorkspaceUser),
|
||||
)
|
||||
// @CheckPolicies((ability: AppAbility) =>
|
||||
// ability.can(Action.Manage, 'WorkspaceUser'),
|
||||
// )
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('members/add')
|
||||
async addWorkspaceMember(
|
||||
@Body() addWorkspaceUserDto: AddWorkspaceUserDto,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.workspaceUserService.addUserToWorkspace(
|
||||
addWorkspaceUserDto.userId,
|
||||
workspace.id,
|
||||
addWorkspaceUserDto.role,
|
||||
);
|
||||
@Post('members/deactivate')
|
||||
async deactivateWorkspaceMember() {
|
||||
return this.workspaceUserService.deactivateUser();
|
||||
}
|
||||
|
||||
@UseGuards(PoliciesGuard)
|
||||
@CheckPolicies((ability: AppAbility) =>
|
||||
ability.can(Action.Manage, WorkspaceUser),
|
||||
)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('members/remove')
|
||||
async removeWorkspaceMember(
|
||||
@Body() removeWorkspaceUserDto: RemoveWorkspaceUserDto,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.workspaceUserService.removeUserFromWorkspace(
|
||||
removeWorkspaceUserDto.userId,
|
||||
workspace.id,
|
||||
);
|
||||
}
|
||||
|
||||
@UseGuards(PoliciesGuard)
|
||||
@CheckPolicies((ability: AppAbility) =>
|
||||
ability.can(Action.Manage, WorkspaceUser),
|
||||
ability.can(Action.Manage, 'workspaceUser'),
|
||||
)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('members/role')
|
||||
async updateWorkspaceMemberRole(
|
||||
@Body() workspaceUserRoleDto: UpdateWorkspaceUserRoleDto,
|
||||
@AuthUser() authUser: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.workspaceUserService.updateWorkspaceUserRole(
|
||||
authUser,
|
||||
@ -159,7 +121,7 @@ export class WorkspaceController {
|
||||
async inviteUser(
|
||||
@Body() inviteUserDto: InviteUserDto,
|
||||
@AuthUser() authUser: User,
|
||||
@CurrentWorkspace() workspace: Workspace,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
return this.workspaceInvitationService.createInvitation(
|
||||
authUser,
|
||||
@ -172,9 +134,9 @@ export class WorkspaceController {
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('invite/accept')
|
||||
async acceptInvite(@Body() acceptInviteDto: AcceptInviteDto) {
|
||||
return this.workspaceInvitationService.acceptInvitation(
|
||||
acceptInviteDto.invitationId,
|
||||
);
|
||||
// return this.workspaceInvitationService.acceptInvitation(
|
||||
// acceptInviteDto.invitationId,
|
||||
//);
|
||||
}
|
||||
|
||||
// TODO: authorize permission with guards
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { IsEmail, IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
import { WorkspaceUserRole } from '../entities/workspace-user.entity';
|
||||
import { UserRole } from '../../../helpers/types/permission';
|
||||
|
||||
export class InviteUserDto {
|
||||
@IsString()
|
||||
@ -9,7 +9,7 @@ export class InviteUserDto {
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@IsEnum(WorkspaceUserRole)
|
||||
@IsEnum(UserRole)
|
||||
role: string;
|
||||
}
|
||||
|
||||
|
||||
@ -1,52 +0,0 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
UpdateDateColumn,
|
||||
ManyToOne,
|
||||
JoinColumn,
|
||||
Unique,
|
||||
} from 'typeorm';
|
||||
import { Workspace } from './workspace.entity';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
|
||||
@Entity('workspace_users')
|
||||
@Unique(['workspaceId', 'userId'])
|
||||
export class WorkspaceUser {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column()
|
||||
userId: string;
|
||||
|
||||
@ManyToOne(() => User, (user) => user.workspaceUsers, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'userId' })
|
||||
user: User;
|
||||
|
||||
@Column()
|
||||
workspaceId: string;
|
||||
|
||||
@ManyToOne(() => Workspace, (workspace) => workspace.workspaceUsers, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'workspaceId' })
|
||||
workspace: Workspace;
|
||||
|
||||
@Column({ length: 100, nullable: true })
|
||||
role: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export enum WorkspaceUserRole {
|
||||
OWNER = 'owner',
|
||||
ADMIN = 'admin',
|
||||
MEMBER = 'member',
|
||||
}
|
||||
@ -4,18 +4,18 @@ import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
UpdateDateColumn,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
JoinColumn,
|
||||
OneToOne,
|
||||
DeleteDateColumn,
|
||||
} from 'typeorm';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { WorkspaceUser } from './workspace-user.entity';
|
||||
import { Page } from '../../page/entities/page.entity';
|
||||
import { WorkspaceInvitation } from './workspace-invitation.entity';
|
||||
import { Comment } from '../../comment/entities/comment.entity';
|
||||
import { Space } from '../../space/entities/space.entity';
|
||||
import { Group } from '../../group/entities/group.entity';
|
||||
import { UserRole } from '../../../helpers/types/permission';
|
||||
|
||||
@Entity('workspaces')
|
||||
export class Workspace {
|
||||
@ -46,12 +46,15 @@ export class Workspace {
|
||||
@Column({ type: 'jsonb', nullable: true })
|
||||
settings: any;
|
||||
|
||||
@Column()
|
||||
@Column({ default: UserRole.MEMBER })
|
||||
defaultRole: string;
|
||||
|
||||
@Column({ nullable: true, type: 'uuid' })
|
||||
creatorId: string;
|
||||
|
||||
@ManyToOne(() => User, (user) => user.workspaces)
|
||||
@JoinColumn({ name: 'creatorId' })
|
||||
creator: User;
|
||||
//@ManyToOne(() => User, (user) => user.workspaces)
|
||||
// @JoinColumn({ name: 'creatorId' })
|
||||
// creator: User;
|
||||
|
||||
@Column({ nullable: true })
|
||||
defaultSpaceId: string;
|
||||
@ -66,8 +69,11 @@ export class Workspace {
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
|
||||
@OneToMany(() => WorkspaceUser, (workspaceUser) => workspaceUser.workspace)
|
||||
workspaceUsers: WorkspaceUser[];
|
||||
@DeleteDateColumn()
|
||||
deletedAt: Date;
|
||||
|
||||
@OneToMany(() => User, (user) => user.workspace)
|
||||
users: [];
|
||||
|
||||
@OneToMany(
|
||||
() => WorkspaceInvitation,
|
||||
@ -87,5 +93,5 @@ export class Workspace {
|
||||
@OneToMany(() => Group, (group) => group.workspace)
|
||||
groups: [];
|
||||
|
||||
workspaceUser?: WorkspaceUser;
|
||||
// workspaceUser?: WorkspaceUser;
|
||||
}
|
||||
|
||||
@ -1,10 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { WorkspaceUser } from '../entities/workspace-user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class WorkspaceUserRepository extends Repository<WorkspaceUser> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(WorkspaceUser, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@ -8,7 +8,24 @@ export class WorkspaceRepository extends Repository<Workspace> {
|
||||
super(Workspace, dataSource.createEntityManager());
|
||||
}
|
||||
|
||||
async findById(workspaceId: string) {
|
||||
return this.findOneBy({ id: workspaceId });
|
||||
async findById(workspaceId: string): Promise<Workspace> {
|
||||
// see: https://github.com/typeorm/typeorm/issues/9316
|
||||
const queryBuilder = this.dataSource.createQueryBuilder(
|
||||
Workspace,
|
||||
'workspace',
|
||||
);
|
||||
return await queryBuilder
|
||||
.where('workspace.id = :id', { id: workspaceId })
|
||||
.getOne();
|
||||
}
|
||||
|
||||
async findFirst(): Promise<Workspace> {
|
||||
const createdWorkspace = await this.find({
|
||||
order: {
|
||||
createdAt: 'ASC',
|
||||
},
|
||||
take: 1,
|
||||
});
|
||||
return createdWorkspace[0];
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,10 +3,11 @@ import { WorkspaceInvitationRepository } from '../repositories/workspace-invitat
|
||||
import { WorkspaceInvitation } from '../entities/workspace-invitation.entity';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { WorkspaceService } from './workspace.service';
|
||||
import { WorkspaceUserService } from './workspace-user.service';
|
||||
import { WorkspaceUserRole } from '../entities/workspace-user.entity';
|
||||
import { UserService } from '../../user/user.service';
|
||||
import { InviteUserDto } from '../dto/invitation.dto';
|
||||
import { WorkspaceUserService } from './workspace-user.service';
|
||||
import { UserRole } from '../../../helpers/types/permission';
|
||||
import { UserRepository } from '../../user/repositories/user.repository';
|
||||
|
||||
@Injectable()
|
||||
export class WorkspaceInvitationService {
|
||||
@ -15,6 +16,7 @@ export class WorkspaceInvitationService {
|
||||
private workspaceService: WorkspaceService,
|
||||
private workspaceUserService: WorkspaceUserService,
|
||||
private userService: UserService,
|
||||
private userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async findInvitedUserByEmail(
|
||||
@ -32,37 +34,17 @@ export class WorkspaceInvitationService {
|
||||
workspaceId: string,
|
||||
inviteUserDto: InviteUserDto,
|
||||
): Promise<WorkspaceInvitation> {
|
||||
const authUserMembership =
|
||||
await this.workspaceUserService.findWorkspaceUser(
|
||||
authUser.id,
|
||||
// check if invited user is already a workspace member
|
||||
const invitedUser =
|
||||
await this.workspaceUserService.findWorkspaceUserByEmail(
|
||||
inviteUserDto.email,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
if (!authUserMembership) {
|
||||
throw new BadRequestException('Inviting user must be a workspace member');
|
||||
}
|
||||
|
||||
if (authUserMembership.role != WorkspaceUserRole.OWNER) {
|
||||
throw new BadRequestException(
|
||||
'Only workspace owners can invite new members',
|
||||
);
|
||||
}
|
||||
|
||||
const invitedUser = await this.userService.findByEmail(inviteUserDto.email);
|
||||
|
||||
// check if invited user is already a workspace member
|
||||
if (invitedUser) {
|
||||
const invitedUserMembership =
|
||||
await this.workspaceUserService.findWorkspaceUser(
|
||||
invitedUser.id,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
if (invitedUserMembership) {
|
||||
throw new BadRequestException(
|
||||
'This user already a member of this workspace',
|
||||
);
|
||||
}
|
||||
throw new BadRequestException(
|
||||
'User is already a member of this workspace',
|
||||
);
|
||||
}
|
||||
|
||||
// check if user was already invited
|
||||
@ -72,7 +54,7 @@ export class WorkspaceInvitationService {
|
||||
);
|
||||
|
||||
if (existingInvitation) {
|
||||
throw new BadRequestException('This user has already been invited');
|
||||
throw new BadRequestException('User has already been invited');
|
||||
}
|
||||
|
||||
const invitation = new WorkspaceInvitation();
|
||||
@ -97,14 +79,22 @@ export class WorkspaceInvitationService {
|
||||
|
||||
// TODO: to be completed
|
||||
|
||||
// check if user is in the system already
|
||||
const invitedUser = await this.userService.findByEmail(invitation.email);
|
||||
// check if user is already a member
|
||||
const invitedUser =
|
||||
await this.workspaceUserService.findWorkspaceUserByEmail(
|
||||
invitation.email,
|
||||
invitation.workspaceId,
|
||||
);
|
||||
|
||||
if (invitedUser) {
|
||||
// fetch the workspace
|
||||
// add the user to the workspace
|
||||
throw new BadRequestException(
|
||||
'User is already a member of this workspace',
|
||||
);
|
||||
}
|
||||
return invitation;
|
||||
// add create account for user
|
||||
// add the user to the workspace
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async revokeInvitation(invitationId: string): Promise<void> {
|
||||
|
||||
@ -1,69 +1,34 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { WorkspaceUserRepository } from '../repositories/workspace-user.repository';
|
||||
import {
|
||||
WorkspaceUser,
|
||||
WorkspaceUserRole,
|
||||
} from '../entities/workspace-user.entity';
|
||||
import { Workspace } from '../entities/workspace.entity';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { UpdateWorkspaceUserRoleDto } from '../dto/update-workspace-user-role.dto';
|
||||
import { PaginationOptions } from '../../../helpers/pagination/pagination-options';
|
||||
import { PaginationMetaDto } from '../../../helpers/pagination/pagination-meta-dto';
|
||||
import { PaginatedResult } from '../../../helpers/pagination/paginated-result';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { DataSource, EntityManager } from 'typeorm';
|
||||
import { transactionWrapper } from '../../../helpers/db.helper';
|
||||
import { WorkspaceRepository } from '../repositories/workspace.repository';
|
||||
import { UserRepository } from '../../user/repositories/user.repository';
|
||||
import { UserRole } from '../../../helpers/types/permission';
|
||||
|
||||
@Injectable()
|
||||
export class WorkspaceUserService {
|
||||
constructor(
|
||||
private workspaceUserRepository: WorkspaceUserRepository,
|
||||
private dataSource: DataSource,
|
||||
private workspaceRepository: WorkspaceRepository,
|
||||
private userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async addUserToWorkspace(
|
||||
userId: string,
|
||||
async getWorkspaceUsers(
|
||||
workspaceId: string,
|
||||
role: string,
|
||||
manager?: EntityManager,
|
||||
): Promise<WorkspaceUser> {
|
||||
let addedUser;
|
||||
|
||||
await transactionWrapper(
|
||||
async (manager) => {
|
||||
const userExists = await manager.exists(User, {
|
||||
where: { id: userId },
|
||||
});
|
||||
if (!userExists) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
const existingWorkspaceUser = await manager.findOneBy(WorkspaceUser, {
|
||||
userId: userId,
|
||||
workspaceId: workspaceId,
|
||||
});
|
||||
|
||||
if (existingWorkspaceUser) {
|
||||
throw new BadRequestException(
|
||||
'User is already a member of this workspace',
|
||||
);
|
||||
}
|
||||
|
||||
const workspaceUser = new WorkspaceUser();
|
||||
workspaceUser.userId = userId;
|
||||
workspaceUser.workspaceId = workspaceId;
|
||||
workspaceUser.role = role;
|
||||
|
||||
addedUser = await manager.save(workspaceUser);
|
||||
paginationOptions: PaginationOptions,
|
||||
): Promise<PaginatedResult<User>> {
|
||||
const [workspaceUsers, count] = await this.userRepository.findAndCount({
|
||||
where: {
|
||||
workspaceId,
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
take: paginationOptions.limit,
|
||||
skip: paginationOptions.skip,
|
||||
});
|
||||
|
||||
return addedUser;
|
||||
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
|
||||
return new PaginatedResult(workspaceUsers, paginationMeta);
|
||||
}
|
||||
|
||||
async updateWorkspaceUserRole(
|
||||
@ -80,16 +45,14 @@ export class WorkspaceUserService {
|
||||
return workspaceUser;
|
||||
}
|
||||
|
||||
const workspaceOwnerCount = await this.workspaceUserRepository.count({
|
||||
const workspaceOwnerCount = await this.userRepository.count({
|
||||
where: {
|
||||
role: WorkspaceUserRole.OWNER,
|
||||
role: UserRole.OWNER,
|
||||
workspaceId,
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
workspaceUser.role === WorkspaceUserRole.OWNER &&
|
||||
workspaceOwnerCount === 1
|
||||
) {
|
||||
if (workspaceUser.role === UserRole.OWNER && workspaceOwnerCount === 1) {
|
||||
throw new BadRequestException(
|
||||
'There must be at least one workspace owner',
|
||||
);
|
||||
@ -97,105 +60,26 @@ export class WorkspaceUserService {
|
||||
|
||||
workspaceUser.role = workspaceUserRoleDto.role;
|
||||
|
||||
return this.workspaceUserRepository.save(workspaceUser);
|
||||
return this.userRepository.save(workspaceUser);
|
||||
}
|
||||
|
||||
async removeUserFromWorkspace(
|
||||
userId: string,
|
||||
workspaceId: string,
|
||||
): Promise<void> {
|
||||
const workspaceUser = await this.findAndValidateWorkspaceUser(
|
||||
userId,
|
||||
workspaceId,
|
||||
);
|
||||
async deactivateUser(): Promise<any> {
|
||||
return 'todo';
|
||||
}
|
||||
|
||||
const workspaceOwnerCount = await this.workspaceUserRepository.count({
|
||||
where: {
|
||||
role: WorkspaceUserRole.OWNER,
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
workspaceUser.role === WorkspaceUserRole.OWNER &&
|
||||
workspaceOwnerCount === 1
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'There must be at least one workspace owner',
|
||||
);
|
||||
}
|
||||
|
||||
await this.workspaceUserRepository.delete({
|
||||
userId,
|
||||
async findWorkspaceUser(userId: string, workspaceId: string): Promise<User> {
|
||||
return await this.userRepository.findOneBy({
|
||||
id: userId,
|
||||
workspaceId,
|
||||
});
|
||||
}
|
||||
|
||||
async getUserWorkspaces(
|
||||
userId: string,
|
||||
paginationOptions: PaginationOptions,
|
||||
): Promise<PaginatedResult<Workspace>> {
|
||||
const [workspaces, count] = await this.workspaceUserRepository.findAndCount(
|
||||
{
|
||||
where: { userId: userId },
|
||||
relations: ['workspace'],
|
||||
take: paginationOptions.limit,
|
||||
skip: paginationOptions.skip,
|
||||
},
|
||||
);
|
||||
|
||||
const userWorkspaces = workspaces.map(
|
||||
(userWorkspace: WorkspaceUser) => userWorkspace.workspace,
|
||||
);
|
||||
|
||||
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
|
||||
return new PaginatedResult(userWorkspaces, paginationMeta);
|
||||
}
|
||||
|
||||
async getWorkspaceUsers(
|
||||
async findWorkspaceUserByEmail(
|
||||
email: string,
|
||||
workspaceId: string,
|
||||
paginationOptions: PaginationOptions,
|
||||
): Promise<PaginatedResult<any>> {
|
||||
const [workspaceUsers, count] =
|
||||
await this.workspaceUserRepository.findAndCount({
|
||||
relations: ['user'],
|
||||
where: {
|
||||
workspace: {
|
||||
id: workspaceId,
|
||||
},
|
||||
},
|
||||
take: paginationOptions.limit,
|
||||
skip: paginationOptions.skip,
|
||||
});
|
||||
|
||||
const users = workspaceUsers.map((workspaceUser) => {
|
||||
workspaceUser.user.password = '';
|
||||
return {
|
||||
...workspaceUser.user,
|
||||
role: workspaceUser.role,
|
||||
};
|
||||
});
|
||||
|
||||
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
|
||||
return new PaginatedResult(users, paginationMeta);
|
||||
}
|
||||
|
||||
async getUserRoleInWorkspace(
|
||||
userId: string,
|
||||
workspaceId: string,
|
||||
): Promise<string> {
|
||||
const workspaceUser = await this.findAndValidateWorkspaceUser(
|
||||
userId,
|
||||
workspaceId,
|
||||
);
|
||||
return workspaceUser.role ? workspaceUser.role : null;
|
||||
}
|
||||
|
||||
async findWorkspaceUser(
|
||||
userId: string,
|
||||
workspaceId: string,
|
||||
): Promise<WorkspaceUser> {
|
||||
return await this.workspaceUserRepository.findOneBy({
|
||||
userId,
|
||||
): Promise<User> {
|
||||
return await this.userRepository.findOneBy({
|
||||
email: email,
|
||||
workspaceId,
|
||||
});
|
||||
}
|
||||
@ -203,13 +87,13 @@ export class WorkspaceUserService {
|
||||
async findAndValidateWorkspaceUser(
|
||||
userId: string,
|
||||
workspaceId: string,
|
||||
): Promise<WorkspaceUser> {
|
||||
const workspaceUser = await this.findWorkspaceUser(userId, workspaceId);
|
||||
): Promise<User> {
|
||||
const user = await this.findWorkspaceUser(userId, workspaceId);
|
||||
|
||||
if (!workspaceUser) {
|
||||
if (!user) {
|
||||
throw new BadRequestException('Workspace member not found');
|
||||
}
|
||||
|
||||
return workspaceUser;
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,32 +1,31 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { CreateWorkspaceDto } from '../dto/create-workspace.dto';
|
||||
import { WorkspaceRepository } from '../repositories/workspace.repository';
|
||||
import { WorkspaceUserRepository } from '../repositories/workspace-user.repository';
|
||||
import {
|
||||
WorkspaceUser,
|
||||
WorkspaceUserRole,
|
||||
} from '../entities/workspace-user.entity';
|
||||
import { Workspace } from '../entities/workspace.entity';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { UpdateWorkspaceDto } from '../dto/update-workspace.dto';
|
||||
import { DeleteWorkspaceDto } from '../dto/delete-workspace.dto';
|
||||
import { SpaceService } from '../../space/space.service';
|
||||
import { PaginationOptions } from '../../../helpers/pagination/pagination-options';
|
||||
import { PaginationMetaDto } from '../../../helpers/pagination/pagination-meta-dto';
|
||||
import { PaginatedResult } from '../../../helpers/pagination/paginated-result';
|
||||
import { DataSource, EntityManager } from 'typeorm';
|
||||
import { transactionWrapper } from '../../../helpers/db.helper';
|
||||
import { CreateSpaceDto } from '../../space/dto/create-space.dto';
|
||||
import { WorkspaceUserService } from './workspace-user.service';
|
||||
import { UserRepository } from '../../user/repositories/user.repository';
|
||||
import { SpaceRole, UserRole } from '../../../helpers/types/permission';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { EnvironmentService } from '../../../environment/environment.service';
|
||||
import { Space } from '../../space/entities/space.entity';
|
||||
|
||||
@Injectable()
|
||||
export class WorkspaceService {
|
||||
constructor(
|
||||
private workspaceRepository: WorkspaceRepository,
|
||||
private workspaceUserRepository: WorkspaceUserRepository,
|
||||
private userRepository: UserRepository,
|
||||
private spaceService: SpaceService,
|
||||
private workspaceUserService: WorkspaceUserService,
|
||||
private environmentService: EnvironmentService,
|
||||
|
||||
private dataSource: DataSource,
|
||||
) {}
|
||||
@ -35,115 +34,118 @@ export class WorkspaceService {
|
||||
return this.workspaceRepository.findById(workspaceId);
|
||||
}
|
||||
|
||||
async save(workspace: Workspace) {
|
||||
return this.workspaceRepository.save(workspace);
|
||||
}
|
||||
async getWorkspaceInfo(workspaceId: string): Promise<Workspace> {
|
||||
const space = await this.workspaceRepository
|
||||
.createQueryBuilder('workspace')
|
||||
.where('workspace.id = :workspaceId', { workspaceId })
|
||||
.loadRelationCountAndMap(
|
||||
'workspace.userCount',
|
||||
'workspace.users',
|
||||
'workspaceUsers',
|
||||
)
|
||||
.getOne();
|
||||
|
||||
async createOrJoinWorkspace(
|
||||
userId,
|
||||
createWorkspaceDto?: CreateWorkspaceDto,
|
||||
manager?: EntityManager,
|
||||
) {
|
||||
await transactionWrapper(
|
||||
async (manager: EntityManager) => {
|
||||
const workspaceCount = await manager
|
||||
.createQueryBuilder(Workspace, 'workspace')
|
||||
.getCount();
|
||||
if (!space) {
|
||||
throw new NotFoundException('Workspace not found');
|
||||
}
|
||||
|
||||
if (workspaceCount === 0) {
|
||||
// create first workspace and add user to workspace as owner
|
||||
const createdWorkspace = await this.create(
|
||||
userId,
|
||||
createWorkspaceDto ?? null,
|
||||
manager,
|
||||
);
|
||||
await this.workspaceUserService.addUserToWorkspace(
|
||||
userId,
|
||||
createdWorkspace.id,
|
||||
WorkspaceUserRole.OWNER,
|
||||
manager,
|
||||
);
|
||||
|
||||
// create default space and add user to it too.
|
||||
const createdSpace = await this.spaceService.create(
|
||||
userId,
|
||||
createdWorkspace.id,
|
||||
{ name: 'General' } as CreateSpaceDto,
|
||||
manager,
|
||||
);
|
||||
|
||||
await this.spaceService.addUserToSpace(
|
||||
userId,
|
||||
createdSpace.id,
|
||||
WorkspaceUserRole.OWNER,
|
||||
createdWorkspace.id,
|
||||
manager,
|
||||
);
|
||||
|
||||
createdWorkspace.defaultSpaceId = createdSpace.id;
|
||||
await manager.save(createdWorkspace);
|
||||
} else {
|
||||
// limited to single workspace
|
||||
// fetch the oldest workspace and add user to it
|
||||
const firstWorkspace = await manager.find(Workspace, {
|
||||
order: {
|
||||
createdAt: 'ASC',
|
||||
},
|
||||
take: 1,
|
||||
});
|
||||
|
||||
// add user to workspace and default space
|
||||
|
||||
await this.workspaceUserService.addUserToWorkspace(
|
||||
userId,
|
||||
firstWorkspace[0].id,
|
||||
WorkspaceUserRole.MEMBER,
|
||||
manager,
|
||||
);
|
||||
|
||||
await this.spaceService.addUserToSpace(
|
||||
userId,
|
||||
firstWorkspace[0].defaultSpaceId,
|
||||
WorkspaceUserRole.MEMBER,
|
||||
firstWorkspace[0].id,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
return space;
|
||||
}
|
||||
|
||||
async create(
|
||||
userId: string,
|
||||
createWorkspaceDto?: CreateWorkspaceDto,
|
||||
user: User,
|
||||
createWorkspaceDto: CreateWorkspaceDto,
|
||||
manager?: EntityManager,
|
||||
): Promise<Workspace> {
|
||||
let workspace: Workspace;
|
||||
|
||||
await transactionWrapper(
|
||||
return await transactionWrapper(
|
||||
async (manager) => {
|
||||
if (createWorkspaceDto) {
|
||||
workspace = plainToInstance(Workspace, createWorkspaceDto);
|
||||
} else {
|
||||
workspace = new Workspace();
|
||||
}
|
||||
|
||||
workspace.inviteCode = uuid();
|
||||
workspace.creatorId = userId;
|
||||
|
||||
//if (workspace.name && !workspace.hostname?.trim()) {
|
||||
// workspace.hostname = generateHostname(createWorkspaceDto.name);
|
||||
// }
|
||||
let workspace = new Workspace();
|
||||
|
||||
workspace.name = createWorkspaceDto.name;
|
||||
workspace.hostname = createWorkspaceDto?.hostname;
|
||||
workspace.description = createWorkspaceDto.description;
|
||||
workspace.inviteCode = uuidv4();
|
||||
workspace.creatorId = user.id;
|
||||
workspace = await manager.save(workspace);
|
||||
|
||||
user.workspaceId = workspace.id;
|
||||
user.role = UserRole.OWNER;
|
||||
await manager.save(user);
|
||||
|
||||
// create default space
|
||||
const spaceData: CreateSpaceDto = {
|
||||
name: 'General',
|
||||
};
|
||||
|
||||
// create default space
|
||||
const createdSpace = await this.spaceService.create(
|
||||
user.id,
|
||||
workspace.id,
|
||||
spaceData,
|
||||
manager,
|
||||
);
|
||||
|
||||
// and add user to it too.
|
||||
await this.spaceService.addUserToSpace(
|
||||
user.id,
|
||||
createdSpace.id,
|
||||
SpaceRole.OWNER,
|
||||
workspace.id,
|
||||
manager,
|
||||
);
|
||||
|
||||
workspace.defaultSpaceId = createdSpace.id;
|
||||
await manager.save(workspace);
|
||||
return workspace;
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
return workspace;
|
||||
async addUserToWorkspace(
|
||||
user: User,
|
||||
workspaceId,
|
||||
assignedRole?: UserRole,
|
||||
manager?: EntityManager,
|
||||
): Promise<Workspace> {
|
||||
return await transactionWrapper(
|
||||
async (manager: EntityManager) => {
|
||||
const workspace = await manager.findOneBy(Workspace, {
|
||||
id: workspaceId,
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
throw new BadRequestException('Workspace does not exist');
|
||||
}
|
||||
|
||||
user.role = assignedRole ?? workspace.defaultRole;
|
||||
user.workspaceId = workspace.id;
|
||||
await manager.save(user);
|
||||
|
||||
const space = await manager.findOneBy(Space, {
|
||||
id: workspace.defaultSpaceId,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
if (!space) {
|
||||
throw new NotFoundException('Space not found');
|
||||
}
|
||||
|
||||
// add user to default space
|
||||
await this.spaceService.addUserToSpace(
|
||||
user.id,
|
||||
space.id,
|
||||
space.defaultRole,
|
||||
workspace.id,
|
||||
manager,
|
||||
);
|
||||
|
||||
return workspace;
|
||||
},
|
||||
this.dataSource,
|
||||
manager,
|
||||
);
|
||||
}
|
||||
|
||||
async update(
|
||||
@ -178,42 +180,4 @@ export class WorkspaceService {
|
||||
// remove all existing users from workspace
|
||||
// delete workspace
|
||||
}
|
||||
|
||||
async getUserCurrentWorkspace(userId: string): Promise<Workspace> {
|
||||
const userWorkspace = await this.workspaceUserRepository.findOne({
|
||||
relations: ['workspace'],
|
||||
where: { userId: userId },
|
||||
order: {
|
||||
createdAt: 'ASC',
|
||||
},
|
||||
});
|
||||
|
||||
if (!userWorkspace) {
|
||||
throw new NotFoundException('No workspace found for this user');
|
||||
}
|
||||
|
||||
const { workspace, ...workspaceUser } = userWorkspace;
|
||||
return { ...workspace, workspaceUser } as Workspace;
|
||||
}
|
||||
|
||||
async getUserWorkspaces(
|
||||
userId: string,
|
||||
paginationOptions: PaginationOptions,
|
||||
): Promise<PaginatedResult<Workspace>> {
|
||||
const [workspaces, count] = await this.workspaceUserRepository.findAndCount(
|
||||
{
|
||||
where: { userId: userId },
|
||||
relations: ['workspace'],
|
||||
take: paginationOptions.limit,
|
||||
skip: paginationOptions.skip,
|
||||
},
|
||||
);
|
||||
|
||||
const userWorkspaces = workspaces.map(
|
||||
(userWorkspace: WorkspaceUser) => userWorkspace.workspace,
|
||||
);
|
||||
|
||||
const paginationMeta = new PaginationMetaDto({ count, paginationOptions });
|
||||
return new PaginatedResult(userWorkspaces, paginationMeta);
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,20 +4,17 @@ import { WorkspaceController } from './controllers/workspace.controller';
|
||||
import { WorkspaceRepository } from './repositories/workspace.repository';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Workspace } from './entities/workspace.entity';
|
||||
import { WorkspaceUser } from './entities/workspace-user.entity';
|
||||
import { WorkspaceInvitation } from './entities/workspace-invitation.entity';
|
||||
import { WorkspaceUserRepository } from './repositories/workspace-user.repository';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { SpaceModule } from '../space/space.module';
|
||||
import { WorkspaceUserService } from './services/workspace-user.service';
|
||||
import { WorkspaceInvitationService } from './services/workspace-invitation.service';
|
||||
import { WorkspaceInvitationRepository } from './repositories/workspace-invitation.repository';
|
||||
import { WorkspaceUserService } from './services/workspace-user.service';
|
||||
import { UserModule } from '../user/user.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Workspace, WorkspaceUser, WorkspaceInvitation]),
|
||||
AuthModule,
|
||||
SpaceModule,
|
||||
TypeOrmModule.forFeature([Workspace, WorkspaceInvitation]),
|
||||
SpaceModule, UserModule
|
||||
],
|
||||
controllers: [WorkspaceController],
|
||||
providers: [
|
||||
@ -25,9 +22,8 @@ import { WorkspaceInvitationRepository } from './repositories/workspace-invitati
|
||||
WorkspaceUserService,
|
||||
WorkspaceInvitationService,
|
||||
WorkspaceRepository,
|
||||
WorkspaceUserRepository,
|
||||
WorkspaceInvitationRepository,
|
||||
],
|
||||
exports: [WorkspaceService, WorkspaceRepository, WorkspaceUserRepository],
|
||||
exports: [WorkspaceService, WorkspaceRepository],
|
||||
})
|
||||
export class WorkspaceModule {}
|
||||
|
||||
@ -1,5 +0,0 @@
|
||||
export function generateHostname(name: string): string {
|
||||
let hostname = name.replace(/[^a-z0-9]/gi, '').toLowerCase();
|
||||
hostname = hostname.substring(0, 30);
|
||||
return hostname;
|
||||
}
|
||||
Reference in New Issue
Block a user