blob: 4386e383eab21782088f70238ecec97a05de42c9 (
plain) (
blame)
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
|
//
// AuthStore.swift
// octosentry
//
// Drives the device authorization flow and mirrors whether a token is
// currently in the Keychain. Replaces the GITHUB_TOKEN env var dev
// shortcut (spec §13) with the real v1 auth flow (spec §6).
//
import Foundation
import Observation
@Observable
final class AuthStore {
private(set) var state: AuthState
private(set) var errorMessage: String?
private let client = GitHubDeviceAuthClient()
private var authorizationTask: Task<Void, Never>?
init() {
state = KeychainTokenStore.load() != nil ? .signedIn : .signedOut
}
var isSignedIn: Bool {
if case .signedIn = state { return true }
return false
}
func signIn() {
guard authorizationTask == nil else { return }
errorMessage = nil
authorizationTask = Task {
defer { authorizationTask = nil }
do {
let deviceCode = try await client.requestDeviceCode()
state = .awaitingAuthorization(userCode: deviceCode.userCode, verificationURL: deviceCode.verificationUri)
let token = try await client.pollForToken(
deviceCode: deviceCode.deviceCode,
interval: deviceCode.interval,
expiresIn: deviceCode.expiresIn
)
try KeychainTokenStore.save(token)
state = .signedIn
} catch {
errorMessage = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
state = .signedOut
}
}
}
func signOut() {
authorizationTask?.cancel()
authorizationTask = nil
KeychainTokenStore.delete()
state = .signedOut
}
}
|