Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add basic commands for account

Neeraj Gupta1bc363ac8d20
diff --git a/cmd/account.go b/cmd/account.go
new file mode 100644
index 0000000000..454d966a6c
--- /dev/null
+++ b/cmd/account.go
@@ -0,0 +1,40 @@
+package cmd
+
+import (
+ "context"
+
+ "github.com/spf13/cobra"
+)
+
+// Define the 'account' command and its subcommands
+var accountCmd = &cobra.Command{
+ Use: "account",
+ Short: "Manage account settings",
+}
+
+// Subcommand for 'account list'
+var listAccCmd = &cobra.Command{
+ Use: "list",
+ Short: "list configured accounts",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return ctrl.ListAccounts(context.Background())
+ },
+}
+
+// Subcommand for 'account add'
+var addAccCmd = &cobra.Command{
+ Use: "add",
+ Short: "Add a new account",
+ Run: func(cmd *cobra.Command, args []string) {
+ ctrl.AddAccount(context.Background())
+ },
+}
+
+func init() {
+
+ // Add 'config' subcommands to the root command
+ rootCmd.AddCommand(accountCmd)
+
+ // Add 'config' subcommands to the 'config' command
+ accountCmd.AddCommand(listAccCmd, addAccCmd)
+}
diff --git a/cmd/root.go b/cmd/root.go
index b31c2fa69e..0b30ea92fd 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -3,9 +3,10 @@ package cmd
import (
"cli-go/pkg"
"fmt"
- "github.com/spf13/viper"
"os"
+ "github.com/spf13/viper"
+
"github.com/spf13/cobra"
)
diff --git a/internal/api/client.go b/internal/api/client.go
index 6d5c952bab..5c73866c33 100644
--- a/internal/api/client.go
+++ b/internal/api/client.go
@@ -1,8 +1,6 @@
package api
import (
- "errors"
-
"github.com/go-resty/resty/v2"
)
@@ -43,7 +41,6 @@ func NewClient(p Params) *Client {
return nil
})
}
- c.SetError(&Error{})
if p.Host != "" {
c.SetBaseURL(p.Host)
} else {
@@ -53,19 +50,3 @@ func NewClient(p Params) *Client {
restClient: c,
}
}
-
-// Error type for resty.Error{}
-type Error struct{}
-
-// Implement Error() method for the error interface
-func (e *Error) Error() string {
- return "Error: response status code is not in the 2xx range"
-}
-
-// OnAfterResponse Implement OnAfterResponse() method for the resty.Error interface
-func (e *Error) OnAfterResponse(resp *resty.Response) error {
- if resp.StatusCode() < 200 || resp.StatusCode() >= 300 {
- return errors.New(e.Error())
- }
- return nil
-}
diff --git a/internal/api/enums.go b/internal/api/enums.go
new file mode 100644
index 0000000000..42cddc2874
--- /dev/null
+++ b/internal/api/enums.go
@@ -0,0 +1,9 @@
+package api
+
+type App string
+
+const (
+ AppPhotos App = "photos"
+ AppAuth App = "auth"
+ AppLocker App = "locker"
+)
diff --git a/internal/api/login.go b/internal/api/login.go
index 0c5ad91b45..8067384fc3 100644
--- a/internal/api/login.go
+++ b/internal/api/login.go
@@ -2,14 +2,15 @@ package api
import (
"context"
+
"github.com/google/uuid"
)
func (c *Client) GetSRPAttributes(ctx context.Context, email string) (*SRPAttributes, error) {
var res struct {
- SRPAttributes SRPAttributes `json:"attributes"`
+ SRPAttributes *SRPAttributes `json:"attributes"`
}
- _, err := c.restClient.R().
+ r, err := c.restClient.R().
SetContext(ctx).
SetResult(&res).
SetQueryParam("email", email).
@@ -17,7 +18,13 @@ func (c *Client) GetSRPAttributes(ctx context.Context, email string) (*SRPAttrib
if err != nil {
return nil, err
}
- return &res.SRPAttributes, err
+ if r.IsError() {
+ return nil, &ApiError{
+ StatusCode: r.StatusCode(),
+ Message: r.String(),
+ }
+ }
+ return res.SRPAttributes, err
}
func (c *Client) CreateSRPSession(
@@ -30,7 +37,7 @@ func (c *Client) CreateSRPSession(
"srpUserID": srpUserID.String(),
"srpA": clientPub,
}
- _, err := c.restClient.R().
+ r, err := c.restClient.R().
SetContext(ctx).
SetResult(&res).
SetBody(payload).
@@ -38,6 +45,12 @@ func (c *Client) CreateSRPSession(
if err != nil {
return nil, err
}
+ if r.IsError() {
+ return nil, &ApiError{
+ StatusCode: r.StatusCode(),
+ Message: r.String(),
+ }
+ }
return &res, nil
}
@@ -53,7 +66,7 @@ func (c *Client) VerifySRPSession(
"sessionID": sessionID.String(),
"srpM1": clientM1,
}
- _, err := c.restClient.R().
+ r, err := c.restClient.R().
SetContext(ctx).
SetResult(&res).
SetBody(payload).
@@ -61,5 +74,63 @@ func (c *Client) VerifySRPSession(
if err != nil {
return nil, err
}
+ if r.IsError() {
+ return nil, &ApiError{
+ StatusCode: r.StatusCode(),
+ Message: r.String(),
+ }
+ }
+ return &res, nil
+}
+
+func (c *Client) SendEmailOTP(
+ ctx context.Context,
+ email string,
+) error {
+ var res AuthorizationResponse
+ payload := map[string]interface{}{
+ "email": email,
+ }
+ r, err := c.restClient.R().
+ SetContext(ctx).
+ SetResult(&res).
+ SetBody(payload).
+ Post("/users/ott")
+ if err != nil {
+ return err
+ }
+ if r.IsError() {
+ return &ApiError{
+ StatusCode: r.StatusCode(),
+ Message: r.String(),
+ }
+ }
+ return nil
+}
+
+func (c *Client) VerifyEmail(
+ ctx context.Context,
+ email string,
+ otp string,
+) (*AuthorizationResponse, error) {
+ var res AuthorizationResponse
+ payload := map[string]interface{}{
+ "email": email,
+ "ott": otp,
+ }
+ r, err := c.restClient.R().
+ SetContext(ctx).
+ SetResult(&res).
+ SetBody(payload).
+ Post("/users/verify-email")
+ if err != nil {
+ return nil, err
+ }
+ if r.IsError() {
+ return nil, &ApiError{
+ StatusCode: r.StatusCode(),
+ Message: r.String(),
+ }
+ }
return &res, nil
}
diff --git a/internal/api/login_type.go b/internal/api/login_type.go
index dc50038733..9c60d4eb16 100644
--- a/internal/api/login_type.go
+++ b/internal/api/login_type.go
@@ -1,6 +1,8 @@
package api
import (
+ "fmt"
+
"github.com/google/uuid"
)
@@ -13,6 +15,15 @@ type SRPAttributes struct {
IsEmailMFAEnabled bool `json:"isEmailMFAEnabled" binding:"required"`
}
+type ApiError struct {
+ Message string
+ StatusCode int
+}
+
+func (e *ApiError) Error() string {
+ return fmt.Sprintf("status %d with err: %s", e.StatusCode, e.Message)
+}
+
type CreateSRPSessionResponse struct {
SessionID uuid.UUID `json:"sessionID" binding:"required"`
SRPB string `json:"srpB" binding:"required"`
@@ -41,3 +52,7 @@ type AuthorizationResponse struct {
// SrpM2 is the SRP M2 value aka the proof that the server has the verifier
SrpM2 *string `json:"srpM2,omitempty"`
}
+
+func (a *AuthorizationResponse) IsMFARequired() bool {
+ return a.TwoFactorSessionID != ""
+}
diff --git a/main.go b/main.go
index 79c2e6fbc2..418167072e 100644
--- a/main.go
+++ b/main.go
@@ -8,34 +8,31 @@ import (
"cli-go/internal/api"
"cli-go/pkg"
"fmt"
+
bolt "go.etcd.io/bbolt"
- "log"
)
-var db *bolt.DB
-var client = api.NewClient(api.Params{
- Debug: true,
-})
-
func main() {
db, err := pkg.GetDB("ente-cli.db")
if err != nil {
panic(err)
}
db.Update(func(tx *bolt.Tx) error {
- log.Println("creating #AccBucket")
_, err := tx.CreateBucketIfNotExists([]byte(pkg.AccBucket))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
})
+ var client = api.NewClient(api.Params{
+ Debug: false,
+ Host: "http://localhost:8080",
+ })
ctrl := pkg.ClICtrl{
Client: client,
DB: db,
}
defer func() {
- log.Println("closing db")
if err := db.Close(); err != nil {
panic(err)
}
diff --git a/pkg/account.go b/pkg/account.go
index c02106df58..b859871247 100644
--- a/pkg/account.go
+++ b/pkg/account.go
@@ -1,30 +1,103 @@
package pkg
import (
+ "cli-go/internal/api"
"context"
"encoding/json"
+ "fmt"
+ "log"
+
bolt "go.etcd.io/bbolt"
)
const AccBucket = "accounts"
type AccountInfo struct {
- Email string `json:"email" binding:"required"`
- UserID int64 `json:"userID" binding:"required"`
+ Email string `json:"email" binding:"required"`
+ UserID int64 `json:"userID" binding:"required"`
+ App api.App `json:"app" binding:"required"`
}
-func (c *ClICtrl) AddAccount(cxt context.Context, email string, userID int64) error {
- return c.DB.Update(func(tx *bolt.Tx) error {
- b := tx.Bucket([]byte(AccBucket))
- info := AccountInfo{
- Email: email,
- UserID: userID,
+func (c *ClICtrl) AddAccount(cxt context.Context) {
+ var flowErr error
+ defer func() {
+ if r := recover(); r != nil {
+ log.Println("recovered from panic", r)
+ }
+ if flowErr != nil {
+ log.Fatal(flowErr)
+ }
+ }()
+
+ email, flowErr := GetUserInput("Enter email address")
+ if flowErr != nil {
+ return
+ }
+ var keyEncKey []byte
+ var verifyEmail bool
+ var authResponse *api.AuthorizationResponse
+ srpAttr, flowErr := c.Client.GetSRPAttributes(cxt, email)
+ if flowErr != nil {
+ return
+ }
+ if verifyEmail || srpAttr.IsEmailMFAEnabled {
+ flowErr = c.Client.SendEmailOTP(cxt, email)
+ if flowErr != nil {
+ return
+ }
+ ott, otpErr := GetCode(
+ fmt.Sprintf("Enter OTP sent to email %s (or 'c' to cancel)", email),
+ 6)
+ if otpErr != nil {
+ flowErr = otpErr
+ return
+ }
+ authResponse, flowErr = c.Client.VerifyEmail(cxt, email, ott)
+ } else {
+ authResponse, keyEncKey, flowErr = c.signInViaPassword(cxt, email, srpAttr)
+ }
+ if flowErr != nil {
+ return
+ }
+ if authResponse == nil {
+ return
+ }
+ if authResponse.IsMFARequired() {
+
+ }
+ if keyEncKey == nil {
+ pass, flowErr := GetSensitiveField("Enter password")
+ if flowErr != nil {
+ return
+ } else if pass == "" {
+ log.Printf("do work")
}
- value, err := json.Marshal(info)
+ }
+}
+
+func (c *ClICtrl) ListAccounts(cxt context.Context) error {
+ err := c.DB.View(func(tx *bolt.Tx) error {
+ b := tx.Bucket([]byte(AccBucket))
+ log.Printf("total accounts: %d", b.Stats().KeyN)
+ err := b.ForEach(func(k, v []byte) error {
+ var info AccountInfo
+ err := json.Unmarshal(v, &info)
+ if err != nil {
+ return err
+ }
+ log.Println(info)
+ return nil
+ })
if err != nil {
+ log.Fatal("error listing accounts", err)
return err
}
- err = b.Put([]byte(email), value)
- return err
+ return nil
})
+ if err != nil {
+ log.Fatal("error listing accounts", err)
+ return err
+ }
+ return err
+
}
diff --git a/pkg/promt.go b/pkg/promt.go
index d1ebfbd005..32936f469d 100644
--- a/pkg/promt.go
+++ b/pkg/promt.go
@@ -3,6 +3,7 @@ package pkg
import (
"errors"
"fmt"
+ "log"
"os"
"golang.org/x/term"
@@ -29,3 +30,24 @@ func GetUserInput(label string) (string, error) {
}
return input, nil
}
+
+func GetCode(promptText string, length int) (string, error) {
+ for {
+ ott, err := GetUserInput(promptText)
+ if err != nil {
+ return "", err
+ }
+ if ott == "" {
+ log.Fatal("no OTP entered")
+ return "", errors.New("no OTP entered")
+ }
+ if ott == "c" {
+ return "", errors.New("OTP entry cancelled")
+ }
+ if len(ott) != length {
+ fmt.Printf("OTP must be %d digits", length)
+ continue
+ }
+ return ott, nil
+ }
+}
diff --git a/pkg/sign_in.go b/pkg/sign_in.go
new file mode 100644
index 0000000000..d66c6fbad7
--- /dev/null
+++ b/pkg/sign_in.go
@@ -0,0 +1,50 @@
+package pkg
+
+import (
+ "cli-go/internal/api"
+ enteCrypto "cli-go/internal/crypto"
+ "cli-go/utils"
+ "context"
+ "fmt"
+ "log"
+
+ "github.com/kong/go-srp"
+)
+
+func (c *ClICtrl) signInViaPassword(ctx context.Context, email string, srpAttr *api.SRPAttributes) (*api.AuthorizationResponse, []byte, error) {
+ for {
+ // CLI prompt for password
+ password, flowErr := GetSensitiveField("Enter password")
+ if flowErr != nil {
+ return nil, nil, flowErr
+ }
+ fmt.Println("\nPlease wait authenticating...")
+ keyEncKey, err := enteCrypto.DeriveArgonKey(password, srpAttr.KekSalt, srpAttr.MemLimit, srpAttr.OpsLimit)
+ if err != nil {
+ fmt.Printf("error deriving key encryption key: %v", err)
+ return nil, nil, err
+ }
+ loginKey := enteCrypto.DeriveLoginKey(keyEncKey)
+
+ srpParams := srp.GetParams(4096)
+ identify := []byte(srpAttr.SRPUserID.String())
+ salt := utils.Base64DecodeString(srpAttr.SRPSalt)
+ clientSecret := srp.GenKey()
+ srpClient := srp.NewClient(srpParams, salt, identify, loginKey, clientSecret)
+ clientA := srpClient.ComputeA()
+ session, err := c.Client.CreateSRPSession(ctx, srpAttr.SRPUserID, utils.BytesToBase64(clientA))
+ if err != nil {
+ return nil, nil, err
+ }
+ serverB := session.SRPB
+ srpClient.SetB(utils.Base64DecodeString(serverB))
+ clientM := srpClient.ComputeM1()
+ authResp, err := c.Client.VerifySRPSession(ctx, srpAttr.SRPUserID, session.SessionID, utils.BytesToBase64(clientM))
+ if err != nil {
+ log.Printf("failed to verify %v", err)
+ continue
+ }
+ return authResp, keyEncKey, nil
+ }
+
+}