api-swift / Sources / IrdAPI / Credentials / CredentialProvider.swift
256 words
 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
import Foundation

/// Where the bearer comes from. Consulted on every request, so a token stored after
/// a device login is picked up without rebuilding the client. Either an API key
/// (`ird_...`) or an account session JWT goes in the same slot.
public protocol CredentialProvider: Sendable {
    /// The current token, or nil to send no `Authorization` header.
    func token() async throws -> String?
}

/// A provider that can also be written to — the app's sign-in and sign-out.
public protocol CredentialStore: CredentialProvider {
    func save(_ token: String) throws
    func delete() throws
}

/// Anonymous: only the operations that allow it will succeed.
public struct NoCredential: CredentialProvider {
    public init() {}
    public func token() async throws -> String? { nil }
}

/// A fixed API key or JWT.
public struct StaticCredential: CredentialProvider {
    public let value: String
    public init(_ value: String) { self.value = value }
    public func token() async throws -> String? { value }
}

/// Keeps the token in memory only — for tests, previews and short-lived tools.
public final class InMemoryCredentialStore: CredentialStore, @unchecked Sendable {
    private let lock = NSLock()
    private var stored: String?

    public init(_ token: String? = nil) { stored = token }
    public func token() async throws -> String? { lock.withLock { stored } }
    public func save(_ token: String) throws { lock.withLock { stored = token } }
    public func delete() throws { lock.withLock { stored = nil } }
}

public enum CredentialStoreError: Error, Sendable, Equatable {
    case keychain(status: Int32)
    case corrupt
}

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/api-swift.git