后端实现权限验证
This commit is contained in:
@@ -8,6 +8,7 @@ import {
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ListDto } from '../dto/admin-user/list.dto';
|
||||
import { CreateDto } from '../dto/admin-user/create.dto';
|
||||
@@ -15,8 +16,14 @@ import { UserService } from 'src/user/user.service';
|
||||
import { UpdateDto } from '../dto/admin-user/update.dto';
|
||||
import { UpdatePasswordDto } from '../dto/admin-user/update-password.dto';
|
||||
import { RemoveUserDto } from '../dto/admin-user/remove.dto';
|
||||
import { RolesGuard } from 'src/common/guard/roles.guard';
|
||||
import { Roles } from 'src/common/decorators/role.decorator';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Controller('admin/user')
|
||||
@UseGuards(AuthGuard('jwt'), RolesGuard)
|
||||
@Roles(Role.Admin)
|
||||
export class AdminUserController {
|
||||
constructor(private readonly userService: UserService) { }
|
||||
|
||||
|
||||
@@ -7,11 +7,18 @@ import {
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { CreateBlogDto } from 'src/admin/dto/admin-web/create-blog.dto';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import { BlogService } from 'src/blog/blog.service';
|
||||
import { Roles } from 'src/common/decorators/role.decorator';
|
||||
import { RolesGuard } from 'src/common/guard/roles.guard';
|
||||
|
||||
@Controller('/admin/web/blog')
|
||||
@UseGuards(AuthGuard('jwt'), RolesGuard)
|
||||
@Roles(Role.Admin)
|
||||
export class AdminWebBlogController {
|
||||
constructor(private readonly adminWebBlogService: BlogService) {}
|
||||
|
||||
|
||||
@@ -7,11 +7,18 @@ import {
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { CreateResourceDto } from 'src/admin/dto/admin-web/create-resource.dto';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import { Roles } from 'src/common/decorators/role.decorator';
|
||||
import { RolesGuard } from 'src/common/guard/roles.guard';
|
||||
import { ResourceService } from 'src/resource/resource.service';
|
||||
|
||||
@Controller('/admin/web/resource')
|
||||
@UseGuards(AuthGuard('jwt'), RolesGuard)
|
||||
@Roles(Role.Admin)
|
||||
export class AdminWebResourceController {
|
||||
constructor(private readonly resourceService: ResourceService) { }
|
||||
|
||||
|
||||
3
tone-page-server/src/auth/role.enum.ts
Normal file
3
tone-page-server/src/auth/role.enum.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export enum Role {
|
||||
Admin = 'admin',
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { UserSessionService } from 'src/user/services/user-session.service';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
constructor(
|
||||
private readonly userService: UserService,
|
||||
private readonly userSessionService: UserSessionService,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
@@ -28,9 +30,14 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
throw new UnauthorizedException('登录凭证已过期,请重新登录');
|
||||
}
|
||||
|
||||
const user = await this.userService.findById(userId);
|
||||
if (!user) {
|
||||
throw new BadRequestException('用户不存在');
|
||||
}
|
||||
|
||||
return {
|
||||
userId,
|
||||
sessionId,
|
||||
...user,
|
||||
sessionId
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const Permissions = (...permissions: string[]) =>
|
||||
SetMetadata('permissions', permissions);
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
|
||||
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
|
||||
export const Roles = (...roles: Role[]) => SetMetadata('roles', roles);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { CanActivate, ExecutionContext, Injectable, RequestTimeoutException } from '@nestjs/common';
|
||||
import { BadRequestException, CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import { User } from 'src/user/entities/user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
@@ -8,7 +10,7 @@ export class RolesGuard implements CanActivate {
|
||||
) { }
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>('roles', [
|
||||
const requiredRoles = this.reflector.getAllAndOverride<Role[] | undefined>('roles', [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
@@ -16,13 +18,16 @@ export class RolesGuard implements CanActivate {
|
||||
if (!requiredRoles) return true;
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const userId = request.user?.userId;
|
||||
const user = request.user as (User | void);
|
||||
|
||||
if (!userId) return false;
|
||||
if (!user) {
|
||||
throw new BadRequestException('服务器内部错误');
|
||||
}
|
||||
|
||||
// 查询用户拥有的有效角色Id TODO
|
||||
if (!requiredRoles.some(role => user.roles.includes(role))) {
|
||||
throw new ForbiddenException('权限不足');
|
||||
}
|
||||
|
||||
// return requiredRoles.some((role) => userRoleNames.includes(role));
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,3 +25,7 @@ export class UserSession {
|
||||
@DeleteDateColumn({ nullable: true, precision: 3 })
|
||||
deletedAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 考虑是否使用sessionId代替id,以节省存储空间
|
||||
*/
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Role } from 'src/auth/role.enum';
|
||||
import {
|
||||
BeforeInsert,
|
||||
Column,
|
||||
@@ -84,4 +85,7 @@ export class User {
|
||||
|
||||
@DeleteDateColumn({ nullable: true, precision: 3 })
|
||||
deletedAt: Date;
|
||||
|
||||
@Column('simple-array', { default: '' })
|
||||
roles: Role[];
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@ export class UserService {
|
||||
private readonly userRepository: Repository<User>,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* @deprecated 尽量不使用该方法
|
||||
*/
|
||||
async findOne(
|
||||
options: UserFindOptions | UserFindOptions[],
|
||||
additionalOptions?: { withDeleted?: boolean },
|
||||
@@ -33,6 +36,14 @@ export class UserService {
|
||||
});
|
||||
}
|
||||
|
||||
async findById(userId: string): Promise<User | null> {
|
||||
return this.userRepository.findOne({
|
||||
where: {
|
||||
userId,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async create(user: Partial<User>): Promise<User> {
|
||||
try {
|
||||
const newUser = this.userRepository.create(user);
|
||||
@@ -114,7 +125,7 @@ export class UserService {
|
||||
if (error.message.includes('IDX_user_phone')) {
|
||||
return '手机号已被使用';
|
||||
}
|
||||
return '数据已存在,请检查输入';
|
||||
return '该登陆方式异常,请更换其他登陆方式或联系管理员';
|
||||
}
|
||||
|
||||
async list(page = 1, pageSize = 20) {
|
||||
|
||||
@@ -54,6 +54,7 @@ export function NavUser({ }: {}) {
|
||||
);
|
||||
|
||||
if (!isLoading && !error && !user) {
|
||||
console.log(isLoading, error, user)
|
||||
router.replace('/console/login');
|
||||
localStorage.removeItem('token');
|
||||
toast.error('账户状态异常,请重新登录');
|
||||
|
||||
Reference in New Issue
Block a user