AuthServiceProtocol.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import Foundation
  2. /// Result enum representing outcomes of authentication operations.
  3. enum AuthResult<T> {
  4. case success(T)
  5. case failure(AuthError)
  6. }
  7. /// Errors that can occur during authentication operations.
  8. enum AuthError: Error, LocalizedError, Equatable {
  9. case invalidInput(String)
  10. case userAlreadyExists
  11. case invalidCredentials
  12. case userNotFound
  13. case incorrectPassword
  14. case storageError
  15. case networkError(String)
  16. var errorDescription: String? {
  17. switch self {
  18. case .invalidInput(let reason):
  19. return reason
  20. case .userAlreadyExists:
  21. return "账号已存在,请直接登录"
  22. case .invalidCredentials:
  23. return "账号或密码错误"
  24. case .userNotFound:
  25. return "未找到对应账号"
  26. case .incorrectPassword:
  27. return "原密码校验错误"
  28. case .storageError:
  29. return "本地存储操作异常"
  30. case .networkError(let msg):
  31. return "网络连接失败: \(msg)"
  32. }
  33. }
  34. }
  35. /// Login request transfer object.
  36. struct LoginRequest {
  37. let identifier: String
  38. let password: String
  39. }
  40. /// Registration request transfer object.
  41. struct RegisterRequest {
  42. let username: String
  43. let identifier: String
  44. let password: String
  45. }
  46. /// Profile update transfer object.
  47. struct UpdateProfileRequest {
  48. let username: String?
  49. let email: String?
  50. let phoneNumber: String?
  51. let avatarURL: String?
  52. }
  53. /// Password modification transfer object.
  54. struct ChangePasswordRequest {
  55. let oldPassword: String
  56. let newPassword: String
  57. }
  58. /// Abstract contract for authentication service implementations.
  59. /// Allows swapping between local persistence and remote server HTTP API seamlessly.
  60. protocol AuthServiceProtocol {
  61. func restoreSession(completion: @escaping (AuthResult<UserAccount?>) -> Void)
  62. func login(request: LoginRequest, completion: @escaping (AuthResult<UserAccount>) -> Void)
  63. func register(request: RegisterRequest, completion: @escaping (AuthResult<UserAccount>) -> Void)
  64. func updateProfile(request: UpdateProfileRequest, completion: @escaping (AuthResult<UserAccount>) -> Void)
  65. func changePassword(request: ChangePasswordRequest, completion: @escaping (AuthResult<Bool>) -> Void)
  66. func logout(completion: @escaping () -> Void)
  67. func getCurrentUser() -> UserAccount?
  68. }