Skip to content

Instantly share code, notes, and snippets.

@bobbyiliev
Created November 1, 2023 16:54
Show Gist options
  • Save bobbyiliev/2a53dc79e60477f2bbf3c128cff61f2d to your computer and use it in GitHub Desktop.
Save bobbyiliev/2a53dc79e60477f2bbf3c128cff61f2d to your computer and use it in GitHub Desktop.
Mock cloud resources auth via an app password
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
const (
PREFIX = "mzp_"
DEFAULT_ADMIN_ENDPOINT = "https://admin.cloud.materialize.com"
)
func formatDashlessUuid(dashlessUuid string) string {
parts := []string{
dashlessUuid[0:8],
dashlessUuid[8:12],
dashlessUuid[12:16],
dashlessUuid[16:20],
dashlessUuid[20:],
}
return strings.Join(parts, "-")
}
func parseAppPassword(password string) (string, string, error) {
strippedPassword := strings.TrimPrefix(password, PREFIX)
var clientId, secretKey string
// Remove any non-hexadecimal characters
re := regexp.MustCompile("[^0-9a-fA-F]")
filteredChars := re.ReplaceAllString(strippedPassword, "")
if len(filteredChars) < 64 {
return "", "", errors.New("invalid app password")
}
clientId = formatDashlessUuid(filteredChars[0:32])
secretKey = formatDashlessUuid(filteredChars[32:])
return clientId, secretKey, nil
}
func getToken(appPassword string, endpoint string) (string, error) {
adminEndpoint := fmt.Sprintf("%s/identity/resources/auth/v1/api-token", endpoint)
clientId, secretKey, err := parseAppPassword(appPassword)
if err != nil {
return "", err
}
fmt.Println("Admin Endpoint:", adminEndpoint)
fmt.Println("Client ID:", clientId)
fmt.Println("Secret Key:", secretKey)
payload := map[string]string{
"clientId": clientId,
"secret": secretKey,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return "", err
}
resp, err := http.Post(adminEndpoint, "application/json", bytes.NewBuffer(payloadBytes))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
fmt.Println("Server Response:", string(body))
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
return "", err
}
if token, exists := result["accessToken"]; exists {
return token.(string), nil
}
return "", errors.New("no access token found in response")
}
func main() {
appPassword := "APP_PASS_HERE"
endpoint := DEFAULT_ADMIN_ENDPOINT
token, err := getToken(appPassword, endpoint)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Access Token:", token)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment