You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

123 lines
2.5 KiB

/**
* 认证服务
* 处理登录、注册等认证相关的 API 请求
*/
import { request } from '@/src/utils/network/api';
import type {
LoginFormData,
RegisterFormData,
ForgotPasswordFormData,
ResetPasswordFormData,
ChangePasswordFormData,
PhoneLoginFormData,
} from '@/src/schemas/auth';
import type { User } from '@/src/schemas/user';
/**
* API 响应接口
*/
interface ApiResponse<T = any> {
code: number;
message: string;
data: T;
}
/**
* 登录响应
*/
interface LoginResponse {
user: User;
token: string;
refreshToken?: string;
}
/**
* 认证服务类
*/
class AuthService {
/**
* 邮箱登录
*/
async login(data: LoginFormData): Promise<LoginResponse> {
const response = await request.post<ApiResponse<LoginResponse>>('/auth/login', data);
return response.data;
}
/**
* 手机号登录
*/
async phoneLogin(data: PhoneLoginFormData): Promise<LoginResponse> {
const response = await request.post<ApiResponse<LoginResponse>>('/auth/phone-login', data);
return response.data;
}
/**
* 注册
*/
async register(data: RegisterFormData): Promise<LoginResponse> {
const response = await request.post<ApiResponse<LoginResponse>>('/auth/register', data);
return response.data;
}
/**
* 登出
*/
async logout(): Promise<void> {
await request.post('/auth/logout');
}
/**
* 发送忘记密码邮件
*/
async forgotPassword(data: ForgotPasswordFormData): Promise<void> {
await request.post('/auth/forgot-password', data);
}
/**
* 重置密码
*/
async resetPassword(data: ResetPasswordFormData): Promise<void> {
await request.post('/auth/reset-password', data);
}
/**
* 修改密码
*/
async changePassword(data: ChangePasswordFormData): Promise<void> {
await request.post('/auth/change-password', data);
}
/**
* 发送验证码
*/
async sendVerificationCode(phone: string): Promise<void> {
await request.post('/auth/send-code', { phone });
}
/**
* 刷新 token
*/
async refreshToken(refreshToken: string): Promise<{ token: string }> {
const response = await request.post<ApiResponse<{ token: string }>>('/auth/refresh-token', {
refreshToken,
});
return response.data;
}
/**
* 验证 token 是否有效
*/
async verifyToken(): Promise<boolean> {
try {
await request.get('/auth/verify-token');
return true;
} catch {
return false;
}
}
}
// 导出单例
export const authService = new AuthService();
export default authService;