Adding attach role to identity functionality

This commit is contained in:
2026-04-04 00:26:45 -04:00
parent f8d3d3fcff
commit 34dc6c9ab6
4 changed files with 96 additions and 85 deletions

View File

@@ -0,0 +1,90 @@
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
)
func authAttachRoleToIdentity(args []string) {
var useRole string
var targetIdentity string
var targetRole string
authAttachRoleCmd := flag.NewFlagSet("attachrole", flag.ExitOnError)
authAttachRoleCmd.StringVar(&useRole, "use-role", "", "Using role (required)")
authAttachRoleCmd.StringVar(&targetIdentity, "target-identity", "", "Target identity (required)")
authAttachRoleCmd.StringVar(&targetRole, "target-role", "", "Target role (required)")
authAttachRoleCmd.Parse(args)
if useRole == "" {
fmt.Println("Error: --use-role is required")
os.Exit(1)
}
if targetIdentity == "" {
fmt.Println("Error: --target-identity is required")
os.Exit(1)
}
if targetRole == "" {
fmt.Println("Error: --target-role is required")
os.Exit(1)
}
// Get the role token we will use
roleData, err := os.ReadFile("/home/farhan/.pcloud/roles/" + useRole + ".json")
if err != nil {
fmt.Printf("Error opening identity file: %v\n", err)
os.Exit(1)
}
var roleToken RoleToken
err = json.Unmarshal(roleData, &roleToken)
if err != nil {
fmt.Printf("Error reading identity file: %v\n", err)
os.Exit(1)
}
var attachRoleToIdentityRequest AttachRoleToIdentityRequest
attachRoleToIdentityRequest.Identity = targetIdentity
attachRoleToIdentityRequest.Role = targetRole
attachRoleToIdentityRequestData, err := json.Marshal(attachRoleToIdentityRequest)
if err != nil {
fmt.Println("Error encoding JSON:", err)
os.Exit(1)
}
url := endpoint + "/identity/allow-role-to-identity"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(attachRoleToIdentityRequestData))
if err != nil {
log.Fatal("Error creating request:", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+roleToken.Token)
// Set headers
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal("Error making request:", err)
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
if resp.StatusCode != http.StatusOK {
log.Fatal("Attach role to identity failed with status:", resp.Status)
}
// fmt.Printf("Attaching role %s to identity %s\n", targetRole, targetIdentity)
}