feat: 微信登录与认证完善 + 一键 docker compose 启动

登录流程(以 openid 为唯一标识):
- auth.service.login 改为 upsert:openid 在库续登,不在库自动建用户签 token
- 个人主体无 getPhoneNumber 权限,故不强制手机号注册;register 接口保留备未来用
- wechat.service 新增 getAccessToken(Redis 缓存)、getPluginOpenPid、getUserPhoneNumber
- 新增 /api/wechat/plugin-openpid、/api/wechat/phone 接口

schema 与迁移:
- User 增加 openpid(可空唯一) 兼容插件场景;openid 保持必填主键
- 新增 add_openpid_optional_openid、openid_required_primary 迁移

部署:
- docker-compose.yml 改为 docker compose up -d 一键启动 postgres+redis+app
- app 容器内用服务名连 db/redis,启动自动跑 prisma migrate deploy
- 端口统一 3090(Dockerfile EXPOSE、compose 映射同步)
- 新增 docs/wechat-api-signature-guide.md API 签名手册

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-05 21:21:09 +08:00
co-authored by Claude Fable 5
parent deaa0c9ce4
commit 1d946046d2
19 changed files with 498 additions and 39 deletions
+62 -14
View File
@@ -1,13 +1,18 @@
import { Inject, Injectable } from '@nestjs/common';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Redis } from 'ioredis';
import { randomBytes } from 'crypto';
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';
import { LoginDto, RegisterDto } from './dto/login.dto';
// session_key 在 Redis 的存储键与默认有效期(微信 session_key 约 30 天,这里保守用 7 天)
// 注册凭证(registerTicket在 Redis 的存储键与有效期
const REG_TICKET_TTL = 10 * 60; // 10 分钟
// session_key 在 Redis 的存储键与有效期
const SESSION_KEY_TTL = 7 * 24 * 60 * 60;
@Injectable()
@@ -21,18 +26,24 @@ export class AuthService {
) {}
/**
* 微信小程序登录核心流程:
* 1. 用前端 code 调微信 code2Session 换 openid + session_key(不信任任何前端 openid
* 2. findOrCreate 用户
* 3. session_key 存 Redis(供后续解密 encryptedData / phone
* 4. 签发自有 JWT 返回
* 登录:以 openid 为唯一标识,自动注册/续登。
* 用前端 wx.login() 的 code openid(不信任前端传的任何 openid
* - openid 已存在 -> 直接签发 token(后续登录)
* - openid 不存在 -> 用 openid 建用户后签发 token(首次登录,无需手机号
*
* 说明:个人主体小程序无 getPhoneNumber 权限,故不强制手机号注册。
* 手机号采集留作未来换企业主体后可选补充(见 register())。
*/
async login(code: string): Promise<{ accessToken: string }> {
const session = await this.wechat.code2Session(code);
async login(dto: LoginDto): Promise<{ accessToken: string }> {
const session = await this.wechat.code2Session(dto.code);
const user = await this.users.findOrCreateByOpenid(session.openid, session.unionid);
// upsertopenid 在库则续登,不在库则直接建用户(无需手机号)
const user = await this.users.findOrCreateByOpenid(
session.openid,
session.unionid,
);
// 缓存 session_keykey 形如 wx:session:{userId}
// 缓存 session_key(供后续解密 encryptedData / 数据签名校验)
await this.redis.set(
`wx:session:${user.id}`,
session.sessionKey,
@@ -40,14 +51,51 @@ export class AuthService {
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'),
const accessToken = await this.signToken(user.id, user.openid);
return { accessToken };
}
/**
* 首次注册:用 registerTicket 换回 openid,验证手机号后创建用户并签发 token。
* 手机号非空即视为注册完成。
*/
async register(dto: RegisterDto): Promise<{ accessToken: string }> {
const key = `wx:reg_ticket:${dto.registerTicket}`;
const raw = await this.redis.get(key);
if (!raw) {
throw new UnauthorizedException('注册凭证无效或已过期,请重新登录');
}
const ticket = JSON.parse(raw) as {
openid: string;
sessionKey?: string;
unionid?: string | null;
};
// 验证手机号;传 openid 让微信校验 code-openid 绑定关系,防串号
const phone = await this.wechat.getUserPhoneNumber(dto.phoneCode, ticket.openid);
const user = await this.users.createWithOpenid(ticket.openid, {
phone: phone.purePhoneNumber,
nickname: dto.nickname,
avatar: dto.avatar,
unionid: ticket.unionid ?? undefined,
});
// 一次性凭证,用完即弃
await this.redis.del(key);
const accessToken = await this.signToken(user.id, user.openid);
return { accessToken };
}
/** 签发 JWTpayload 携带 userId(sub) 与 openid */
private async signToken(userId: string, openid: string): Promise<string> {
const payload: JwtPayload = { sub: userId, openid };
return this.jwt.signAsync(payload, {
expiresIn: this.config.get<number>('jwt.expires'),
});
}
/** 取出缓存的 session_key(供解密小程序加密数据用) */
async getSessionKey(userId: string): Promise<string | null> {
return this.redis.get(`wx:session:${userId}`);