All files / lib/supabase/services auth.ts

98.98% Statements 98/99
91.66% Branches 33/36
92.3% Functions 12/13
98.98% Lines 98/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463                                                                                                                                                          16x                                     16x 8x     8x 66x 5x                 3x                   16x 15x 8x             7x                                             5x   5x 5x         4x 1x 1x     3x 2x             1x 1x   1x 1x                                                   6x   6x   6x   6x                     5x 1x 1x           4x 1x               3x 2x 2x             1x 1x   1x 1x                       3x   3x 3x   2x 1x 1x     1x 1x   1x 1x                       4x 4x   3x 1x     2x   1x                       3x 3x   2x 1x     1x   1x                           4x   4x 4x   3x 1x 1x     2x 1x             1x 1x   1x 1x                       3x   3x   3x   3x       2x 1x 1x     1x 1x   1x 1x                       3x   3x 3x       2x 1x 1x     1x 1x   1x 1x                                                                   2x       2x 1x           16x      
/**
 * Supabase 认证服务
 *
 * - 统一的错误处理和响应格式
 * - TypeScript 类型安全
 * - 自动 Session 管理
 */
 
import { supabase } from '../client';
import { logger } from '../helpers';
 
import type { AuthError, Session, User as SupabaseUser } from '@supabase/supabase-js';
 
// ==================== 类型定义 ====================
 
/**
 * 认证响应类型
 */
export interface AuthResponse<T = unknown> {
  data: T | null;
  error: AuthErrorDetail | null;
  success: boolean;
}
 
/**
 * 认证错误详情
 */
export interface AuthErrorDetail {
  message: string;
  code?: string;
  status?: number;
}
 
/**
 * 登录参数
 */
export interface LoginParams {
  email: string;
  password: string;
}
 
/**
 * 注册参数
 */
export interface RegisterParams {
  email: string;
  password: string;
  username: string;
}
 
/**
 * 登录/注册成功响应
 */
export interface AuthSuccessData {
  user: SupabaseUser;
  session: Session;
}
 
/**
 * 密码重置参数
 */
export interface ResetPasswordParams {
  email: string;
}
 
/**
 * 更新密码参数
 */
export interface UpdatePasswordParams {
  newPassword: string;
}
 
// ==================== 错误处理 ====================
 
/**
 * 认证错误消息映射(中文本地化)
 */
const AUTH_ERROR_MESSAGES: Record<string, string> = {
  'Invalid login credentials': '邮箱或密码错误',
  'Email not confirmed': '邮箱尚未验证,请检查邮箱并点击验证链接',
  'User already registered': '该邮箱已被注册',
  'Password should be at least 6 characters': '密码至少需要6个字符',
  'Unable to validate email address: invalid format': '邮箱格式不正确',
  'Email rate limit exceeded': '请求过于频繁,请稍后再试',
  'For security purposes, you can only request this once every 60 seconds':
    '出于安全考虑,每60秒只能请求一次',
  'New password should be different from the old password': '新密码不能与旧密码相同',
  'Auth session missing!': '登录已过期,请重新登录',
  'JWT expired': '登录已过期,请重新登录',
  'Invalid Refresh Token': '登录已过期,请重新登录',
  'Refresh Token Not Found': '登录已过期,请重新登录',
};
 
/**
 * 转换 Supabase Auth 错误为用户友好消息
 */
const translateAuthError = (error: AuthError): AuthErrorDetail => {
  const message = error.message || '认证失败';
 
  // 查找匹配的错误消息
  for (const [key, value] of Object.entries(AUTH_ERROR_MESSAGES)) {
    if (message.includes(key)) {
      return {
        message: value,
        code: error.code,
        status: error.status,
      };
    }
  }
 
  // 默认返回原始消息
  return {
    message,
    code: error.code,
    status: error.status,
  };
};
 
/**
 * 包装认证响应
 */
const wrapAuthResponse = <T>(data: T | null, error: AuthError | null): AuthResponse<T> => {
  if (error) {
    return {
      data: null,
      error: translateAuthError(error),
      success: false,
    };
  }
 
  return {
    data,
    error: null,
    success: true,
  };
};
 
