Skip to content

Commit

Permalink
feat: add a middleware to transform user info
Browse files Browse the repository at this point in the history
  • Loading branch information
ChingCdesu committed Oct 1, 2023
1 parent b7881e8 commit c7f2758
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 50 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "supernode",
"version": "1.0.0-alpha.10",
"version": "1.0.0-alpha.11",
"description": "",
"author": "",
"private": true,
Expand Down
13 changes: 11 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { Module } from '@nestjs/common';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';

import { UserMiddleware } from '@/common/middlewares/user.middleware';

import { DatabaseConfig } from '@/config/database.config';

Expand All @@ -12,9 +15,11 @@ import { LocalAuthModule } from '@/auth/local/local.module';
import { OidcModule } from '@/auth/oidc/oidc.module';
import { SupernodeModule } from '@/modules/supernode/supernode.module';
import { UserModule } from '@/modules/user/user.module';
import { User } from '@/modules/user/entities/user.entity';

@Module({
imports: [
SequelizeModule.forFeature([User]),
DatabaseConfig,
LocalAuthModule,
OidcModule,
Expand All @@ -28,4 +33,8 @@ import { UserModule } from '@/modules/user/user.module';
DeviceBusinessModule,
],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(UserMiddleware).exclude('auth/(.*)').forRoutes('*');
}
}
13 changes: 1 addition & 12 deletions src/common/guards/administration.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,6 @@ import { useConfig } from '@/utils/config.util';
export class AdministrationGuard implements CanActivate {
async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest();
if (!request.user) {
return false;
}
if (request.user instanceof User) {
return request.user.isAdmin;
} else if (request.user.sub) {
const config = useConfig();
return Array.from((request.user.groups as string[]) ?? []).includes(
config.oidc.adminGroup,
);
}
return false;
return !!request.localUser?.isAdmin;
}
}
2 changes: 1 addition & 1 deletion src/common/interceptors/transform.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class TransformInterceptor implements NestInterceptor {
`Request original url: ${req.originalUrl}\n` +
`Method: ${req.method}\n` +
`IP: ${req.headers['X-Real-IP'] ?? req.ip}\n` +
`User: ${JSON.stringify(req.user)}\n` +
`User: ${JSON.stringify(req.localUser)}\n` +
`Response data: ${JSON.stringify(data)}`;
accessLogger.log(accessLog);
return {
Expand Down
34 changes: 34 additions & 0 deletions src/common/middlewares/user.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { OidcUserDto } from '@/modules/user/dtos/oidc-user.dto';
import { User } from '@/modules/user/entities/user.entity';
import { ForbiddenException, Injectable, NestMiddleware } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Request, Response, NextFunction } from 'express';
import { isNull } from 'lodash';

@Injectable()
export class UserMiddleware implements NestMiddleware {
constructor(
@InjectModel(User)
private readonly _userModel: typeof User,
) {}
use(req: Request, res: Response, next: NextFunction) {
if (!req.user || req.user instanceof User) {
next();
return;
}
const { sub: uniqueId } = req.user as OidcUserDto;
this._userModel
.findOne({
where: {
uniqueId,
},
})
.then((user) => {
if (isNull(user)) {
throw new ForbiddenException('Not recognized user');
}
req.localUser = user;
next();
});
}
}
10 changes: 5 additions & 5 deletions src/modules/business/device/device.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class DeviceBusinessService extends LoggerProvider {

public async list(): Promise<DeviceDto[]> {
const data: DeviceDto[] = [];
// const operator = this._req.user;
// const operator = this._req.localUser;
const nativeList = await this._supernodeService.listCommunities();

const result = await this._deviceModel.findAndCountAll({
Expand Down Expand Up @@ -74,7 +74,7 @@ export class DeviceBusinessService extends LoggerProvider {
}

public async get(deviceId: number): Promise<DeviceDto> {
const operator = this._req.user;
const operator = this._req.localUser;
const device = await this._deviceModel.findOne({
where: {
id: deviceId,
Expand Down Expand Up @@ -122,7 +122,7 @@ export class DeviceBusinessService extends LoggerProvider {
public async create(
createDeviceDto: BusinessCreateDeviceDto,
): Promise<DeviceDto> {
const operator = this._req.user;
const operator = this._req.localUser;
const result = await this._deviceModel.create({
name: createDeviceDto.name,
publicKey: createDeviceDto.publicKey,
Expand All @@ -147,7 +147,7 @@ export class DeviceBusinessService extends LoggerProvider {
deviceId: number,
updateDeviceDto: BusinessUpdateDeviceDto,
): Promise<void> {
const operator = this._req.user;
const operator = this._req.localUser;
const [affectedRows] = await this._deviceModel.update(updateDeviceDto, {
where: {
id: deviceId,
Expand All @@ -172,7 +172,7 @@ export class DeviceBusinessService extends LoggerProvider {
}

public async destroy(deviceId: number): Promise<void> {
const operator = this._req.user;
const operator = this._req.localUser;
const affectedRows = await this._deviceModel.destroy({
where: {
id: deviceId,
Expand Down
8 changes: 4 additions & 4 deletions src/modules/management/community/community.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class CommunityManagementService extends LoggerProvider {
const community = await this._communityModal.create(
Object.assign(communityDto),
);
const operator = this._req.user;
const operator = this._req.localUser;
await this._auditService.log({
action: 'create',
resource: 'community',
Expand Down Expand Up @@ -124,7 +124,7 @@ export class CommunityManagementService extends LoggerProvider {
await community.destroy();
await this._supernodeService.syncCommunities();

const operator = this._req.user;
const operator = this._req.localUser;
await this._auditService.log({
action: 'destroy',
resource: 'community',
Expand All @@ -139,7 +139,7 @@ export class CommunityManagementService extends LoggerProvider {
if (!community) {
throw new Error('Community not found');
}
const operator = this._req.user;
const operator = this._req.localUser;
await this._auditService.log({
action: 'export',
resource: 'community',
Expand All @@ -161,7 +161,7 @@ export class CommunityManagementService extends LoggerProvider {
const community = await this._communityModal.create(
Object.assign(communityDto),
);
const operator = this._req.user;
const operator = this._req.localUser;
await this._auditService.log({
action: 'import',
resource: 'community',
Expand Down
6 changes: 3 additions & 3 deletions src/modules/management/device/device.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export class DeviceManagementService extends LoggerProvider {
ownerId: createDeviceDto.ownerId,
communityId,
});
const operator = this._req.user;
const operator = this._req.localUser;

await this._supernodeService.syncCommunities();

Expand Down Expand Up @@ -172,7 +172,7 @@ export class DeviceManagementService extends LoggerProvider {
});

if (affectedRows > 0) {
const operator = this._req.user;
const operator = this._req.localUser;
await this._supernodeService.syncCommunities();

await this._auditService.log({
Expand All @@ -198,7 +198,7 @@ export class DeviceManagementService extends LoggerProvider {
});

if (affectedRows > 0) {
const operator = this._req.user;
const operator = this._req.localUser;
await this._supernodeService.syncCommunities();

await this._auditService.log({
Expand Down
9 changes: 2 additions & 7 deletions src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,15 @@ export class UserControllerV1 {
@UseGuards(AuthenticatedGuard)
@Get('me')
async me(@Req() req: Request) {
if (req.user instanceof UserModel) {
return req.user;
} else if (req.user?.sub /* OIDC */) {
return await this._userService.getByUniqueId(req.user.sub);
}
return {};
return req.localUser;
}

@ApiOperation({ summary: '更新自己的用户信息' })
@UseGuards(AuthenticatedGuard)
@UsePipes(new ValidationPipe({ transform: true }))
@Put('me')
async updateMe(@Req() req: Request, @Body() body: UpdateUserDto) {
const userId = req.user.id;
const userId = req.localUser.id;
return await this._userService.update(userId, body);
}

Expand Down
18 changes: 3 additions & 15 deletions src/modules/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,9 @@ export class UserService extends LoggerProvider {
return user;
}

public async getByUniqueId(uniqueId: string): Promise<UserModel> {
const user = await this._userModel.findOne({
where: {
uniqueId,
},
});
if (isNull(user)) {
throw new NotFoundException('User not found');
}
return user;
}

public async create(createUserDto: CreateUserDto): Promise<UserModel> {
const user = await this._userModel.create(Object.assign(createUserDto));
const operator = this._req.user;
const operator = this._req.localUser;
await this._auditService.log({
action: 'create',
resource: 'user',
Expand All @@ -90,7 +78,7 @@ export class UserService extends LoggerProvider {
limit: 1,
});
if (affectedRows > 0) {
const operator = this._req.user;
const operator = this._req.localUser;
await this._auditService.log({
action: 'create',
resource: 'user',
Expand All @@ -111,7 +99,7 @@ export class UserService extends LoggerProvider {
limit: 1,
});
if (affectedRows > 0) {
const operator = this._req.user;
const operator = this._req.localUser;
await this._auditService.log({
action: 'create',
resource: 'user',
Expand Down
1 change: 1 addition & 0 deletions src/utils/express.extend.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ declare namespace Express {
user:
| import('@/modules/user/entities/user.entity').User
| import('@/modules/user/dtos/oidc-user.dto').OidcUserDto;
localUser: import('@/modules/user/entities/user.entity').User;
}
}

0 comments on commit c7f2758

Please sign in to comment.