Add complete OAuth 2.0 Authorization Code Flow with PKCE as alternative to API token authentication, with automatic server detection and graceful fallback to classic login. **OAuth Core (RFC 7636 PKCE):** - PKCEGenerator: S256 challenge generation for secure code exchange - OAuth DTOs: Client registration, token request/response models - OAuthClient, OAuthToken, AuthenticationMethod domain models - API.swift: registerOAuthClient() and exchangeOAuthToken() endpoints - OAuthRepository + POAuthRepository protocol **Browser Integration (ASWebAuthenticationSession):** - OAuthSession: Wraps native authentication session - OAuthFlowCoordinator: Orchestrates 5-phase OAuth flow - readeck:// URL scheme for OAuth callback handling - State verification for CSRF protection - User cancellation handling **Token Management:** - KeychainHelper: OAuth token storage alongside API tokens - TokenProvider: getOAuthToken(), setOAuthToken(), getAuthMethod() - AuthenticationMethod enum to distinguish token types - AuthRepository: loginWithOAuth(), getAuthenticationMethod() - Endpoint persistence in both Keychain and Settings **Server Feature Detection:** - ServerInfo extended with features array and supportsOAuth flag - GET /api/info endpoint integration (backward compatible) - GetServerInfoUseCase with optional endpoint parameter **User Profile Integration:** - ProfileApiClient: Fetch user data via GET /api/profile - UserProfileDto with username, email, provider information - GetUserProfileUseCase: Extract username from profile - Username saved and displayed for OAuth users (like classic auth) **Automatic OAuth Flow (No User Selection):** - OnboardingServerView: 2-phase flow (endpoint → auto-OAuth or classic) - OAuth attempted automatically if server supports it - Fallback to username/password on OAuth failure or unsupported - SettingsServerViewModel: checkServerOAuthSupport(), loginWithOAuth() **Cleanup & Refactoring:** - Remove all #if os(iOS) && !APP_EXTENSION conditionals - Remove LoginMethodSelectionView (no longer needed) - Remove switchToClassicLogin() method - Factories updated with OAuth dependencies **Testing:** - PKCEGeneratorTests: Verify RFC 7636 compliance - ServerInfoTests: Feature detection and backward compatibility - Mock implementations for all OAuth components **Documentation:** - docs/OAuth2-Implementation-Plan.md: Complete implementation guide - openapi.json: Readeck API specification **Scopes Requested:** - bookmarks:read, bookmarks:write, profile:read OAuth users now have full feature parity with classic authentication. Server auto-detects OAuth support via /info endpoint. Seamless UX with browser-based login and automatic fallback.
120 lines
3.8 KiB
Swift
120 lines
3.8 KiB
Swift
//
|
|
// ServerInfoRepository.swift
|
|
// readeck
|
|
//
|
|
// Created by Ilyas Hallak
|
|
|
|
import Foundation
|
|
|
|
class ServerInfoRepository: PServerInfoRepository {
|
|
private let apiClient: PInfoApiClient
|
|
private let logger = Logger.network
|
|
|
|
// Cache properties
|
|
private var cachedServerInfo: ServerInfo?
|
|
private var lastCheckTime: Date?
|
|
private let cacheTTL: TimeInterval = 30.0 // 30 seconds cache
|
|
private let rateLimitInterval: TimeInterval = 5.0 // min 5 seconds between requests
|
|
|
|
// Thread safety
|
|
private let queue = DispatchQueue(label: "com.readeck.serverInfoRepository", attributes: .concurrent)
|
|
|
|
init(apiClient: PInfoApiClient) {
|
|
self.apiClient = apiClient
|
|
}
|
|
|
|
func checkServerReachability() async -> Bool {
|
|
// Check cache first
|
|
if let cached = getCachedReachability() {
|
|
logger.debug("Server reachability from cache: \(cached)")
|
|
return cached
|
|
}
|
|
|
|
// Check rate limiting
|
|
if isRateLimited() {
|
|
logger.debug("Server reachability check rate limited, using cached value")
|
|
return cachedServerInfo?.isReachable ?? false
|
|
}
|
|
|
|
// Perform actual check
|
|
do {
|
|
let info = try await apiClient.getServerInfo(endpoint: nil)
|
|
let serverInfo = ServerInfo(from: info)
|
|
updateCache(serverInfo: serverInfo)
|
|
logger.info("Server reachability checked: true (version: \(info.version))")
|
|
return true
|
|
} catch {
|
|
let unreachableInfo = ServerInfo.unreachable
|
|
updateCache(serverInfo: unreachableInfo)
|
|
logger.warning("Server reachability check failed: \(error.localizedDescription)")
|
|
return false
|
|
}
|
|
}
|
|
|
|
func getServerInfo(endpoint: String? = nil) async throws -> ServerInfo {
|
|
// Check cache first (only if no custom endpoint provided)
|
|
if endpoint == nil, let cached = getCachedServerInfo() {
|
|
logger.debug("Server info from cache")
|
|
return cached
|
|
}
|
|
|
|
// Check rate limiting (only if no custom endpoint provided)
|
|
if endpoint == nil, isRateLimited(), let cached = cachedServerInfo {
|
|
logger.debug("Server info check rate limited, using cached value")
|
|
return cached
|
|
}
|
|
|
|
// Fetch fresh info
|
|
let dto = try await apiClient.getServerInfo(endpoint: endpoint)
|
|
let serverInfo = ServerInfo(from: dto)
|
|
|
|
// Only update cache if using default endpoint
|
|
if endpoint == nil {
|
|
updateCache(serverInfo: serverInfo)
|
|
}
|
|
|
|
logger.info("Server info fetched: version \(dto.version)")
|
|
return serverInfo
|
|
}
|
|
|
|
// MARK: - Cache Management
|
|
|
|
private func getCachedReachability() -> Bool? {
|
|
queue.sync {
|
|
guard let lastCheck = lastCheckTime,
|
|
Date().timeIntervalSince(lastCheck) < cacheTTL,
|
|
let cached = cachedServerInfo else {
|
|
return nil
|
|
}
|
|
return cached.isReachable
|
|
}
|
|
}
|
|
|
|
private func getCachedServerInfo() -> ServerInfo? {
|
|
queue.sync {
|
|
guard let lastCheck = lastCheckTime,
|
|
Date().timeIntervalSince(lastCheck) < cacheTTL,
|
|
let cached = cachedServerInfo else {
|
|
return nil
|
|
}
|
|
return cached
|
|
}
|
|
}
|
|
|
|
private func isRateLimited() -> Bool {
|
|
queue.sync {
|
|
guard let lastCheck = lastCheckTime else {
|
|
return false
|
|
}
|
|
return Date().timeIntervalSince(lastCheck) < rateLimitInterval
|
|
}
|
|
}
|
|
|
|
private func updateCache(serverInfo: ServerInfo) {
|
|
queue.async(flags: .barrier) { [weak self] in
|
|
self?.cachedServerInfo = serverInfo
|
|
self?.lastCheckTime = Date()
|
|
}
|
|
}
|
|
}
|