-
Notifications
You must be signed in to change notification settings - Fork 23
/
gcar-auth.gradle
70 lines (55 loc) · 2.26 KB
/
gcar-auth.gradle
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
63
64
65
66
67
68
69
70
import java.util.concurrent.TimeUnit
class GoogleArtifactRegistryCredentials {
private final String username;
private final String password;
GoogleArtifactRegistryCredentials(String username, String password) {
this.username = username
this.password = password
}
String getUsername() {
return this.username
}
String getPassword() {
return this.password
}
}
class ResolveGoogleArtifactRegistryCredentialsAction implements Action<Credentials> {
def resolveGCARCredentials() {
def serviceAccountKeyFile = new File("${System.getenv('HOME')}/gcp-service-account-key.json")
if (serviceAccountKeyFile.exists()) {
return resolveSAKeyCredentials(serviceAccountKeyFile)
}
//SA key is not present on path `$HOME/gcp-service-account-key.json`.
//Fall back to using access token of any active account.
return resolveUserCredentials()
}
def resolveSAKeyCredentials(serviceAccountKeyFile) {
def username = "_json_key_base64"
def password = serviceAccountKeyFile.text.bytes.encodeBase64().toString()
return new GoogleArtifactRegistryCredentials(username, password)
}
def resolveUserCredentials() {
def sout = new StringBuilder(), serr = new StringBuilder()
try {
def proc = ['gcloud', 'auth', 'print-access-token'].execute(null, new File('.'))
proc.consumeProcessOutput(sout, serr)
proc.waitFor(5, TimeUnit.SECONDS)
if (!serr.allWhitespace) {
println "Unable to retrieve access token: ${serr.toString()}"
}
return new GoogleArtifactRegistryCredentials("oauth2accesstoken", sout.toString())
} catch (e) {
println "Errors returned by `gcloud auth print-access-token`: $serr, result: $sout"
throw new Exception('Unable to retrieve access token ', e)
}
}
@Override
void execute(Credentials credentials) {
def gCARCredentials = resolveGCARCredentials()
credentials.setUsername(gCARCredentials.getUsername())
credentials.setPassword(gCARCredentials.getPassword())
}
}
ext {
resolveGCARCredentialsAction = { new ResolveGoogleArtifactRegistryCredentialsAction() }
}