Google service account authentication for the Google APIs.
import google
Server programs reach the Google APIs through a "service account". Get the account JSON file from the Google console, read it with ParseServiceAccount, and get a token for the scope you need with AccessToken; then send it in your net/http requests with Authorization. Keep the service account file as carefully as a password.
Types
ServiceAccount
struct ServiceAccount| Name | Type | Description |
|---|---|---|
client_email | str = "" | The account email. |
private_key | str = "" | The PEM private key. |
token_uri | str = "https://oauth2.googleapis.com/token" | The address the token comes from. |
project_id | str = "" | The project id. |
ok | bool = false | It was read correctly. |
import google
func main:
document := `{"type":"service_account","project_id":"salam-demo","client_email":"bot@salam-demo.iam.gserviceaccount.com","private_key":"(the private key goes here)"}`
account := google.ParseServiceAccount(document)
println account.ok, account.project_id, account.client_email
println account.token_uri
println account.private_key.len() > 0
println google.ParseServiceAccount(`{"project_id":"x"}`).ok
println google.Authorization("ya29.abc")
println google.SCOPE_FCM
println google.SCOPE_STORAGE
println google.SCOPE_CLOUD
endConstants and variables
SCOPE_FCM
const SCOPE_FCM: str = "https://www.googleapis.com/auth/firebase.messaging"The example for this item is shown with the ones above: google-Account.salam
SCOPE_STORAGE
const SCOPE_STORAGE: str = "https://www.googleapis.com/auth/devstorage.read_write"The example for this item is shown with the ones above: google-Account.salam
SCOPE_CLOUD
const SCOPE_CLOUD: str = "https://www.googleapis.com/auth/cloud-platform"The example for this item is shown with the ones above: google-Account.salam
Functions
ParseServiceAccount
func ParseServiceAccount(document: str): ServiceAccountThe example for this item is shown with the ones above: google-Account.salam
AccessToken
func AccessToken(sa: ServiceAccount, scope: str, ok &: bool): strimport google
import io
import net.http
func main:
account := google.ParseServiceAccount(io.ReadFile("service-account.json"))
if not account.ok:
println "the service account file is not valid"
ret
end
mut good := false
token := google.AccessToken(account, google.SCOPE_STORAGE, good)
if not good:
println "the token was not granted"
ret
end
mut headers := http.NewHeaders()
headers.insert("Authorization", google.Authorization(token))
r := http.GetWith("https://storage.googleapis.com/storage/v1/b?project=" + account.project_id, headers)
println http.Status(r)
google.Forget(account)
endForget
func Forget(sa: ServiceAccount)The example for this item is shown with the ones above: google-Token.salam
Authorization
func Authorization(token: str): strAuthorization header with the token.The example for this item is shown with the ones above: google-Account.salam