-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSupabaseAuthService.swift
More file actions
212 lines (188 loc) · 6.6 KB
/
Copy pathSupabaseAuthService.swift
File metadata and controls
212 lines (188 loc) · 6.6 KB
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
import Combine
import Supabase
import SwiftUI
// MARK: - Auth-specific errors
enum RegistrationError: LocalizedError {
case emailConfirmationRequired
var errorDescription: String? {
switch self {
case .emailConfirmationRequired:
return "Revisa tu correo para confirmar tu cuenta."
}
}
}
// MARK: - Supabase Auth Service
@MainActor
final class SupabaseAuthService: ObservableObject, AuthRepository {
@Published var currentUser: UserProfile?
@Published private(set) var isAuthenticated = false
@Published private(set) var isLoading = false
@Published private(set) var isInitialLoading = true
@Published private(set) var errorMessage: String?
// MARK: - Publishers
var isAuthenticatedPublisher: AnyPublisher<Bool, Never> {
$isAuthenticated.eraseToAnyPublisher()
}
var isLoadingPublisher: AnyPublisher<Bool, Never> {
$isLoading.eraseToAnyPublisher()
}
var errorMessagePublisher: AnyPublisher<String?, Never> {
$errorMessage.eraseToAnyPublisher()
}
var objectWillChangePublisher: AnyPublisher<Void, Never> {
objectWillChange.map { _ in () }.eraseToAnyPublisher()
}
// MARK: - Init
init() {
Task { await restoreSession() }
}
// MARK: - Auth actions
func signIn(email: String, password: String) async -> Result<Void, DMError> {
isLoading = true
defer { isLoading = false }
do {
let session = try await supabase.auth.signIn(email: email, password: password)
try await loadProfile(userId: session.user.id)
return .success(())
} catch {
let errorMsg = error.localizedDescription
errorMessage = errorMsg
if errorMsg.localizedCaseInsensitiveContains("email not confirmed") ||
errorMsg.localizedCaseInsensitiveContains("confirm")
{
return .failure(.emailConfirmationRequired("Tu correo no está confirmado. Por favor ingresa el código de confirmación."))
}
return .failure(.unknown(errorMsg))
}
}
func signUp(
email: String,
password: String,
username: String,
displayName: String,
university: String? = nil
) async -> Result<Void, DMError> {
isLoading = true
defer { isLoading = false }
do {
var metadata: [String: AnyJSON] = [
"username": .string(username),
"display_name": .string(displayName),
"is_moderator": .bool(email.lowercased() == "moderador@dailymath.com"),
]
if let university {
metadata["university"] = .string(university)
}
let response = try await supabase.auth.signUp(
email: email,
password: password,
data: metadata
)
if response.session != nil {
// Auto-confirmed — load profile and log in immediately
try await loadProfile(userId: response.user.id)
return .success(())
} else {
// Email confirmation required — registration succeeded but user must confirm
return .failure(.emailConfirmationRequired("Revisa tu correo para confirmar tu cuenta."))
}
} catch {
errorMessage = error.localizedDescription
return .failure(.unknown(error.localizedDescription))
}
}
func signOut() async -> Result<Void, DMError> {
do {
try await supabase.auth.signOut()
currentUser = nil
isAuthenticated = false
return .success(())
} catch {
return .failure(.unknown(error.localizedDescription))
}
}
func resetPassword(email: String) async -> Result<Void, DMError> {
do {
try await supabase.auth.resetPasswordForEmail(email)
return .success(())
} catch {
return .failure(.unknown(error.localizedDescription))
}
}
func deleteAccount() async -> Result<Void, DMError> {
guard let userId = currentUser?.id else {
return .failure(.unauthorized)
}
do {
// Delete profile row (cascades to all user data)
try await supabase
.from("profiles")
.delete()
.eq("id", value: userId.uuidString)
.execute()
_ = await signOut()
return .success(())
} catch {
return .failure(.unknown(error.localizedDescription))
}
}
// MARK: - Profile mutation helper (used by repositories to update points etc.)
func updateCurrentProfile(_ mutation: (inout UserProfile) -> Void) {
guard var profile = currentUser else { return }
mutation(&profile)
currentUser = profile
Task {
try? await supabase
.from("profiles")
.update([
"points": profile.points,
"reputation": profile.reputation,
"study_streak": profile.studyStreak,
])
.eq("id", value: profile.id.uuidString)
.execute()
}
}
func checkEmailExists(email: String) async -> Result<Bool, DMError> {
do {
let normalized = email.lowercased().trimmingCharacters(in: .whitespaces)
let profiles: [UserProfile] = try await supabase
.from("profiles")
.select()
.eq("email", value: normalized)
.execute()
.value
return .success(!profiles.isEmpty)
} catch {
return .failure(.unknown(error.localizedDescription))
}
}
// MARK: - Private helpers
private func loadProfile(userId: UUID) async throws {
let profile: UserProfile = try await supabase
.from("profiles")
.select()
.eq("id", value: userId.uuidString)
.single()
.execute()
.value
currentUser = profile
isAuthenticated = true
errorMessage = nil
}
private func restoreSession() async {
isInitialLoading = true
isLoading = true
defer {
isLoading = false
isInitialLoading = false
}
do {
let session = try await supabase.auth.session
try await loadProfile(userId: session.user.id)
} catch {
// No active session — stay logged out
isAuthenticated = false
}
}
}