-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathCredentials.kt
57 lines (52 loc) · 2.23 KB
/
Credentials.kt
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
package ftl.client.google
import com.google.api.client.http.GoogleApiLogger
import com.google.api.client.http.HttpRequestInitializer
import com.google.auth.oauth2.AccessToken
import com.google.auth.oauth2.GoogleCredentials
import com.google.auth.oauth2.ServiceAccountCredentials
import flank.common.defaultCredentialPath
import flank.common.isWindows
import ftl.config.FtlConstants
import ftl.http.HttpTimeoutIncrease
import ftl.run.exception.FlankGeneralError
import java.io.IOException
import java.util.Date
val credential: GoogleCredentials by lazy {
when {
FtlConstants.useMock -> GoogleCredentials.create(AccessToken("mock", Date()))
else ->
runCatching {
GoogleApiLogger.silenceComputeEngine()
ServiceAccountCredentials.getApplicationDefault()
}.getOrElse {
when {
isWindows -> loadCredentialsWindows()
UserAuth.exists() -> UserAuth.load()
else -> throw FlankGeneralError("Error: Failed to read service account credential.\n${it.message}")
}
}
}
}
private fun loadCredentialsWindows() = runCatching {
loadGoogleAccountCredentials()
}.getOrElse {
if (UserAuth.exists()) UserAuth.load()
else throw FlankGeneralError("Error: Failed to read service account credential.\n${it.message}")
}
private fun loadGoogleAccountCredentials(): GoogleCredentials = try {
GoogleCredentials.fromStream(defaultCredentialPath.toFile().inputStream())
} catch (e: IOException) {
throw FlankGeneralError("Error: Failed to read service account credential.\n${e.message}")
}
val httpCredential: HttpRequestInitializer by lazy {
if (FtlConstants.useMock) {
HttpRequestInitializer {}
} else {
// Authenticate with https://github.com/googleapis/google-auth-library-java
// Scope is required.
// https://developers.google.com/identity/protocols/googlescopes
// https://developers.google.com/identity/protocols/application-default-credentials
// https://cloud.google.com/sdk/gcloud/reference/alpha/compute/instances/set-scopes
HttpTimeoutIncrease(credential.createScoped(listOf("https://www.googleapis.com/auth/cloud-platform")))
}
}