From 4641e7692134313fc374ffc22385039c8ea4fc3f Mon Sep 17 00:00:00 2001 From: Siddhesh Khandagale Date: Wed, 29 Nov 2023 03:58:41 +0530 Subject: [PATCH] Updates --- cmd/create.go | 1 - cmd/login.go | 19 ++++--- cmd/root.go | 4 +- cmd/version.go | 2 +- go.mod | 5 +- go.sum | 2 + lib/init.go | 44 +++++++-------- lib/user.go | 146 +++++++++++++++++++++++++++++++------------------ 8 files changed, 132 insertions(+), 91 deletions(-) diff --git a/cmd/create.go b/cmd/create.go index 814d9b6..c693b0f 100644 --- a/cmd/create.go +++ b/cmd/create.go @@ -52,7 +52,6 @@ var createCmd = &cobra.Command{ } email := strings.Replace(userData.Email, "@", "-", -1) Newemail := strings.Replace(email, ".", "-", -1) - fmt.Println(Newemail) err = lib.Create(Newemail) if err != nil { diff --git a/cmd/login.go b/cmd/login.go index 421d397..3f2d47f 100644 --- a/cmd/login.go +++ b/cmd/login.go @@ -14,7 +14,6 @@ import ( "github.com/Siddheshk02/Securelee-cli/lib" "github.com/mattn/go-colorable" - "github.com/pangeacyber/pangea-go/pangea-sdk/v2/service/authn" "github.com/spf13/cobra" "golang.org/x/term" ) @@ -46,7 +45,7 @@ var loginCmd = &cobra.Command{ var choice int var token string var err error - var result *authn.ClientTokenCheckResult + var result lib.ResponseData var ch, usertype string fmt.Fprintf(out, "\n%s Select any one option: %s\n", yellow, reset) fmt.Fprintf(out, "\n%s > 1. Login using Socials through Browser%s\n", yellow, reset) @@ -96,10 +95,12 @@ var loginCmd = &cobra.Command{ return } - token, usertype, err = lib.LoginWithEmail(email, string(password)) + // token, usertype, err = lib.LoginWithEmail(email, string(password)) + + if token == "" && usertype == "" && err == nil { + fmt.Println("\033[31m", "\n > Failed to Login! Please try another login method. \033[0m") + os.Exit(0) - if token == "" && usertype == "" && err != nil { - log.Fatalf(err.Error()) } else if token == "" && usertype != "" && err == nil { fmt.Println("\033[31m", "\n > ", usertype, "\033[0m") fmt.Println("") @@ -119,7 +120,7 @@ var loginCmd = &cobra.Command{ return } - parsedTime, err := time.Parse(time.RFC3339, result.Expire) + parsedTime, err := time.Parse(time.RFC3339, result.Result.Expire) if err != nil { log.Fatal(err.Error()) } @@ -132,9 +133,9 @@ var loginCmd = &cobra.Command{ Expiry time.Time `json:"expiry"` }{ Token: token, - Email: result.Email, - Name: result.Profile["first_name"] + " " + result.Profile["last_name"], - User_ID: result.ID, + Email: result.Result.Email, + Name: result.Result.Profile.FirstName + " " + result.Result.Profile.LastName, + User_ID: result.Result.ID, Expiry: parsedTime, } diff --git a/cmd/root.go b/cmd/root.go index c8a79da..6a37414 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -14,7 +14,7 @@ import ( // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "Securelee-cli", - Version: "v1.1.6", + Version: "v1.1.7", Short: "\nA CLI based Vault App for storing your Secret Messages or Keys Securely.", Long: `A CLI based Vault App for storing your Secret Messages or Keys Securely.`, // Uncomment the following line if your bare application @@ -28,7 +28,7 @@ var rootCmd = &cobra.Command{ renderStr, _ := ascii.RenderOpts("Securelee.", options) fmt.Print(renderStr) - fmt.Print(" > v1.1.6") + fmt.Print(" > v1.1.7") }, } diff --git a/cmd/version.go b/cmd/version.go index b55a9ab..5902057 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -16,7 +16,7 @@ var versionCmd = &cobra.Command{ Short: "Version of the Securelee CLI.", Long: `Version of the Securelee CLI.`, Run: func(cmd *cobra.Command, args []string) { - color.Cyan("\n > Securelee - v1.1.6") + color.Cyan("\n > Securelee - v1.1.7") fmt.Print("\n") }, } diff --git a/go.mod b/go.mod index df066b1..43153cc 100644 --- a/go.mod +++ b/go.mod @@ -4,16 +4,17 @@ go 1.20 require github.com/pangeacyber/pangea-go/pangea-sdk/v3 v3.0.0 -require github.com/fatih/color v1.16.0 +require github.com/fatih/color v1.16.0 require ( github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-retryablehttp v0.7.2 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/joho/godotenv v1.5.1 - github.com/mattn/go-colorable v0.1.13 + github.com/mattn/go-colorable v0.1.13 github.com/mattn/go-isatty v0.0.20 // indirect github.com/mbndr/figlet4go v0.0.0-20190224160619-d6cef5b186ea + github.com/pangeacyber/pangea-go/pangea-sdk v1.10.0 github.com/pangeacyber/pangea-go/pangea-sdk/v2 v2.3.0 github.com/rs/zerolog v1.29.1 // indirect github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 diff --git a/go.sum b/go.sum index 8136ffd..3e30583 100644 --- a/go.sum +++ b/go.sum @@ -24,6 +24,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mbndr/figlet4go v0.0.0-20190224160619-d6cef5b186ea h1:mQncVDBpKkAecPcH2IMGpKUQYhwowlafQbfkz2QFqkc= github.com/mbndr/figlet4go v0.0.0-20190224160619-d6cef5b186ea/go.mod h1:QzTGLGoOqLHUBK8/EZ0v4Fa4CdyXmdyRwCHcl0YbeO4= +github.com/pangeacyber/pangea-go/pangea-sdk v1.10.0 h1:r7htbn5m56+4J8d5ZquCoBD6eRf80LmFQ4mEZfu3ttA= +github.com/pangeacyber/pangea-go/pangea-sdk v1.10.0/go.mod h1:TrRBjwbk83YhtHqCNsrMf//iz9yj/b3139mvts20qH0= github.com/pangeacyber/pangea-go/pangea-sdk/v2 v2.3.0 h1:s72iLPWawcKFh8GO5eP1qev5Zp/VPGavYaqZ3CS3JWw= github.com/pangeacyber/pangea-go/pangea-sdk/v2 v2.3.0/go.mod h1:VsuUoA8XBjZGMI8hu2UlWCBQau9enkisMdWr2AnxvqI= github.com/pangeacyber/pangea-go/pangea-sdk/v3 v3.0.0 h1:24yIYHJ8iYUwt74+O9WRewwAgSYDQj2i6Ngkq81Q7jY= diff --git a/lib/init.go b/lib/init.go index 8336cde..3906b2f 100644 --- a/lib/init.go +++ b/lib/init.go @@ -1,50 +1,50 @@ package lib import ( - "log" - "os" - - "github.com/joho/godotenv" "github.com/pangeacyber/pangea-go/pangea-sdk/v2/pangea" "github.com/pangeacyber/pangea-go/pangea-sdk/v2/service/authn" "github.com/pangeacyber/pangea-go/pangea-sdk/v2/service/vault" ) func Init() *authn.AuthN { - err := godotenv.Load(".env") - if err != nil { - log.Fatal("\033[31m", "Error loading .env file", "\033[0m") - } + // err := godotenv.Load(".env") + // if err != nil { + // log.Fatal("\033[31m", "Error loading .env file", "\033[0m") + // } // Get token - token := os.Getenv("PANGEA_AUTHN_TOKEN") - if token == "" { - log.Fatal("\033[31m", "Unauthorized: No token present", "\033[0m") - } + // token := os.Getenv("PANGEA_AUTHN_TOKEN") + // if token == "" { + // log.Fatal("\033[31m", "Unauthorized: No token present", "\033[0m") + // } + token := "pts_xajlrac4we4mufoebqgejbrh2ieq72c4" + domain := "aws.us.pangea.cloud" // Create config and client client := authn.New(&pangea.Config{ Token: token, - Domain: os.Getenv("PANGEA_DOMAIN"), + Domain: domain, }) return client } func InitVault() vault.Client { - err := godotenv.Load(".env") - if err != nil { - log.Fatal("\033[31m", "Error loading .env file", "\033[0m") - } + // err := godotenv.Load(".env") + // if err != nil { + // log.Fatal("\033[31m", "Error loading .env file", "\033[0m") + // } // Get token - token := os.Getenv("PANGEA_VAULT_TOKEN") - if token == "" { - log.Fatal("\033[31m", "Unauthorized: No token present", "\033[0m") - } + // token := os.Getenv("PANGEA_VAULT_TOKEN") + // if token == "" { + // log.Fatal("\033[31m", "Unauthorized: No token present", "\033[0m") + // } + token := "pts_xajlrac4we4mufoebqgejbrh2ieq72c4" + domain := "aws.us.pangea.cloud" // Create config and client client := vault.New(&pangea.Config{ Token: token, - Domain: os.Getenv("PANGEA_DOMAIN"), + Domain: domain, }) return client diff --git a/lib/user.go b/lib/user.go index 1d44df0..f705538 100644 --- a/lib/user.go +++ b/lib/user.go @@ -1,20 +1,19 @@ package lib import ( + "bytes" "context" "encoding/json" - "errors" "fmt" "io/ioutil" "log" + "net/http" "os" "os/user" "path/filepath" - "regexp" "time" "github.com/pangeacyber/pangea-go/pangea-sdk/v2/service/authn" - "github.com/pangeacyber/pangea-go/pangea-sdk/v3/pangea" "github.com/skratchdot/open-golang/open" ) @@ -71,28 +70,62 @@ func Check() bool { return false } +type ResponseData struct { + RequestID string `json:"request_id"` + RequestTime string `json:"request_time"` + ResponseTime string `json:"response_time"` + Status string `json:"status"` + Result ResultData +} + +type ResultData struct { + ID string `json:"id"` + Type string `json:"type"` + Life int `json:"life"` + Expire string `json:"expire"` + Identity string `json:"identity"` + Email string `json:"email"` + Profile ProfileData + CreatedAt string `json:"created_at"` +} + +type ProfileData struct { + LastLoginCity string `json:"Last-Login-City"` + LastLoginCountry string `json:"Last-Login-Country"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` +} + // Check Token Validity -func CheckToken(token string) (*authn.ClientTokenCheckResult, string) { - ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second) - defer cancelFn() - client := Init() +func CheckToken(token string) (ResponseData, string) { - input := authn.ClientTokenCheckRequest{ - Token: token, - } + url := "https://authn.aws.us.pangea.cloud/v2/client/token/check" + method := "POST" - resp, err := client.Client.Token.Check(ctx, input) + payload, _ := json.Marshal(map[string]string{ + "token": token, + }) - if err != nil && resp == nil { - return nil, "No User" - } + AuthToken := "Bearer " + "pts_xajlrac4we4mufoebqgejbrh2ieq72c4" - if *resp.Status == "Success" { - return resp.Result, "" - } + client1 := &http.Client{} + req, _ := http.NewRequest(method, url, bytes.NewBuffer(payload)) + req.Header.Add("Content-Type", "application/json") + req.Header.Add("Authorization", AuthToken) + + res, _ := client1.Do(req) + defer res.Body.Close() - return nil, "Invalid Token" + body, _ := ioutil.ReadAll(res.Body) + var responseData ResponseData + _ = json.Unmarshal(body, &responseData) + + if responseData.Status == "Success" { + return responseData, "" + } + + return ResponseData{}, "Invalid Token" } func FileExists(filename string) bool { @@ -166,18 +199,14 @@ func LoginWithEmail(Email string, Password string) (string, string, error) { // Logout the Current User's Session func Logout() error { - res := Check() - if !res { + ref := Check() + if !ref { fmt.Print("\033[31m", "\n > No User logged in, You must Login to use Securelee Vault Services.\n", "\033[0m") fmt.Print("\033[36m", "\n > Use 'Securelee-cli login' command to complete the Authentication.\n", "\033[0m") fmt.Println("") os.Exit(0) } - ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second) - defer cancelFn() - client := Init() - user, err := user.Current() if err != nil { log.Fatal("\033[31m", err, "\033[0m") @@ -196,19 +225,32 @@ func Logout() error { return err } - token := TokenData.Token + url := "https://authn.aws.us.pangea.cloud/v2/client/session/logout" + method := "POST" + payload, _ := json.Marshal(map[string]string{ + "token": TokenData.Token, + }) + + AuthToken := "Bearer " + "pts_xajlrac4we4mufoebqgejbrh2ieq72c4" + + client := &http.Client{} + req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) - input := authn.ClientSessionLogoutRequest{ - Token: token, - } - _, err = client.Client.Session.Logout(ctx, input) if err != nil { - // return err - fmt.Print("\033[31m", "\n > No User logged in, You must Login to use Securelee Vault Services.\n", "\033[0m") - fmt.Print("\033[36m", "\n > Use 'Securelee-cli login' command to complete the Authentication.\n", "\033[0m") - fmt.Println("") + fmt.Println("Error !!! Please Try Again.") os.Exit(0) } + req.Header.Add("Content-Type", "application/json") + req.Header.Add("Authorization", AuthToken) + + res, _ := client.Do(req) + + defer res.Body.Close() + + body, _ := ioutil.ReadAll(res.Body) + + var responseData ResponseData + _ = json.Unmarshal(body, &responseData) err = os.Remove(filePath) if err != nil { @@ -228,32 +270,28 @@ type APIError struct { } func NewUser(Email string) (string, error) { - ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second) - defer cancelFn() - client := Init() - input := authn.UserProfileGetRequest{ - Email: pangea.String(Email), - } - resp, err := client.User.Profile.Get(ctx, input) + url := "https://authn.aws.us.pangea.cloud/v2/user/profile/get" + method := "POST" - if resp == nil { - re := regexp.MustCompile(`\{[^{}]*\}`) - match := re.Find([]byte(err.Error())) + payload, _ := json.Marshal(map[string]string{ + "email": Email, + }) - if match == nil { - return "", errors.New("No JSON data found in the error message") - } + AuthToken := "Bearer " + "pts_xajlrac4we4mufoebqgejbrh2ieq72c4" - var apiError APIError - err = json.Unmarshal(match, &apiError) - if err != nil { - return "", err + client1 := &http.Client{} + req, _ := http.NewRequest(method, url, bytes.NewBuffer(payload)) + req.Header.Add("Content-Type", "application/json") + req.Header.Add("Authorization", AuthToken) - } + res, _ := client1.Do(req) + defer res.Body.Close() - return apiError.Status, nil - } + body, _ := ioutil.ReadAll(res.Body) + + var responseData ResponseData + _ = json.Unmarshal(body, &responseData) - return *resp.Status, nil + return responseData.Status, nil }