Some checks reported errors
continuous-integration/drone/push Build was killed
- 搭建 api、auth、utils 等逻辑模块 - 通过 tsc、eslint、vitest 测试验证 BREAKING CHANGE: 新镜像分支
217 lines
5.3 KiB
Markdown
217 lines
5.3 KiB
Markdown
# 认证模块
|
||
|
||
## 概述
|
||
|
||
认证模块提供基于Session的认证机制,支持用户登录、注册、登出和会话管理功能。该模块采用适配器模式,支持多种存储方式(Cookie、LocalStorage、内存),以适应不同的运行环境(浏览器、SSR等)。
|
||
|
||
## 核心组件
|
||
|
||
### 1. 认证服务 (AuthService)
|
||
|
||
`AuthService` 接口定义了认证相关的核心功能:
|
||
|
||
- `login(credentials)`: 用户登录
|
||
- `register(userData)`: 用户注册
|
||
- `logout()`: 用户登出
|
||
- `isAuthenticated()`: 检查是否已认证
|
||
- `getCurrentUser()`: 获取当前用户信息
|
||
- `refreshSession()`: 刷新会话
|
||
- `getSession()`: 获取会话信息
|
||
|
||
### 2. 会话管理器 (SessionManager)
|
||
|
||
`SessionManager` 负责管理用户会话状态,包括:
|
||
|
||
- 会话的创建、验证、刷新和清除
|
||
- 用户信息的获取和缓存
|
||
- 会话状态的持久化存储
|
||
|
||
### 3. 存储适配器 (StorageAdapter)
|
||
|
||
`StorageAdapter` 提供统一的存储接口,支持多种存储方式:
|
||
|
||
- `CookieStorageAdapter`: 使用Cookie存储,适用于SSR环境
|
||
- `LocalStorageAdapter`: 使用浏览器LocalStorage存储
|
||
- `MemoryStorageAdapter`: 使用内存存储,适用于测试或临时会话
|
||
|
||
### 4. 事件管理器 (EventManager)
|
||
|
||
`EventManager` 负责管理认证相关事件:
|
||
|
||
- 登录事件 (`login`)
|
||
- 注册事件 (`register`)
|
||
- 登出事件 (`logout`)
|
||
- 错误事件 (`error`)
|
||
|
||
### 5. 类型定义
|
||
|
||
模块包含完整的TypeScript类型定义,确保类型安全。
|
||
|
||
## 使用方法
|
||
|
||
### 基本使用
|
||
|
||
```typescript
|
||
import { authService } from '@/auth';
|
||
|
||
// 用户登录
|
||
const loginResult = await authService.login({
|
||
username: 'user@example.com',
|
||
password: 'password123'
|
||
});
|
||
|
||
if (loginResult.success) {
|
||
console.log('登录成功', loginResult.data);
|
||
} else {
|
||
console.error('登录失败', loginResult.error);
|
||
}
|
||
|
||
// 检查认证状态
|
||
if (await authService.isAuthenticated()) {
|
||
// 获取当前用户信息
|
||
const userResult = await authService.getCurrentUser();
|
||
if (userResult.success) {
|
||
console.log('当前用户:', userResult.data);
|
||
}
|
||
}
|
||
|
||
// 用户登出
|
||
await authService.logout();
|
||
```
|
||
|
||
### 测试环境使用
|
||
|
||
```typescript
|
||
import { getAuthService, resetAuthService } from '@/auth';
|
||
|
||
// 在测试前重置服务实例
|
||
resetAuthService();
|
||
|
||
// 获取新的服务实例
|
||
const authService = getAuthService();
|
||
```
|
||
|
||
### 自定义存储方式
|
||
|
||
```typescript
|
||
import { createStorageAdapter } from '@/auth';
|
||
|
||
// 创建自定义存储适配器
|
||
const customStorage = createStorageAdapter('localStorage');
|
||
|
||
// 注意:当前版本使用单例模式,自定义存储需要修改auth-service.ts中的实现
|
||
```
|
||
|
||
### 使用自定义存储适配器
|
||
|
||
```typescript
|
||
import { createAuthService, createStorageAdapter } from '@/auth';
|
||
|
||
// 创建自定义Cookie存储适配器
|
||
const cookieStorage = createStorageAdapter('cookie', {
|
||
domain: '.example.com',
|
||
secure: true,
|
||
httpOnly: false,
|
||
sameSite: 'strict'
|
||
});
|
||
|
||
// 使用自定义存储适配器
|
||
const authService = createAuthService(undefined, cookieStorage);
|
||
```
|
||
|
||
### 事件监听
|
||
|
||
```typescript
|
||
import { createAuthService, createEventManager } from '@/auth';
|
||
|
||
const eventManager = createEventManager();
|
||
const authService = createAuthService();
|
||
|
||
// 监听登录事件
|
||
eventManager.on('login', (data) => {
|
||
console.log('用户登录:', data.user);
|
||
});
|
||
|
||
// 监听登出事件
|
||
eventManager.on('logout', () => {
|
||
console.log('用户已登出');
|
||
});
|
||
```
|
||
|
||
## 会话管理
|
||
|
||
### 会话存储
|
||
|
||
会话信息通过StorageAdapter存储,默认使用Cookie存储,以支持SSR环境。会话信息包括:
|
||
|
||
- `sessionId`: 会话ID
|
||
- `userId`: 用户ID
|
||
- `expiresAt`: 过期时间
|
||
- `createdAt`: 创建时间
|
||
|
||
### 会话验证
|
||
|
||
SessionManager会自动验证会话的有效性:
|
||
|
||
1. 检查本地是否存在会话ID
|
||
2. 验证会话是否过期
|
||
3. 向服务器验证会话有效性
|
||
4. 自动刷新过期会话
|
||
|
||
### 会话刷新
|
||
|
||
当会话即将过期时,SessionManager会自动尝试刷新会话:
|
||
|
||
1. 使用当前会话ID请求刷新
|
||
2. 更新本地存储的会话信息
|
||
3. 清除缓存的用户信息,下次获取时重新请求
|
||
|
||
## API端点
|
||
|
||
认证模块需要以下API端点:
|
||
|
||
- `POST /auth/login`: 用户登录
|
||
- `POST /auth/register`: 用户注册
|
||
- `POST /auth/logout`: 用户登出
|
||
- `GET /auth/session/:sessionId`: 获取会话信息
|
||
- `POST /auth/session/refresh`: 刷新会话
|
||
- `GET /auth/user/:userId`: 获取用户信息
|
||
|
||
## 设计模式
|
||
|
||
认证模块采用以下设计模式:
|
||
|
||
1. **适配器模式**: 通过StorageAdapter接口支持多种存储方式
|
||
2. **工厂模式**: 提供createAuthService等工厂函数简化实例创建
|
||
3. **观察者模式**: 通过EventManager实现事件发布订阅
|
||
4. **策略模式**: 不同存储方式采用不同策略
|
||
|
||
## 安全考虑
|
||
|
||
1. **会话安全**: 使用HttpOnly Cookie存储会话ID,防止XSS攻击
|
||
2. **CSRF防护**: 通过SameSite Cookie属性防止CSRF攻击
|
||
3. **会话过期**: 设置合理的会话过期时间,并支持自动刷新
|
||
4. **HTTPS**: 在生产环境中使用HTTPS传输敏感数据
|
||
|
||
## SSR支持
|
||
|
||
认证模块完全支持SSR环境:
|
||
|
||
1. 默认使用Cookie存储,可在服务器端读取
|
||
2. 提供统一的StorageAdapter接口,可针对不同环境实现
|
||
3. 会话状态可在服务器和客户端之间同步
|
||
|
||
## 测试
|
||
|
||
认证模块包含完整的单元测试,覆盖:
|
||
|
||
- 会话管理功能
|
||
- 存储适配器功能
|
||
- 认证服务功能
|
||
- 错误处理
|
||
|
||
运行测试:
|
||
|
||
```bash
|
||
npm test auth
|
||
``` |