npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@chenwei83425/common

v1.0.5

Published

Heita common utilities for NestJS microservices - Authentication guards and decorators

Readme

@heita/common

黑塔NestJS微服务通用工具包 - 认证守卫、装饰器和用户服务

功能特性

  • AuthGuard - 微服务共享认证守卫(自动获取用户信息)
  • @Public装饰器 - 跳过身份验证
  • @CurrentUser装饰器 - 获取当前登录用户
  • HeitaUserService - 黑塔用户服务(获取用户列表等)
  • URL白名单配置 - 灵活的排除规则

安装

npm install @heita/common

使用方式

1. 启用全局守卫

main.ts 中:

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);
}

2. 使用@Public装饰器

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. 使用@CurrentUser装饰器获取当前用户

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);
  }
}

4. 使用HeitaUserService获取用户信息

在模块中注册服务:

import { Module } from '@nestjs/common';
import { HeitaUserService } from '@heita/common';

@Module({
  providers: [HeitaUserService],
  exports: [HeitaUserService],
})
export class UserModule {}

在服务中使用:

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中结合使用:

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);
  }
}

5. 自定义排除URL

import { EXCLUDE_URLS } from '@heita/common';

// 添加自定义排除URL
EXCLUDE_URLS.push('/custom/public/**');

认证方式

Token提取优先级

  1. Cookie中的X-Access-Token(微服务共享)
  2. Header中的X-Access-Token(本地调试)
  3. Query参数中的token(文件预览)

用户信息自动注入

AuthGuard在验证Token后会自动:

  1. 调用黑塔用户中心验证Token
  2. 获取用户完整信息
  3. 将用户信息注入到request.user
  4. 可通过@CurrentUser()装饰器直接获取

本地调试

# 使用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

配置

CORS设置

app.enableCors({
  origin: true,
  credentials: true, // 允许携带Cookie
});

环境变量

# 黑塔API地址(可选,默认为 https://saas.btitib.com)
HEITA_API_URL=https://saas.btitib.com

Token验证策略

默认采用调用黑塔用户中心验证策略。

如需自定义验证,可以扩展AuthGuard类:

import { AuthGuard } from '@heita/common';

@Injectable()
export class CustomAuthGuard extends AuthGuard {
  protected async validateToken(token: string, request: Request): Promise<any> {
    // 自定义验证逻辑
    // 返回用户对象表示验证成功,返回null表示验证失败
    return await this.authService.verify(token);
  }
}

API

AuthGuard

认证守卫类,拦截所有请求进行Token验证并自动获取用户信息。

@Public()

装饰器,标记不需要验证的路由。

@CurrentUser()

装饰器,获取当前登录用户信息。

HeitaUserService

黑塔用户服务类,提供以下方法:

  • getCurrentUser(token: string) - 获取当前登录用户信息
  • getUserById(userId: string, token: string) - 根据ID获取用户
  • getUserList(params, token: string) - 获取用户列表
  • getUsersByDepartment(departId: string, token: string) - 根据部门获取用户

EXCLUDE_URLS

URL白名单数组,可以添加自定义排除路径。

EXCLUDE_EXTENSIONS

文件扩展名白名单数组,自动放行静态资源。

发布到npm

# 登录npm(首次)
npm login

# 构建
npm run build

# 发布
npm publish --access public

License

MIT