forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeiumAuthService.swift
More file actions
63 lines (53 loc) · 1.99 KB
/
CodeiumAuthService.swift
File metadata and controls
63 lines (53 loc) · 1.99 KB
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
61
62
import Configs
import Foundation
import KeychainAccess
public final class CodeiumAuthService {
public init() {}
let codeiumKeyKey = "codeiumAuthKey"
let keychain: Keychain = {
let info = Bundle.main.infoDictionary
return Keychain(service: keychainService, accessGroup: keychainAccessGroup)
.attributes([
kSecUseDataProtectionKeychain as String: true,
])
}()
var key: String? { try? keychain.getString(codeiumKeyKey) }
public var isSignedIn: Bool { return key != nil }
public func signIn(token: String) async throws {
let key = try await generate(token: token)
try keychain.set(key, key: codeiumKeyKey)
}
public func signOut() async throws {
try keychain.remove(codeiumKeyKey)
}
struct GenerateKeyRequestBody: Codable {
var firebase_id_token: String
}
struct GenerateKeyResponseBody: Codable {
var api_key: String
}
struct GenerateKeyErrorResponseBody: Codable, Error, LocalizedError {
var detail: String
var errorDescription: String? { detail }
}
func generate(token: String) async throws -> String {
var request = URLRequest(url: URL(string: "https://api.codeium.com/register_user/")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let requestBody = GenerateKeyRequestBody(firebase_id_token: token)
let requestData = try JSONEncoder().encode(requestBody)
request.httpBody = requestData
let (data, _) = try await URLSession.shared.data(for: request)
do {
let response = try JSONDecoder().decode(GenerateKeyResponseBody.self, from: data)
return response.api_key
} catch {
if let response = try? JSONDecoder()
.decode(GenerateKeyErrorResponseBody.self, from: data)
{
throw response
}
throw error
}
}
}