Files
upc/authenticate.go

157 lines
3.8 KiB
Go

package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"libshared"
"log"
"net/http"
"os"
"path/filepath"
)
var authCmd *flag.FlagSet
type AuthenticateRequest struct {
Accountid string `json:"accountid"`
Username string `json:"username"`
Password string `json:"password"`
}
type AuthenticateResponse struct {
Token string `json:"token"`
}
func authLocalGetToken() {
}
func authLocalAuthenticate(args []string) {
var authUsername string
var authPassword string
var authAccountid string
var outputFormat string
var saveProfile string
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)")
outputFormat = "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)
}