// ==================== 认证服务 ====================
 
class SupabaseAuthService {
  /**
   * 用户登录
   *
   * @param params - 登录参数 { email, password }
   * @returns AuthResponse<AuthSuccessData>
   *
   * @example
   * const { data, error } = await supabaseAuthService.login({
   *   email: 'user@example.com',
   *   password: 'password123'
   * });
   */
  async login(params: LoginParams): Promise<AuthResponse<AuthSuccessData>> {
    logger.query('auth', 'login', { email: params.email });
 
    try {
      const { data, error } = await supabase.auth.signInWithPassword({
        email: params.email,
        password: params.password,
      });
 
      if (error) {
        logger.error('auth', 'login', error);
        return wrapAuthResponse<AuthSuccessData>(null, error);
      }
 
      if (!data.user || !data.session) {
        return {
          data: null,
          error: { message: '登录失败,请重试' },
          success: false,
        };
      }
 
      logger.success('auth', 'login');
      return wrapAuthResponse({ user: data.user, session: data.session }, null);
    } catch (err) {
      logger.error('auth', 'login', err);
      return {
        data: null,
        error: { message: String(err) },
        success: false,
      };
    }
  }
 
  /**
   * 用户注册
   *
   * @param params - 注册参数 { email, password, username }
   * @returns AuthResponse<AuthSuccessData | null>
   *
   * 注意:如果启用了邮箱验证,session 可能为 null
   *
   * @example
   * const { data, error } = await supabaseAuthService.register({
   *   email: 'user@example.com',
   *   password: 'password123',
   *   username: 'myusername'
   * });
   */
  async register(
    params: RegisterParams
  ): Promise<AuthResponse<AuthSuccessData | { user: SupabaseUser; session: null }>> {
    logger.query('auth', 'register', { email: params.email, username: params.username });
 
    try {
      // 构造重定向 URL - 开发环境使用 exp://,生产环境使用 petlove://
      const redirectUrl = __DEV__ ? 'exp://127.0.0.1:8081' : 'petlove://';
 
      const { data, error } = await supabase.auth.signUp({
        email: params.email,
        password: params.password,
        options: {
          data: {
            username: params.username,
          },
          emailRedirectTo: redirectUrl,
        },
      });
 
      if (error) {
        logger.error('auth', 'register', error);
        return wrapAuthResponse<AuthSuccessData | { user: SupabaseUser; session: null }>(
          null,
          error
        );
      }
 
      if (!data.user) {
        return {
          data: null,
          error: { message: '注册失败,请重试' },
          success: false,
        };
      }
 
      // 如果需要邮箱验证,session 为 null
      if (!data.session) {
        logger.success('auth', 'register (需要邮箱验证)');
        return {
          data: { user: data.user, session: null },
          error: null,
          success: true,
        };
      }
 
      logger.success('auth', 'register');
      return wrapAuthResponse({ user: data.user, session: data.session }, null);
    } catch (err) {
      logger.error('auth', 'register', err);
      return {
        data: null,
        error: { message: String(err) },
        success: false,
      };
    }
  }
 
  /**
   * 用户登出
   */
  async logout(): Promise<AuthResponse<void>> {
    logger.query('auth', 'logout');
 
    try {
      const { error } = await supabase.auth.signOut();
 
      if (error) {
        logger.error('auth', 'logout', error);
        return wrapAuthResponse<void>(null, error);
      }
 
      logger.success('auth', 'logout');
      return { data: undefined, error: null, success: true };
    } catch (err) {
      logger.error('auth', 'logout', err);
      return {
        data: null,
        error: { message: String(err) },
        success: false,
      };
    }
  }
 
  /**
   * 获取当前 Session
   */
  async getSession(): Promise<AuthResponse<Session>> {
    try {
      const { data, error } = await supabase.auth.getSession();
 
      if (error) {
        return wrapAuthResponse<Session>(null, error);
      }
 
      return wrapAuthResponse(data.session, null);
    } catch (err) {
      return {
        data: null,
        error: { message: String(err) },
        success: false,
      };
    }
  }
 
