|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+import Foundation
|
|
|
2
|
+import CryptoKit
|
|
|
3
|
+import AppKit
|
|
|
4
|
+import Network
|
|
|
5
|
+
|
|
|
6
|
+struct GoogleOAuthTokens: Codable, Equatable {
|
|
|
7
|
+ var accessToken: String
|
|
|
8
|
+ var refreshToken: String?
|
|
|
9
|
+ var expiresAt: Date
|
|
|
10
|
+ var scope: String?
|
|
|
11
|
+ var tokenType: String?
|
|
|
12
|
+}
|
|
|
13
|
+
|
|
|
14
|
+struct GoogleUserProfile: Codable, Equatable {
|
|
|
15
|
+ var name: String?
|
|
|
16
|
+ var email: String?
|
|
|
17
|
+ var picture: String?
|
|
|
18
|
+}
|
|
|
19
|
+
|
|
|
20
|
+enum GoogleOAuthError: Error {
|
|
|
21
|
+ case missingClientId
|
|
|
22
|
+ case missingClientSecret
|
|
|
23
|
+ case invalidCallbackURL
|
|
|
24
|
+ case missingAuthorizationCode
|
|
|
25
|
+ case tokenExchangeFailed(String)
|
|
|
26
|
+ case unableToOpenBrowser
|
|
|
27
|
+ case authenticationTimedOut
|
|
|
28
|
+ case noStoredTokens
|
|
|
29
|
+}
|
|
|
30
|
+
|
|
|
31
|
+final class GoogleOAuthService: NSObject {
|
|
|
32
|
+ static let shared = GoogleOAuthService()
|
|
|
33
|
+
|
|
|
34
|
+ // Stored in UserDefaults so you can configure without rebuilding.
|
|
|
35
|
+ // Put your OAuth Desktop client ID here (from Google Cloud Console).
|
|
|
36
|
+ private let clientIdDefaultsKey = "google.oauth.clientId"
|
|
|
37
|
+ private let clientSecretDefaultsKey = "google.oauth.clientSecret"
|
|
|
38
|
+ private let bundledClientId = "824412072260-m9g5g6mlemnb0o079rtuqnh0e1unmelc.apps.googleusercontent.com"
|
|
|
39
|
+ private let bundledClientSecret = "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"
|
|
|
40
|
+
|
|
|
41
|
+ // Calendar is needed for schedule. Profile/email make login feel complete in-app.
|
|
|
42
|
+ private let scopes = [
|
|
|
43
|
+ "openid",
|
|
|
44
|
+ "email",
|
|
|
45
|
+ "profile",
|
|
|
46
|
+ "https://www.googleapis.com/auth/calendar.events"
|
|
|
47
|
+ ]
|
|
|
48
|
+
|
|
|
49
|
+ private let tokenStore = KeychainTokenStore()
|
|
|
50
|
+ private override init() {}
|
|
|
51
|
+
|
|
|
52
|
+ func configuredClientId() -> String? {
|
|
|
53
|
+ let value = UserDefaults.standard.string(forKey: clientIdDefaultsKey)?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
54
|
+ if let value, value.isEmpty == false { return value }
|
|
|
55
|
+ return bundledClientId
|
|
|
56
|
+ }
|
|
|
57
|
+
|
|
|
58
|
+ func setClientIdForTesting(_ clientId: String) {
|
|
|
59
|
+ UserDefaults.standard.set(clientId, forKey: clientIdDefaultsKey)
|
|
|
60
|
+ }
|
|
|
61
|
+
|
|
|
62
|
+ func configuredClientSecret() -> String? {
|
|
|
63
|
+ let value = UserDefaults.standard.string(forKey: clientSecretDefaultsKey)?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
64
|
+ if let value, value.isEmpty == false { return value }
|
|
|
65
|
+ return bundledClientSecret
|
|
|
66
|
+ }
|
|
|
67
|
+
|
|
|
68
|
+ func setClientSecretForTesting(_ clientSecret: String) {
|
|
|
69
|
+ UserDefaults.standard.set(clientSecret, forKey: clientSecretDefaultsKey)
|
|
|
70
|
+ }
|
|
|
71
|
+
|
|
|
72
|
+ func signOut() throws {
|
|
|
73
|
+ try tokenStore.deleteTokens()
|
|
|
74
|
+ }
|
|
|
75
|
+
|
|
|
76
|
+ func loadTokens() -> GoogleOAuthTokens? {
|
|
|
77
|
+ try? tokenStore.readTokens()
|
|
|
78
|
+ }
|
|
|
79
|
+
|
|
|
80
|
+ func fetchUserProfile(accessToken: String) async throws -> GoogleUserProfile {
|
|
|
81
|
+ var request = URLRequest(url: URL(string: "https://openidconnect.googleapis.com/v1/userinfo")!)
|
|
|
82
|
+ request.httpMethod = "GET"
|
|
|
83
|
+ request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
|
|
|
84
|
+
|
|
|
85
|
+ let (data, response) = try await URLSession.shared.data(for: request)
|
|
|
86
|
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
|
|
|
87
|
+ let details = String(data: data, encoding: .utf8) ?? "HTTP \((response as? HTTPURLResponse)?.statusCode ?? -1)"
|
|
|
88
|
+ throw GoogleOAuthError.tokenExchangeFailed(details)
|
|
|
89
|
+ }
|
|
|
90
|
+ return try JSONDecoder().decode(GoogleUserProfile.self, from: data)
|
|
|
91
|
+ }
|
|
|
92
|
+
|
|
|
93
|
+ func validAccessToken(presentingWindow: NSWindow?) async throws -> String {
|
|
|
94
|
+ if var tokens = try tokenStore.readTokens() {
|
|
|
95
|
+ if tokens.expiresAt.timeIntervalSinceNow > 60 {
|
|
|
96
|
+ return tokens.accessToken
|
|
|
97
|
+ }
|
|
|
98
|
+ if let refreshed = try await refreshTokens(tokens) {
|
|
|
99
|
+ tokens = refreshed
|
|
|
100
|
+ try tokenStore.writeTokens(tokens)
|
|
|
101
|
+ return tokens.accessToken
|
|
|
102
|
+ }
|
|
|
103
|
+ }
|
|
|
104
|
+
|
|
|
105
|
+ let tokens = try await interactiveSignIn(presentingWindow: presentingWindow)
|
|
|
106
|
+ try tokenStore.writeTokens(tokens)
|
|
|
107
|
+ return tokens.accessToken
|
|
|
108
|
+ }
|
|
|
109
|
+
|
|
|
110
|
+ // MARK: - Interactive sign-in (Authorization Code + PKCE)
|
|
|
111
|
+
|
|
|
112
|
+ private func interactiveSignIn(presentingWindow: NSWindow?) async throws -> GoogleOAuthTokens {
|
|
|
113
|
+ _ = presentingWindow
|
|
|
114
|
+ guard let clientId = configuredClientId() else { throw GoogleOAuthError.missingClientId }
|
|
|
115
|
+ guard let clientSecret = configuredClientSecret() else { throw GoogleOAuthError.missingClientSecret }
|
|
|
116
|
+ let codeVerifier = Self.randomURLSafeString(length: 64)
|
|
|
117
|
+ let codeChallenge = Self.pkceChallenge(for: codeVerifier)
|
|
|
118
|
+ let state = Self.randomURLSafeString(length: 32)
|
|
|
119
|
+
|
|
|
120
|
+ let loopback = try await OAuthLoopbackServer.start()
|
|
|
121
|
+ defer { loopback.stop() }
|
|
|
122
|
+ let redirectURI = loopback.redirectURI
|
|
|
123
|
+
|
|
|
124
|
+ var components = URLComponents(string: "https://accounts.google.com/o/oauth2/v2/auth")!
|
|
|
125
|
+ components.queryItems = [
|
|
|
126
|
+ URLQueryItem(name: "client_id", value: clientId),
|
|
|
127
|
+ URLQueryItem(name: "redirect_uri", value: redirectURI),
|
|
|
128
|
+ URLQueryItem(name: "response_type", value: "code"),
|
|
|
129
|
+ URLQueryItem(name: "scope", value: scopes.joined(separator: " ")),
|
|
|
130
|
+ URLQueryItem(name: "state", value: state),
|
|
|
131
|
+ URLQueryItem(name: "code_challenge", value: codeChallenge),
|
|
|
132
|
+ URLQueryItem(name: "code_challenge_method", value: "S256"),
|
|
|
133
|
+ URLQueryItem(name: "access_type", value: "offline"),
|
|
|
134
|
+ URLQueryItem(name: "prompt", value: "consent")
|
|
|
135
|
+ ]
|
|
|
136
|
+
|
|
|
137
|
+ guard let authURL = components.url else { throw GoogleOAuthError.invalidCallbackURL }
|
|
|
138
|
+ guard NSWorkspace.shared.open(authURL) else { throw GoogleOAuthError.unableToOpenBrowser }
|
|
|
139
|
+ let callbackURL = try await loopback.waitForCallback()
|
|
|
140
|
+
|
|
|
141
|
+ guard let returnedState = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)?
|
|
|
142
|
+ .queryItems?.first(where: { $0.name == "state" })?.value,
|
|
|
143
|
+ returnedState == state else {
|
|
|
144
|
+ throw GoogleOAuthError.invalidCallbackURL
|
|
|
145
|
+ }
|
|
|
146
|
+
|
|
|
147
|
+ guard let code = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)?
|
|
|
148
|
+ .queryItems?.first(where: { $0.name == "code" })?.value,
|
|
|
149
|
+ code.isEmpty == false else {
|
|
|
150
|
+ throw GoogleOAuthError.missingAuthorizationCode
|
|
|
151
|
+ }
|
|
|
152
|
+
|
|
|
153
|
+ return try await exchangeCodeForTokens(
|
|
|
154
|
+ code: code,
|
|
|
155
|
+ codeVerifier: codeVerifier,
|
|
|
156
|
+ redirectURI: redirectURI,
|
|
|
157
|
+ clientId: clientId,
|
|
|
158
|
+ clientSecret: clientSecret
|
|
|
159
|
+ )
|
|
|
160
|
+ }
|
|
|
161
|
+
|
|
|
162
|
+ private func exchangeCodeForTokens(code: String, codeVerifier: String, redirectURI: String, clientId: String, clientSecret: String) async throws -> GoogleOAuthTokens {
|
|
|
163
|
+ var request = URLRequest(url: URL(string: "https://oauth2.googleapis.com/token")!)
|
|
|
164
|
+ request.httpMethod = "POST"
|
|
|
165
|
+ request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
|
|
|
166
|
+ request.httpBody = Self.formURLEncoded([
|
|
|
167
|
+ "client_id": clientId,
|
|
|
168
|
+ "client_secret": clientSecret,
|
|
|
169
|
+ "code": code,
|
|
|
170
|
+ "code_verifier": codeVerifier,
|
|
|
171
|
+ "redirect_uri": redirectURI,
|
|
|
172
|
+ "grant_type": "authorization_code"
|
|
|
173
|
+ ])
|
|
|
174
|
+
|
|
|
175
|
+ let (data, response) = try await URLSession.shared.data(for: request)
|
|
|
176
|
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
|
|
|
177
|
+ let details = String(data: data, encoding: .utf8) ?? "HTTP \((response as? HTTPURLResponse)?.statusCode ?? -1)"
|
|
|
178
|
+ throw GoogleOAuthError.tokenExchangeFailed(details)
|
|
|
179
|
+ }
|
|
|
180
|
+
|
|
|
181
|
+ struct TokenResponse: Decodable {
|
|
|
182
|
+ let access_token: String
|
|
|
183
|
+ let expires_in: Double
|
|
|
184
|
+ let refresh_token: String?
|
|
|
185
|
+ let scope: String?
|
|
|
186
|
+ let token_type: String?
|
|
|
187
|
+ }
|
|
|
188
|
+
|
|
|
189
|
+ let decoded = try JSONDecoder().decode(TokenResponse.self, from: data)
|
|
|
190
|
+ return GoogleOAuthTokens(
|
|
|
191
|
+ accessToken: decoded.access_token,
|
|
|
192
|
+ refreshToken: decoded.refresh_token,
|
|
|
193
|
+ expiresAt: Date().addingTimeInterval(decoded.expires_in),
|
|
|
194
|
+ scope: decoded.scope,
|
|
|
195
|
+ tokenType: decoded.token_type
|
|
|
196
|
+ )
|
|
|
197
|
+ }
|
|
|
198
|
+
|
|
|
199
|
+ private func refreshTokens(_ tokens: GoogleOAuthTokens) async throws -> GoogleOAuthTokens? {
|
|
|
200
|
+ guard let refreshToken = tokens.refreshToken else { return nil }
|
|
|
201
|
+ guard let clientId = configuredClientId() else { throw GoogleOAuthError.missingClientId }
|
|
|
202
|
+ guard let clientSecret = configuredClientSecret() else { throw GoogleOAuthError.missingClientSecret }
|
|
|
203
|
+
|
|
|
204
|
+ var request = URLRequest(url: URL(string: "https://oauth2.googleapis.com/token")!)
|
|
|
205
|
+ request.httpMethod = "POST"
|
|
|
206
|
+ request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
|
|
|
207
|
+ request.httpBody = Self.formURLEncoded([
|
|
|
208
|
+ "client_id": clientId,
|
|
|
209
|
+ "client_secret": clientSecret,
|
|
|
210
|
+ "refresh_token": refreshToken,
|
|
|
211
|
+ "grant_type": "refresh_token"
|
|
|
212
|
+ ])
|
|
|
213
|
+
|
|
|
214
|
+ let (data, response) = try await URLSession.shared.data(for: request)
|
|
|
215
|
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
|
|
|
216
|
+ return nil
|
|
|
217
|
+ }
|
|
|
218
|
+
|
|
|
219
|
+ struct RefreshResponse: Decodable {
|
|
|
220
|
+ let access_token: String
|
|
|
221
|
+ let expires_in: Double
|
|
|
222
|
+ let scope: String?
|
|
|
223
|
+ let token_type: String?
|
|
|
224
|
+ }
|
|
|
225
|
+
|
|
|
226
|
+ let decoded = try JSONDecoder().decode(RefreshResponse.self, from: data)
|
|
|
227
|
+ return GoogleOAuthTokens(
|
|
|
228
|
+ accessToken: decoded.access_token,
|
|
|
229
|
+ refreshToken: refreshToken,
|
|
|
230
|
+ expiresAt: Date().addingTimeInterval(decoded.expires_in),
|
|
|
231
|
+ scope: decoded.scope ?? tokens.scope,
|
|
|
232
|
+ tokenType: decoded.token_type ?? tokens.tokenType
|
|
|
233
|
+ )
|
|
|
234
|
+ }
|
|
|
235
|
+
|
|
|
236
|
+ // MARK: - Helpers
|
|
|
237
|
+
|
|
|
238
|
+ private static func pkceChallenge(for verifier: String) -> String {
|
|
|
239
|
+ let data = Data(verifier.utf8)
|
|
|
240
|
+ let digest = SHA256.hash(data: data)
|
|
|
241
|
+ return Data(digest).base64URLEncodedString()
|
|
|
242
|
+ }
|
|
|
243
|
+
|
|
|
244
|
+ private static func randomURLSafeString(length: Int) -> String {
|
|
|
245
|
+ var bytes = [UInt8](repeating: 0, count: length)
|
|
|
246
|
+ _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
|
|
|
247
|
+ return Data(bytes).base64URLEncodedString()
|
|
|
248
|
+ }
|
|
|
249
|
+
|
|
|
250
|
+ private static func formURLEncoded(_ params: [String: String]) -> Data {
|
|
|
251
|
+ let allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
|
|
|
252
|
+ let pairs = params.map { key, value -> String in
|
|
|
253
|
+ let k = key.addingPercentEncoding(withAllowedCharacters: allowed) ?? key
|
|
|
254
|
+ let v = value.addingPercentEncoding(withAllowedCharacters: allowed) ?? value
|
|
|
255
|
+ return "\(k)=\(v)"
|
|
|
256
|
+ }
|
|
|
257
|
+ .joined(separator: "&")
|
|
|
258
|
+ return Data(pairs.utf8)
|
|
|
259
|
+ }
|
|
|
260
|
+}
|
|
|
261
|
+
|
|
|
262
|
+private extension Data {
|
|
|
263
|
+ func base64URLEncodedString() -> String {
|
|
|
264
|
+ let s = base64EncodedString()
|
|
|
265
|
+ return s
|
|
|
266
|
+ .replacingOccurrences(of: "+", with: "-")
|
|
|
267
|
+ .replacingOccurrences(of: "/", with: "_")
|
|
|
268
|
+ .replacingOccurrences(of: "=", with: "")
|
|
|
269
|
+ }
|
|
|
270
|
+}
|
|
|
271
|
+
|
|
|
272
|
+private final class OAuthLoopbackServer {
|
|
|
273
|
+ private let queue = DispatchQueue(label: "google.oauth.loopback.server")
|
|
|
274
|
+ private let listener: NWListener
|
|
|
275
|
+ private var readyContinuation: CheckedContinuation<Void, Error>?
|
|
|
276
|
+ private var callbackContinuation: CheckedContinuation<URL, Error>?
|
|
|
277
|
+ private var callbackURL: URL?
|
|
|
278
|
+
|
|
|
279
|
+ private init(listener: NWListener) {
|
|
|
280
|
+ self.listener = listener
|
|
|
281
|
+ }
|
|
|
282
|
+
|
|
|
283
|
+ static func start() async throws -> OAuthLoopbackServer {
|
|
|
284
|
+ let listener = try NWListener(using: .tcp, on: .any)
|
|
|
285
|
+ let server = OAuthLoopbackServer(listener: listener)
|
|
|
286
|
+ try await server.startListening()
|
|
|
287
|
+ return server
|
|
|
288
|
+ }
|
|
|
289
|
+
|
|
|
290
|
+ var redirectURI: String {
|
|
|
291
|
+ let port = listener.port?.rawValue ?? 0
|
|
|
292
|
+ return "http://127.0.0.1:\(port)/oauth2redirect"
|
|
|
293
|
+ }
|
|
|
294
|
+
|
|
|
295
|
+ func waitForCallback(timeoutSeconds: Double = 120) async throws -> URL {
|
|
|
296
|
+ try await withThrowingTaskGroup(of: URL.self) { group in
|
|
|
297
|
+ group.addTask { [weak self] in
|
|
|
298
|
+ guard let self else { throw GoogleOAuthError.invalidCallbackURL }
|
|
|
299
|
+ return try await self.awaitCallback()
|
|
|
300
|
+ }
|
|
|
301
|
+ group.addTask {
|
|
|
302
|
+ try await Task.sleep(nanoseconds: UInt64(timeoutSeconds * 1_000_000_000))
|
|
|
303
|
+ throw GoogleOAuthError.authenticationTimedOut
|
|
|
304
|
+ }
|
|
|
305
|
+
|
|
|
306
|
+ let url = try await group.next()!
|
|
|
307
|
+ group.cancelAll()
|
|
|
308
|
+ return url
|
|
|
309
|
+ }
|
|
|
310
|
+ }
|
|
|
311
|
+
|
|
|
312
|
+ func stop() {
|
|
|
313
|
+ queue.async {
|
|
|
314
|
+ self.listener.cancel()
|
|
|
315
|
+ if let callbackContinuation = self.callbackContinuation {
|
|
|
316
|
+ self.callbackContinuation = nil
|
|
|
317
|
+ callbackContinuation.resume(throwing: GoogleOAuthError.authenticationTimedOut)
|
|
|
318
|
+ }
|
|
|
319
|
+ }
|
|
|
320
|
+ }
|
|
|
321
|
+
|
|
|
322
|
+ private func startListening() async throws {
|
|
|
323
|
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
|
|
|
324
|
+ queue.async {
|
|
|
325
|
+ self.readyContinuation = continuation
|
|
|
326
|
+ self.listener.stateUpdateHandler = { [weak self] state in
|
|
|
327
|
+ guard let self else { return }
|
|
|
328
|
+ switch state {
|
|
|
329
|
+ case .ready:
|
|
|
330
|
+ if let readyContinuation = self.readyContinuation {
|
|
|
331
|
+ self.readyContinuation = nil
|
|
|
332
|
+ readyContinuation.resume()
|
|
|
333
|
+ }
|
|
|
334
|
+ case .failed(let error):
|
|
|
335
|
+ if let readyContinuation = self.readyContinuation {
|
|
|
336
|
+ self.readyContinuation = nil
|
|
|
337
|
+ readyContinuation.resume(throwing: error)
|
|
|
338
|
+ }
|
|
|
339
|
+ case .cancelled:
|
|
|
340
|
+ if let readyContinuation = self.readyContinuation {
|
|
|
341
|
+ self.readyContinuation = nil
|
|
|
342
|
+ readyContinuation.resume(throwing: GoogleOAuthError.invalidCallbackURL)
|
|
|
343
|
+ }
|
|
|
344
|
+ default:
|
|
|
345
|
+ break
|
|
|
346
|
+ }
|
|
|
347
|
+ }
|
|
|
348
|
+ self.listener.newConnectionHandler = { [weak self] connection in
|
|
|
349
|
+ self?.handle(connection: connection)
|
|
|
350
|
+ }
|
|
|
351
|
+ self.listener.start(queue: self.queue)
|
|
|
352
|
+ }
|
|
|
353
|
+ }
|
|
|
354
|
+ }
|
|
|
355
|
+
|
|
|
356
|
+ private func awaitCallback() async throws -> URL {
|
|
|
357
|
+ if let callbackURL { return callbackURL }
|
|
|
358
|
+ return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<URL, Error>) in
|
|
|
359
|
+ queue.async {
|
|
|
360
|
+ if let callbackURL = self.callbackURL {
|
|
|
361
|
+ continuation.resume(returning: callbackURL)
|
|
|
362
|
+ return
|
|
|
363
|
+ }
|
|
|
364
|
+ self.callbackContinuation = continuation
|
|
|
365
|
+ }
|
|
|
366
|
+ }
|
|
|
367
|
+ }
|
|
|
368
|
+
|
|
|
369
|
+ private func handle(connection: NWConnection) {
|
|
|
370
|
+ connection.start(queue: queue)
|
|
|
371
|
+ connection.receive(minimumIncompleteLength: 1, maximumLength: 8192) { [weak self] data, _, _, _ in
|
|
|
372
|
+ guard let self else { return }
|
|
|
373
|
+ let requestLine = data
|
|
|
374
|
+ .flatMap { String(data: $0, encoding: .utf8) }?
|
|
|
375
|
+ .split(separator: "\r\n", omittingEmptySubsequences: false)
|
|
|
376
|
+ .first
|
|
|
377
|
+ .map(String.init)
|
|
|
378
|
+
|
|
|
379
|
+ var parsedURL: URL?
|
|
|
380
|
+ if let requestLine {
|
|
|
381
|
+ let parts = requestLine.split(separator: " ")
|
|
|
382
|
+ if parts.count >= 2 {
|
|
|
383
|
+ let pathAndQuery = String(parts[1])
|
|
|
384
|
+ parsedURL = URL(string: "http://127.0.0.1\(pathAndQuery)")
|
|
|
385
|
+ }
|
|
|
386
|
+ }
|
|
|
387
|
+
|
|
|
388
|
+ self.sendHTTPResponse(connection: connection, success: parsedURL != nil)
|
|
|
389
|
+
|
|
|
390
|
+ if let parsedURL {
|
|
|
391
|
+ self.callbackURL = parsedURL
|
|
|
392
|
+ DispatchQueue.main.async {
|
|
|
393
|
+ // Bring the app back to foreground once OAuth redirects.
|
|
|
394
|
+ NSApp.activate(ignoringOtherApps: true)
|
|
|
395
|
+ }
|
|
|
396
|
+ if let continuation = self.callbackContinuation {
|
|
|
397
|
+ self.callbackContinuation = nil
|
|
|
398
|
+ continuation.resume(returning: parsedURL)
|
|
|
399
|
+ }
|
|
|
400
|
+ self.listener.cancel()
|
|
|
401
|
+ }
|
|
|
402
|
+ connection.cancel()
|
|
|
403
|
+ }
|
|
|
404
|
+ }
|
|
|
405
|
+
|
|
|
406
|
+ private func sendHTTPResponse(connection: NWConnection, success: Bool) {
|
|
|
407
|
+ let body = success
|
|
|
408
|
+ ? "<html><body><h3>Authentication complete</h3><p>You can return to the app.</p></body></html>"
|
|
|
409
|
+ : "<html><body><h3>Authentication failed</h3></body></html>"
|
|
|
410
|
+ let response = """
|
|
|
411
|
+ HTTP/1.1 200 OK\r
|
|
|
412
|
+ Content-Type: text/html; charset=utf-8\r
|
|
|
413
|
+ Content-Length: \(body.utf8.count)\r
|
|
|
414
|
+ Connection: close\r
|
|
|
415
|
+ \r
|
|
|
416
|
+ \(body)
|
|
|
417
|
+ """
|
|
|
418
|
+ connection.send(content: Data(response.utf8), completion: .contentProcessed { _ in })
|
|
|
419
|
+ }
|
|
|
420
|
+}
|
|
|
421
|
+
|
|
|
422
|
+extension GoogleOAuthError: LocalizedError {
|
|
|
423
|
+ var errorDescription: String? {
|
|
|
424
|
+ switch self {
|
|
|
425
|
+ case .missingClientId:
|
|
|
426
|
+ return "Missing Google OAuth Client ID."
|
|
|
427
|
+ case .missingClientSecret:
|
|
|
428
|
+ return "Missing Google OAuth Client Secret."
|
|
|
429
|
+ case .invalidCallbackURL:
|
|
|
430
|
+ return "Invalid OAuth callback URL."
|
|
|
431
|
+ case .missingAuthorizationCode:
|
|
|
432
|
+ return "Google did not return an authorization code."
|
|
|
433
|
+ case .tokenExchangeFailed(let details):
|
|
|
434
|
+ return "Token exchange failed: \(details)"
|
|
|
435
|
+ case .unableToOpenBrowser:
|
|
|
436
|
+ return "Could not open browser for Google sign-in."
|
|
|
437
|
+ case .authenticationTimedOut:
|
|
|
438
|
+ return "Google sign-in timed out."
|
|
|
439
|
+ case .noStoredTokens:
|
|
|
440
|
+ return "No stored Google tokens found."
|
|
|
441
|
+ }
|
|
|
442
|
+ }
|
|
|
443
|
+}
|
|
|
444
|
+
|