Phase 1 aus dem Native-Auth-Vollausbau-Plan (Option A, siehe mana/docs/MANA_SWIFT.md). 7 neue AuthClient-Methoden für die Account-Reise: register, forgotPassword, resetPassword, resendVerification, changeEmail, changePassword, deleteAccount. AuthError jetzt mit 19 präzisen Cases gespiegelt aus AuthErrorCode in mana-auth/lib/auth-errors.ts, plus AuthError.classify() als public Helper und Equatable-Conformance. AuthClient.lastError ergänzt — strukturierter Fehler für ManaAuthUI das den .emailNotVerified-Gate programmatisch braucht. signIn und refreshAccessToken auf neue Klassifikation umgestellt. Breaking: AuthError.serverError hat zusätzliches code:-Argument. Apps (cards-native, memoro-native) sind bereits angepasst. 38/38 Tests grün (26 neu): AuthErrorClassifyTests deckt jeden ErrorCode + Status-Heuristik + Retry-After ab, AuthClientAccountTests deckt jede neue Methode via URLProtocol-Mock ab. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
385 lines
15 KiB
Swift
385 lines
15 KiB
Swift
import Foundation
|
|
|
|
/// Account-Lifecycle-Methoden: Registrierung, Passwort-Reset,
|
|
/// Email-Verifikation, Account-Management.
|
|
///
|
|
/// Diese Methoden ergänzen die Login-/Refresh-Maschine in ``AuthClient``
|
|
/// um die Flows, die eine native App für eine vollständige Auth-Reise
|
|
/// braucht (vergleichbar mit `mana-auth-web` aber API-basiert statt
|
|
/// Cookie-basiert).
|
|
///
|
|
/// **Server-Endpoints (alle JSON, alle unter `/api/v1/auth/*`):**
|
|
/// - `POST /register` — Sign-Up + (je nach Config) email-verify-required
|
|
/// - `POST /forgot-password` — Reset-Mail anfordern (immer 200, kein Enum-Leak)
|
|
/// - `POST /reset-password` — neues PW mit Token aus Reset-Mail
|
|
/// - `POST /resend-verification` — Verify-Mail erneut senden
|
|
/// - `POST /change-email` — Email ändern (verschickt Verify-Mail an neue Adresse)
|
|
/// - `POST /change-password` — Passwort ändern (current + new)
|
|
/// - `DELETE /account` — Account löschen (App-Store-Pflicht 5.1.1(v))
|
|
///
|
|
/// **Server-Limitation (Stand 2026-05-13):** `change-email`,
|
|
/// `change-password` und `DELETE /account` forwarden Original-Request-
|
|
/// Headers an Better Auth. Better Auth liest Session-Cookies. Der
|
|
/// `bearer`-Plugin von Better Auth ist NICHT installiert, daher
|
|
/// scheitern diese Endpoints heute mit reinem `Authorization: Bearer`.
|
|
/// → Server-Fix in Phase 3 nötig (entweder `bearerPlugin()` in
|
|
/// `better-auth.config.ts` aktivieren oder Custom-Bearer-Resolver in
|
|
/// `mana-auth/src/routes/auth.ts` ergänzen). ManaCore sendet Bearer
|
|
/// bereits korrekt — sobald der Server das akzeptiert, funktionieren
|
|
/// die Methoden ohne Swift-Änderung.
|
|
public extension AuthClient {
|
|
// MARK: - Registrierung
|
|
|
|
/// Registriert einen neuen Account.
|
|
///
|
|
/// - Parameters:
|
|
/// - email: Email-Adresse, wird als Login-Identifier genutzt.
|
|
/// - password: Klartext-Passwort, Server hasht via Better Auth.
|
|
/// - name: Anzeige-Name. Wenn nil, nutzt der Server den Email-Local-Part.
|
|
/// - sourceAppUrl: Basis-URL für den Verify-Email-Klick-Redirect.
|
|
/// Per-App-spezifisch — z.B. `https://cardecky.mana.how/auth/verify`
|
|
/// für einen Universal-Link-Handler. Der Server hängt `?token=…` an.
|
|
///
|
|
/// Bei Erfolg ist mit Default-Server-Config (`requireEmailVerification: true`)
|
|
/// noch **kein Login** gemacht — der User muss erst die Verify-Mail
|
|
/// klicken. Ein anschließendes `signIn(...)` mit denselben Credentials
|
|
/// liefert dann `.emailNotVerified` bis der Klick passiert.
|
|
///
|
|
/// Wenn der Server in der Antwort doch Tokens schickt (kann passieren
|
|
/// wenn Email-Verifikation off ist), wird die Session persistiert und
|
|
/// der Status auf `.signedIn` gesetzt.
|
|
///
|
|
/// - Throws: ``AuthError/emailAlreadyRegistered``,
|
|
/// ``AuthError/weakPassword(message:)``, ``AuthError/signupLimitReached``,
|
|
/// ``AuthError/validation(message:)`` und Netzwerk-Cases.
|
|
func register(
|
|
email: String,
|
|
password: String,
|
|
name: String? = nil,
|
|
sourceAppUrl: URL? = nil
|
|
) async throws {
|
|
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !trimmed.isEmpty, !password.isEmpty else {
|
|
throw AuthError.validation(message: "Email und Passwort sind erforderlich")
|
|
}
|
|
|
|
let body = RegisterRequest(
|
|
email: trimmed,
|
|
password: password,
|
|
name: name,
|
|
sourceAppUrl: sourceAppUrl?.absoluteString
|
|
)
|
|
let (data, http) = try await postJSON(path: "/api/v1/auth/register", body: body)
|
|
guard http.statusCode == 200 else {
|
|
throw AuthError.classify(
|
|
status: http.statusCode,
|
|
data: data,
|
|
retryAfterHeader: http.retryAfterSeconds
|
|
)
|
|
}
|
|
|
|
let decoded = try JSONDecoder().decode(RegisterResponse.self, from: data)
|
|
if let access = decoded.accessToken, let refresh = decoded.refreshToken {
|
|
try persistSession(email: trimmed, accessToken: access, refreshToken: refresh)
|
|
CoreLog.auth.info("Register successful — auto-signed-in")
|
|
} else {
|
|
CoreLog.auth.info("Register successful — awaiting email verification")
|
|
}
|
|
}
|
|
|
|
// MARK: - Passwort-Reset
|
|
|
|
/// Fordert eine Passwort-Reset-Email an.
|
|
///
|
|
/// Der Server antwortet **immer mit 200**, unabhängig davon ob die
|
|
/// Email existiert (bewusst, um User-Enumeration zu verhindern).
|
|
/// Die UI sollte daher generisch melden ("Wenn dein Account existiert,
|
|
/// ist eine Email unterwegs").
|
|
///
|
|
/// - Parameters:
|
|
/// - email: Email-Adresse des Accounts.
|
|
/// - resetUniversalLink: Universal-Link der App, der die
|
|
/// Reset-Seite öffnet. Z.B. `https://cardecky.mana.how/auth/reset`.
|
|
/// Der Server hängt `?token=…` an und nutzt diesen Link im
|
|
/// Mail-Template.
|
|
///
|
|
/// - Throws: nur Netzwerk-Fehler. Server-Fehler werden vom Server
|
|
/// geschluckt (200 trotzdem).
|
|
func forgotPassword(email: String, resetUniversalLink: URL) async throws {
|
|
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !trimmed.isEmpty else {
|
|
throw AuthError.validation(message: "Email ist erforderlich")
|
|
}
|
|
|
|
let body = ForgotPasswordRequest(email: trimmed, redirectTo: resetUniversalLink.absoluteString)
|
|
let (data, http) = try await postJSON(path: "/api/v1/auth/forgot-password", body: body)
|
|
guard http.statusCode == 200 else {
|
|
throw AuthError.classify(
|
|
status: http.statusCode,
|
|
data: data,
|
|
retryAfterHeader: http.retryAfterSeconds
|
|
)
|
|
}
|
|
CoreLog.auth.info("Password reset requested")
|
|
}
|
|
|
|
/// Setzt das Passwort mit einem Reset-Token aus der Reset-Email.
|
|
///
|
|
/// - Parameters:
|
|
/// - token: Reset-Token aus der Email (Query-Param `?token=…`).
|
|
/// - newPassword: Neues Klartext-Passwort.
|
|
///
|
|
/// Nach Erfolg ist der User **nicht** automatisch eingeloggt — der
|
|
/// `signIn(...)`-Call muss separat passieren.
|
|
///
|
|
/// - Throws: ``AuthError/tokenExpired``, ``AuthError/tokenInvalid``,
|
|
/// ``AuthError/weakPassword(message:)`` und Netzwerk-Cases.
|
|
func resetPassword(token: String, newPassword: String) async throws {
|
|
guard !token.isEmpty, !newPassword.isEmpty else {
|
|
throw AuthError.validation(message: "Token und neues Passwort sind erforderlich")
|
|
}
|
|
|
|
let body = ResetPasswordRequest(token: token, newPassword: newPassword)
|
|
let (data, http) = try await postJSON(path: "/api/v1/auth/reset-password", body: body)
|
|
guard http.statusCode == 200 else {
|
|
throw AuthError.classify(
|
|
status: http.statusCode,
|
|
data: data,
|
|
retryAfterHeader: http.retryAfterSeconds
|
|
)
|
|
}
|
|
CoreLog.auth.info("Password reset completed")
|
|
}
|
|
|
|
// MARK: - Email-Verifikation
|
|
|
|
/// Sendet die Email-Verifikations-Mail erneut.
|
|
///
|
|
/// Aufzurufen wenn `signIn(...)` mit ``AuthError/emailNotVerified``
|
|
/// zurückkommt — die UI bietet einen "Mail erneut senden"-Button.
|
|
///
|
|
/// - Parameters:
|
|
/// - email: Email-Adresse des Accounts.
|
|
/// - sourceAppUrl: Universal-Link für den Verify-Klick. Gleiche
|
|
/// Semantik wie bei ``register(email:password:name:sourceAppUrl:)``.
|
|
///
|
|
/// - Throws: ``AuthError/notFound`` wenn die Email nicht existiert,
|
|
/// ``AuthError/rateLimited(retryAfter:)`` bei zu vielen Versuchen.
|
|
func resendVerification(email: String, sourceAppUrl: URL? = nil) async throws {
|
|
let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !trimmed.isEmpty else {
|
|
throw AuthError.validation(message: "Email ist erforderlich")
|
|
}
|
|
|
|
let body = ResendVerificationRequest(
|
|
email: trimmed,
|
|
sourceAppUrl: sourceAppUrl?.absoluteString
|
|
)
|
|
let (data, http) = try await postJSON(path: "/api/v1/auth/resend-verification", body: body)
|
|
guard http.statusCode == 200 else {
|
|
throw AuthError.classify(
|
|
status: http.statusCode,
|
|
data: data,
|
|
retryAfterHeader: http.retryAfterSeconds
|
|
)
|
|
}
|
|
CoreLog.auth.info("Verification email resent")
|
|
}
|
|
|
|
// MARK: - Account-Management (erfordert eingeloggte Session)
|
|
|
|
/// Ändert die Email des aktuell eingeloggten Accounts.
|
|
///
|
|
/// Der Server schickt eine Verifikations-Mail an die **neue** Adresse.
|
|
/// Bis der User klickt, bleibt die alte Email aktiv.
|
|
///
|
|
/// - Parameters:
|
|
/// - newEmail: Neue Email-Adresse.
|
|
/// - callbackUniversalLink: Universal-Link, der nach erfolgter
|
|
/// Verifikation geöffnet wird (z.B.
|
|
/// `https://cardecky.mana.how/auth/email-changed`).
|
|
///
|
|
/// - Important: Aktuell server-seitig nicht Bearer-fähig — siehe
|
|
/// Doc-Header dieser Datei.
|
|
func changeEmail(newEmail: String, callbackUniversalLink: URL? = nil) async throws {
|
|
let trimmed = newEmail.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !trimmed.isEmpty else {
|
|
throw AuthError.validation(message: "Neue Email ist erforderlich")
|
|
}
|
|
|
|
let body = ChangeEmailRequest(
|
|
newEmail: trimmed,
|
|
callbackURL: callbackUniversalLink?.absoluteString
|
|
)
|
|
let (data, http) = try await postJSON(
|
|
path: "/api/v1/auth/change-email",
|
|
body: body,
|
|
authenticated: true
|
|
)
|
|
guard http.statusCode == 200 else {
|
|
throw AuthError.classify(
|
|
status: http.statusCode,
|
|
data: data,
|
|
retryAfterHeader: http.retryAfterSeconds
|
|
)
|
|
}
|
|
CoreLog.auth.info("Email change requested — verification email sent")
|
|
}
|
|
|
|
/// Ändert das Passwort des aktuell eingeloggten Accounts.
|
|
///
|
|
/// - Parameters:
|
|
/// - currentPassword: Aktuelles Klartext-Passwort (Re-Auth).
|
|
/// - newPassword: Neues Klartext-Passwort.
|
|
///
|
|
/// - Important: Aktuell server-seitig nicht Bearer-fähig — siehe
|
|
/// Doc-Header dieser Datei.
|
|
func changePassword(currentPassword: String, newPassword: String) async throws {
|
|
guard !currentPassword.isEmpty, !newPassword.isEmpty else {
|
|
throw AuthError.validation(message: "Aktuelles und neues Passwort sind erforderlich")
|
|
}
|
|
|
|
let body = ChangePasswordRequest(currentPassword: currentPassword, newPassword: newPassword)
|
|
let (data, http) = try await postJSON(
|
|
path: "/api/v1/auth/change-password",
|
|
body: body,
|
|
authenticated: true
|
|
)
|
|
guard http.statusCode == 200 else {
|
|
throw AuthError.classify(
|
|
status: http.statusCode,
|
|
data: data,
|
|
retryAfterHeader: http.retryAfterSeconds
|
|
)
|
|
}
|
|
CoreLog.auth.info("Password changed")
|
|
}
|
|
|
|
/// Löscht den aktuell eingeloggten Account vollständig.
|
|
///
|
|
/// Server löscht alle User-Daten (Auth, Credits, Sync-DB-Records).
|
|
/// Bei Erfolg wird der lokale Keychain gewiped und der Status auf
|
|
/// `.signedOut` gesetzt.
|
|
///
|
|
/// **App-Store-Pflicht 5.1.1(v):** jede App mit Account-Erstellung
|
|
/// muss eine Account-Löschung anbieten.
|
|
///
|
|
/// - Parameter password: Aktuelles Klartext-Passwort als Re-Auth.
|
|
///
|
|
/// - Important: Aktuell server-seitig nicht Bearer-fähig — siehe
|
|
/// Doc-Header dieser Datei.
|
|
func deleteAccount(password: String) async throws {
|
|
guard !password.isEmpty else {
|
|
throw AuthError.validation(message: "Passwort ist erforderlich")
|
|
}
|
|
|
|
let body = DeleteAccountRequest(password: password)
|
|
let (data, http) = try await postJSON(
|
|
path: "/api/v1/auth/account",
|
|
method: "DELETE",
|
|
body: body,
|
|
authenticated: true
|
|
)
|
|
guard http.statusCode == 200 else {
|
|
throw AuthError.classify(
|
|
status: http.statusCode,
|
|
data: data,
|
|
retryAfterHeader: http.retryAfterSeconds
|
|
)
|
|
}
|
|
clearSession()
|
|
CoreLog.auth.notice("Account deleted")
|
|
}
|
|
}
|
|
|
|
// MARK: - Private Helpers
|
|
|
|
extension AuthClient {
|
|
/// Generischer JSON-POST/DELETE-Helper. Wenn `authenticated == true`,
|
|
/// wird der aktuelle Bearer-Token mitgeschickt.
|
|
fileprivate func postJSON<Body: Encodable>(
|
|
path: String,
|
|
method: String = "POST",
|
|
body: Body,
|
|
authenticated: Bool = false
|
|
) async throws -> (Data, HTTPURLResponse) {
|
|
let url = config.authBaseURL.appending(path: path)
|
|
var request = URLRequest(url: url)
|
|
request.httpMethod = method
|
|
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
if authenticated {
|
|
let token = try currentAccessToken()
|
|
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
|
}
|
|
do {
|
|
request.httpBody = try JSONEncoder().encode(body)
|
|
} catch {
|
|
throw AuthError.encoding
|
|
}
|
|
|
|
do {
|
|
let (data, response) = try await session.data(for: request)
|
|
guard let http = response as? HTTPURLResponse else {
|
|
throw AuthError.networkFailure("Keine HTTP-Antwort")
|
|
}
|
|
return (data, http)
|
|
} catch let error as URLError {
|
|
throw AuthError.networkFailure(error.localizedDescription)
|
|
} catch let error as AuthError {
|
|
throw error
|
|
} catch {
|
|
throw AuthError.networkFailure(String(describing: error))
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Wire-Format
|
|
|
|
private struct RegisterRequest: Encodable {
|
|
let email: String
|
|
let password: String
|
|
let name: String?
|
|
let sourceAppUrl: String?
|
|
}
|
|
|
|
/// Server-Antwort auf `/register`. Tokens sind optional weil
|
|
/// `requireEmailVerification: true` (Default) keine Session liefert.
|
|
private struct RegisterResponse: Decodable {
|
|
let user: RegisterUser?
|
|
let accessToken: String?
|
|
let refreshToken: String?
|
|
}
|
|
|
|
private struct RegisterUser: Decodable {
|
|
let id: String
|
|
let email: String?
|
|
}
|
|
|
|
private struct ForgotPasswordRequest: Encodable {
|
|
let email: String
|
|
let redirectTo: String
|
|
}
|
|
|
|
private struct ResetPasswordRequest: Encodable {
|
|
let token: String
|
|
let newPassword: String
|
|
}
|
|
|
|
private struct ResendVerificationRequest: Encodable {
|
|
let email: String
|
|
let sourceAppUrl: String?
|
|
}
|
|
|
|
private struct ChangeEmailRequest: Encodable {
|
|
let newEmail: String
|
|
let callbackURL: String?
|
|
}
|
|
|
|
private struct ChangePasswordRequest: Encodable {
|
|
let currentPassword: String
|
|
let newPassword: String
|
|
}
|
|
|
|
private struct DeleteAccountRequest: Encodable {
|
|
let password: String
|
|
}
|