  /**
   * 获取当前用户
   */
  async getCurrentUser(): Promise<AuthResponse<SupabaseUser>> {
    try {
      const { data, error } = await supabase.auth.getUser();
 
      if (error) {
        return wrapAuthResponse<SupabaseUser>(null, error);
      }
 
      return wrapAuthResponse(data.user, null);
    } catch (err) {
      return {
        data: null,
        error: { message: String(err) },
        success: false,
      };
    }
  }
 
  /**
   * 刷新 Session
   *
   * Supabase SDK 会自动刷新,此方法用于手动刷新
   */
  async refreshSession(): Promise<AuthResponse<Session>> {
    logger.query('auth', 'refreshSession');
 
    try {
      const { data, error } = await supabase.auth.refreshSession();
 
      if (error) {
        logger.error('auth', 'refreshSession', error);
        return wrapAuthResponse<Session>(null, error);
      }
 
      if (!data.session) {
        return {
          data: null,
          error: { message: '刷新失败,请重新登录' },
          success: false,
        };
      }
 
      logger.success('auth', 'refreshSession');
      return wrapAuthResponse(data.session, null);
    } catch (err) {
      logger.error('auth', 'refreshSession', err);
      return {
        data: null,
        error: { message: String(err) },
        success: false,
      };
    }
  }
 
  /**
   * 发送密码重置邮件
   */
  async resetPassword(params: ResetPasswordParams): Promise<AuthResponse<void>> {
    logger.query('auth', 'resetPassword', { email: params.email });
 
    try {
      // 构造重定向 URL - 开发环境使用 exp://,生产环境使用 petlove://
      const redirectUrl = __DEV__ ? 'exp://127.0.0.1:8081' : 'petlove://';
 
      const { error } = await supabase.auth.resetPasswordForEmail(params.email, {
        redirectTo: redirectUrl,
      });
 
      if (error) {
        logger.error('auth', 'resetPassword', error);
        return wrapAuthResponse<void>(null, error);
      }
 
      logger.success('auth', 'resetPassword');
      return { data: undefined, error: null, success: true };
    } catch (err) {
      logger.error('auth', 'resetPassword', err);
      return {
        data: null,
        error: { message: String(err) },
        success: false,
      };
    }
  }
 
  /**
   * 更新密码(需要已登录)
   */
  async updatePassword(params: UpdatePasswordParams): Promise<AuthResponse<SupabaseUser>> {
    logger.query('auth', 'updatePassword');
 
    try {
      const { data, error } = await supabase.auth.updateUser({
        password: params.newPassword,
      });
 
      if (error) {
        logger.error('auth', 'updatePassword', error);
        return wrapAuthResponse<SupabaseUser>(null, error);
      }
 
      logger.success('auth', 'updatePassword');
      return wrapAuthResponse(data.user, null);
    } catch (err) {
      logger.error('auth', 'updatePassword', err);
      return {
        data: null,
        error: { message: String(err) },
        success: false,
      };
    }
  }
 
  /**
   * 监听认证状态变化
   *
   * @param callback - 状态变化回调
   * @returns 取消订阅函数
   *
   * @example
   * const unsubscribe = supabaseAuthService.onAuthStateChange((event, session) => {
   *   if (event === 'SIGNED_IN') {
   *     console.log('用户已登录', session?.user);
   *   } else if (event === 'SIGNED_OUT') {
   *     console.log('用户已登出');
   *   }
   * });
   *
   * // 清理时调用
   * unsubscribe();
   */
  onAuthStateChange(
    callback: (
      event: 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED',
      session: Session | null
    ) => void
  ): () => void {
    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange((event, session) => {
      callback(event as any, session);
    });
 
    return () => {
      subscription.unsubscribe();
    };
  }
}
 
// 导出单例
export const supabaseAuthService = new SupabaseAuthService();
 
export default supabaseAuthService;