Files
upc/authenticate.go

276 lines
6.8 KiB
Go

package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"libshared"
"log"
"net/http"
"os"
"path/filepath"
)
type AuthenticateRequest struct {
Accountid string `json:"accountid"`
Username string `json:"username"`
Password string `json:"password"`
}
type AuthenticateResponse struct {
Token string `json:"token"`
}
type RoleToken struct {
Token string `json:"token"`
}
type AttachRoleToIdentityRequest struct {
Identity string `json:"identity"`
Role string `json:"role"`
}
var authCmd *flag.FlagSet
var identityCommands = []Command{
{
Names: []string{"login"},
Description: "Login with username and password",
Handler: authLocalAuthenticate,
},
{
Names: []string{"attachrole"},
Description: "Attach Role to Identity",
Handler: authAttachRoleToIdentity,
},
}
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)
}
func authLocalAuthenticate(args []string) {
var authUsername string
var authPassword string
var authAccountid string
var outputFormat string
var saveProfile string
// fmt.Println("----")
// fmt.Println(args)
authCmd = flag.NewFlagSet("authenticate", flag.ExitOnError)
authCmd.StringVar(&saveProfile, "save-profile", "", "Save authentication profile with given name")
authCmd.StringVar(&authUsername, "u", "", "Username (required)")
authCmd.StringVar(&authUsername, "username", "", "Username (required)")
authCmd.StringVar(&authPassword, "p", "", "Password (required)")
authCmd.StringVar(&authPassword, "password", "", "Password (required)")
authCmd.StringVar(&authAccountid, "a", "", "Account ID (required)")
authCmd.StringVar(&authAccountid, "account", "", "Account ID (required)")
authCmd.StringVar(&outputFormat, "o", "json", "Output format (text or json)")
authCmd.Parse(args)
if authAccountid == "" {
fmt.Print("Account ID: ")
fmt.Scanln(&authAccountid)
}
if authUsername == "" {
fmt.Print("Username: ")
fmt.Scanln(&authUsername)
}
if authPassword == "" {
fmt.Print("Password: ")
fmt.Scanln(&authPassword)
}
if (outputFormat != "json") && (outputFormat != "text") && (outputFormat != "silent") {
log.Fatal("Invalid output format. Use 'json', 'text', or 'silent'.")
}
var authenticaterequest AuthenticateRequest
authenticaterequest.Accountid = authAccountid
authenticaterequest.Username = authUsername
authenticaterequest.Password = authPassword
authenticaterequestpostdata, err := json.Marshal(authenticaterequest)
if err != nil {
fmt.Println("Error encoding JSON:", err)
os.Exit(1)
}
url := endpoint + "/identity/authenticate"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(authenticaterequestpostdata))
if err != nil {
log.Fatal("Error creating request:", err)
}
// 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()
if resp.StatusCode != http.StatusOK {
log.Fatal("Authentication failed with status:", resp.Status)
}
apiresponse := libshared.APIResponse[AuthenticateResponse]{}
// var result map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&apiresponse)
if err != nil {
log.Fatal("Error decoding response:", err)
}
if saveProfile != "" {
home, err := os.UserHomeDir()
if err != nil {
panic(err)
}
dir := filepath.Dir(home + "/.pcloud/identities/" + saveProfile + ".json")
err = os.MkdirAll(dir, 0700)
if err != nil {
log.Fatal("Error creating directory:", err)
}
profileData, err := json.MarshalIndent(apiresponse.Content, "", "\t")
if err != nil {
log.Fatal("Error encoding profile JSON:", err)
}
err = os.Remove(home + "/.pcloud/identities/" + saveProfile + ".json")
if err != nil && !os.IsNotExist(err) {
log.Fatal("Error removing profile:", err)
}
err = os.WriteFile(home+"/.pcloud/identities/"+saveProfile+".json", profileData, 0600)
if err != nil {
log.Fatal("Error saving profile:", err)
}
}
switch outputFormat {
case "json":
jsonOutput, err := json.MarshalIndent(apiresponse.Content, "", "\t")
if err != nil {
log.Fatal("Error encoding JSON output:", err)
}
fmt.Println(string(jsonOutput))
case "text":
fmt.Printf("Status: %s\nMessage: %s\n", apiresponse.Status, apiresponse.Message)
case "silent":
}
}
/*
func authenticateMain(args []string) {
authCmd = flag.NewFlagSet("auth", flag.ExitOnError)
authLocalAuthenticate(args)
}
*/
func authenticateMain(args []string) {
if len(args) < 1 {
fmt.Println("Error: subcommand is required")
os.Exit(1)
}
subcommand := args[0]
cmd := findCommand(subcommand, identityCommands)
if cmd == nil {
fmt.Println("Error: unknown command:", subcommand)
os.Exit(1)
}
cmd.Handler(args[1:])
}