forked from kubernetes-sigs/cloud-provider-equinix-metal
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
exchange Metal API key for LB OAuth tokenbefore making LB API requests
- Loading branch information
Showing
2 changed files
with
93 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package emlb | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"time" | ||
|
||
"golang.org/x/oauth2" | ||
) | ||
|
||
type MetalTokenExchanger struct { | ||
metalAPIKey string | ||
client *http.Client | ||
} | ||
|
||
func (m *MetalTokenExchanger) Token() (*oauth2.Token, error) { | ||
tokenExchangeURL := "https://iam.metalctrl.io/api-keys/exchange" | ||
tokenExchangeRequest, err := http.NewRequest("POST", tokenExchangeURL, nil) | ||
if err != nil { | ||
return nil, err | ||
} | ||
tokenExchangeRequest.Header.Add("Authorization", fmt.Sprintf("Bearer %v", m.metalAPIKey)) | ||
|
||
resp, err := m.client.Do(tokenExchangeRequest) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
body, err := io.ReadAll(resp.Body) | ||
resp.Body.Close() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
if resp.StatusCode != http.StatusOK { | ||
return nil, fmt.Errorf("token exchange request failed with status %v, body %v", resp.StatusCode, body) | ||
} | ||
|
||
token := oauth2.Token{} | ||
err = json.Unmarshal(body, &token) | ||
if err != nil { | ||
fmt.Println(len(body)) | ||
fmt.Println(token) | ||
fmt.Println(err) | ||
return nil, err | ||
} | ||
|
||
expiresIn := token.Extra("expires_in") | ||
if expiresIn != nil { | ||
expiresInSeconds := expiresIn.(int) | ||
token.Expiry = time.Now().Add(time.Second * time.Duration(expiresInSeconds)) | ||
} | ||
|
||
return &token, nil | ||
} |