GoogleCloud: re fetch token on expiry

This commit is contained in:
end-4
2026-04-05 21:52:50 +02:00
parent cc582fd113
commit 6050148835
2 changed files with 38 additions and 16 deletions
@@ -12,6 +12,7 @@ Singleton {
property bool keyError: false
property bool keyReady: false
property string token: ""
property date tokenExpiry
property bool tokenError: false
property bool tokenReady: false
readonly property string projectId: keyProjectId
@@ -21,7 +22,14 @@ Singleton {
readonly property string tokenForKeyScriptPath: Quickshell.shellPath("services/gCloud/token-from-key-venv.sh")
function load() {
// Dummy for init
// Init load will be handled by Component.onCompleted
if (!tokenReady) return;
// We just reload if key expired
if (new Date() >= root.tokenExpiry) {
root.tokenReady = false;
root.keyReady = false;
loadKeyIfPossible();
}
}
function setKeyJson(str: string): bool {
@@ -41,20 +49,26 @@ Singleton {
return;
}
tokenProc.runSequence([(() => { // prep token fetcher
tokenProc.environment.SERVICE_KEY_CONTENT = JSON.stringify(root.keyContent);
tokenProc.command = [ //
"bash", "-c" //
, `${tokenForKeyScriptPath} "$SERVICE_KEY_CONTENT"`];
}), [] // run token fetcher
, (out => {
if (out.startsWith("Error")) {
root.tokenError = true;
} else {
root.tokenError = false;
root.token = out.trim();
}
root.tokenReady = true;
})]);
tokenProc.environment.SERVICE_KEY_CONTENT = JSON.stringify(root.keyContent);
tokenProc.command = [ //
"bash", "-c" //
, `${tokenForKeyScriptPath} "$SERVICE_KEY_CONTENT"`];
}), //
[], // run token fetcher
((out) => {
try {
const data = JSON.parse(out)
root.token = data.token
// Js wants millis instead of seconds
root.tokenExpiry = new Date(data.expiry * 1000)
root.tokenError = false;
} catch(e) {
root.tokenError = true;
print("[GoogleCloud] Failed to parse token response: " + e)
}
root.tokenReady = true;
}
)]);
}
function loadKeyIfPossible() {
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
import calendar
import sys
import json
import google.auth.transport.requests
@@ -16,8 +17,15 @@ def get_token(json_str):
# Refresh to get the access token
request = google.auth.transport.requests.Request()
scoped_creds.refresh(request)
token = scoped_creds.token
expiry = int(calendar.timegm(scoped_creds.expiry.utctimetuple()))
print(scoped_creds.token)
print(json.dumps({
"token": token,
"expiry": expiry
}))
except Exception as e:
sys.stderr.write(f"Error: {str(e)}\n")
sys.exit(1)