Heita common utilities for NestJS microservices - Authentication guards and decorators
npm install @chenwei83425/commonbash
npm install @heita/common
`
使用方式
$3
在 main.ts 中:
`typescript
import { AuthGuard } from '@heita/common';
import { Reflector } from '@nestjs/core';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 启用Cookie解析(必需)
app.use(cookieParser());
// 注册全局认证守卫
app.useGlobalGuards(new AuthGuard(app.get(Reflector)));
await app.listen(3000);
}
`
$3
`typescript
import { Public } from '@heita/common';
@Controller('auth')
export class AuthController {
@Public() // 跳过身份验证
@Post('login')
login() {
return { message: 'Login successful' };
}
@Get('profile') // 需要身份验证
getProfile() {
return { user: 'info' };
}
}
`
$3
`typescript
import { CurrentUser } from '@heita/common';
@Controller('users')
export class UserController {
@Get('me')
getCurrentUser(@CurrentUser() user: any) {
// user对象包含当前登录用户的完整信息
return user;
}
@Post('profile')
updateProfile(@CurrentUser() user: any, @Body() dto: UpdateProfileDto) {
console.log('当前用户ID:', user.id);
console.log('当前用户名:', user.username);
return this.userService.updateProfile(user.id, dto);
}
}
`
$3
在模块中注册服务:
`typescript
import { Module } from '@nestjs/common';
import { HeitaUserService } from '@heita/common';
@Module({
providers: [HeitaUserService],
exports: [HeitaUserService],
})
export class UserModule {}
`
在服务中使用:
`typescript
import { Injectable } from '@nestjs/common';
import { HeitaUserService } from '@heita/common';
@Injectable()
export class MyService {
constructor(private readonly heitaUserService: HeitaUserService) {}
async getUserList(token: string) {
// 获取用户列表
const users = await this.heitaUserService.getUserList({
pageNo: 1,
pageSize: 10,
username: 'test',
}, token);
return users;
}
async getUserById(userId: string, token: string) {
// 根据ID获取用户
const user = await this.heitaUserService.getUserById(userId, token);
return user;
}
async getUsersByDepartment(departId: string, token: string) {
// 根据部门获取用户
const users = await this.heitaUserService.getUsersByDepartment(departId, token);
return users;
}
}
`
在Controller中结合使用:
`typescript
import { Controller, Get, Req } from '@nestjs/common';
import { HeitaUserService, CurrentUser } from '@heita/common';
@Controller('users')
export class UserController {
constructor(private readonly heitaUserService: HeitaUserService) {}
@Get('list')
async getUserList(@Req() request: Request) {
// 从请求中获取token
const token = request.cookies?.['X-Access-Token'];
return this.heitaUserService.getUserList({ pageNo: 1, pageSize: 10 }, token);
}
@Get('current')
async getCurrentUserInfo(@CurrentUser() user: any, @Req() request: Request) {
// 方式1: 直接使用@CurrentUser装饰器获取(推荐)
return user;
// 方式2: 通过服务获取最新信息
const token = request.cookies?.['X-Access-Token'];
return this.heitaUserService.getCurrentUser(token);
}
}
`
$3
`typescript
import { EXCLUDE_URLS } from '@heita/common';
// 添加自定义排除URL
EXCLUDE_URLS.push('/custom/public/**');
`
认证方式
$3
1. Cookie中的X-Access-Token(微服务共享)
2. Header中的X-Access-Token(本地调试)
3. Query参数中的token(文件预览)
$3
AuthGuard在验证Token后会自动:
1. 调用黑塔用户中心验证Token
2. 获取用户完整信息
3. 将用户信息注入到request.user
4. 可通过@CurrentUser()装饰器直接获取
$3
`bash
使用Header
curl -H "X-Access-Token: your_token" http://localhost:3000/api/users
使用Cookie
curl --cookie "X-Access-Token=your_token" http://localhost:3000/api/users
`
配置
$3
`typescript
app.enableCors({
origin: true,
credentials: true, // 允许携带Cookie
});
`
$3
`env
黑塔API地址(可选,默认为 https://saas.btitib.com)
HEITA_API_URL=https://saas.btitib.com
`
$3
默认采用调用黑塔用户中心验证策略。
如需自定义验证,可以扩展AuthGuard类:
`typescript
import { AuthGuard } from '@heita/common';
@Injectable()
export class CustomAuthGuard extends AuthGuard {
protected async validateToken(token: string, request: Request): Promise {
// 自定义验证逻辑
// 返回用户对象表示验证成功,返回null表示验证失败
return await this.authService.verify(token);
}
}
`
API
$3
认证守卫类,拦截所有请求进行Token验证并自动获取用户信息。
$3
装饰器,标记不需要验证的路由。
$3
装饰器,获取当前登录用户信息。
$3
黑塔用户服务类,提供以下方法:
- getCurrentUser(token: string) - 获取当前登录用户信息
- getUserById(userId: string, token: string) - 根据ID获取用户
- getUserList(params, token: string) - 获取用户列表
- getUsersByDepartment(departId: string, token: string) - 根据部门获取用户
$3
URL白名单数组,可以添加自定义排除路径。
$3
文件扩展名白名单数组,自动放行静态资源。
发布到npm
`bash
登录npm(首次)
npm login
构建
npm run build
发布
npm publish --access public
``