Files
wxmp_backend/src/auth/auth.service.ts
T
broccoliandClaude Fable 5 deaa0c9ce4 feat: 初始化微信小程序后端骨架
- NestJS + TypeScript + Prisma + PostgreSQL 工程骨架
- 微信登录安全流程:服务端 code2Session 换 openid 后签发 JWT,
  session_key 缓存于 Redis,不信任前端 openid
- 统一响应/异常处理、JWT 全局鉴权(@Public 豁免)、Swagger 文档
- Prisma 全量核心 schema(用户/分类/商品/设计清单/地址/订单/支付/上传/定制任务)+ seed
- 业务模块空壳(商品/分类/设计清单/地址/订单/支付/上传/BullMQ 队列)
- Docker 多阶段镜像 + 本地/生产 docker-compose
- docs:密钥获取指南、COS SDK 移除记录

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 17:33:50 +08:00

56 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Inject, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Redis } from 'ioredis';
import { REDIS_CLIENT } from '../redis/redis.module';
import { JwtPayload } from '../common/decorators/current-user.decorator';
import { UsersService } from '../users/users.service';
import { WechatService } from '../wechat/wechat.service';
// session_key 在 Redis 的存储键与默认有效期(微信 session_key 约 30 天,这里保守用 7 天)
const SESSION_KEY_TTL = 7 * 24 * 60 * 60;
@Injectable()
export class AuthService {
constructor(
private readonly wechat: WechatService,
private readonly users: UsersService,
private readonly jwt: JwtService,
private readonly config: ConfigService,
@Inject(REDIS_CLIENT) private readonly redis: Redis,
) {}
/**
* 微信小程序登录核心流程:
* 1. 用前端 code 调微信 code2Session 换 openid + session_key(不信任任何前端 openid
* 2. findOrCreate 用户
* 3. session_key 存 Redis(供后续解密 encryptedData / phone
* 4. 签发自有 JWT 返回
*/
async login(code: string): Promise<{ accessToken: string }> {
const session = await this.wechat.code2Session(code);
const user = await this.users.findOrCreateByOpenid(session.openid, session.unionid);
// 缓存 session_keykey 形如 wx:session:{userId}
await this.redis.set(
`wx:session:${user.id}`,
session.sessionKey,
'EX',
SESSION_KEY_TTL,
);
const payload: JwtPayload = { sub: user.id, openid: user.openid };
const accessToken = await this.jwt.signAsync(payload, {
expiresIn: this.config.get<number>('jwt.expires'),
});
return { accessToken };
}
/** 取出缓存的 session_key(供解密小程序加密数据用) */
async getSessionKey(userId: string): Promise<string | null> {
return this.redis.get(`wx:session:${userId}`);
}
}