Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
sign in codes from web ui <> cli auth
Dane Schneider312fa7174b6b
diff --git a/app/cli/auth/account.go b/app/cli/auth/account.goindex 063715ae..94248a77 100644--- a/app/cli/auth/account.go+++ b/app/cli/auth/account.go@@ -13,32 +13,6 @@ const (AuthAccountOption = "Sign in, accept an invite, or create an account")-func promptInitialAuth() error {- selected, err := term.SelectFromList("π Hey there!\nIt looks like this is your first time using Plandex on this computer.\nWhat would you like to do?", []string{AuthFreeTrialOption, AuthAccountOption})-- if err != nil {- return fmt.Errorf("error selecting auth option: %v", err)- }-- switch selected {- case AuthFreeTrialOption:- err = startTrial()-- if err != nil {- return fmt.Errorf("error starting trial: %v", err)- }-- case AuthAccountOption:- err = SelectOrSignInOrCreate()-- if err != nil {- return fmt.Errorf("error selecting or signing in to account: %v", err)- }- }-- return nil-}-const AddAccountOption = "Add another account"func SelectOrSignInOrCreate() error {@@ -134,6 +108,47 @@ func SelectOrSignInOrCreate() error {return nil}+func SignInWithCode(code, host string) error {+ term.StartSpinner("")+ res, apiErr := apiClient.SignIn(shared.SignInRequest{+ Pin: code,+ IsSignInCode: true,+ }, host)+ term.StopSpinner()++ if apiErr != nil {+ return fmt.Errorf("error signing in: %v", apiErr.Msg)+ }++ return handleSignInResponse(res, host)+}++func promptInitialAuth() error {+ selected, err := term.SelectFromList("π Hey there!\nIt looks like this is your first time using Plandex on this computer.\nWhat would you like to do?", []string{AuthFreeTrialOption, AuthAccountOption})++ if err != nil {+ return fmt.Errorf("error selecting auth option: %v", err)+ }++ switch selected {+ case AuthFreeTrialOption:+ err = startTrial()++ if err != nil {+ return fmt.Errorf("error starting trial: %v", err)+ }++ case AuthAccountOption:+ err = SelectOrSignInOrCreate()++ if err != nil {+ return fmt.Errorf("error selecting or signing in to account: %v", err)+ }+ }++ return nil+}+const (SignInCloudOption = "Plandex Cloud"SignInOtherOption = "Another host"@@ -225,6 +240,10 @@ func signIn(email, pin, host string) error {return fmt.Errorf("error signing in: %v", apiErr.Msg)}+ return handleSignInResponse(res, host)+}++func handleSignInResponse(res *shared.SessionResponse, host string) error {err := setAuth(&shared.ClientAuth{ClientAccount: shared.ClientAccount{Email: res.Email,diff --git a/app/cli/cmd/sign_in.go b/app/cli/cmd/sign_in.goindex 89a5cc39..cd172f16 100644--- a/app/cli/cmd/sign_in.go+++ b/app/cli/cmd/sign_in.go@@ -16,10 +16,27 @@ var signInCmd = &cobra.Command{func init() {RootCmd.AddCommand(signInCmd)++ signInCmd.Flags().String("code", "", "Sign in code from the Plandex web UI")}func signIn(cmd *cobra.Command, args []string) {- err := auth.SelectOrSignInOrCreate()+ code, err := cmd.Flags().GetString("code")+ if err != nil {+ term.OutputErrorAndExit("Error getting code: %v", err)+ }++ if code != "" {+ err = auth.SignInWithCode(code, "")++ if err != nil {+ term.OutputErrorAndExit("Error signing in: %v", err)+ }++ return+ }++ err = auth.SelectOrSignInOrCreate()if err != nil {term.OutputErrorAndExit("Error signing in: %v", err)diff --git a/app/server/db/auth_helpers.go b/app/server/db/auth_helpers.goindex d5ed3657..987a575c 100644--- a/app/server/db/auth_helpers.go+++ b/app/server/db/auth_helpers.go@@ -120,6 +120,44 @@ func validateEmailVerification(email, pin string, enforceExpiration bool, errOnAreturn id, nil}+func CreateSignInCode(userId, orgId, pinHash string) error {+ _, err := Conn.Exec("INSERT INTO sign_in_codes (user_id, org_id, pin_hash) VALUES ($1, $2, $3)", userId, orgId, pinHash)++ if err != nil {+ return fmt.Errorf("error creating sign in code: %v", err)+ }++ return nil+}++const signInCodeExpirationMinutes = 5++type ValidateSignInCodeRes struct {+ Id string+ OrgId string+ UserId string+}++func ValidateSignInCode(pin string) (*ValidateSignInCodeRes, error) {+ pinHashBytes := sha256.Sum256([]byte(pin))+ pinHash := hex.EncodeToString(pinHashBytes[:])++ res := &ValidateSignInCodeRes{}+ var authTokenId *string+ query := `SELECT id, org_id, user_id, auth_token_id FROM sign_in_codes WHERE pin_hash = $1 AND created_at > $2`+ err := Conn.QueryRow(query, pinHash, time.Now().Add(-signInCodeExpirationMinutes*time.Minute)).Scan(&res.Id, &res.OrgId, &res.UserId, &authTokenId)++ if err != nil {+ return nil, fmt.Errorf("error validating sign in code: %v", err)+ }++ if authTokenId != nil {+ return nil, errors.New("sign in code already used")+ }++ return res, nil+}+func GetUserPermissions(userId, orgId string) ([]string, error) {var permissions []stringdiff --git a/app/server/handlers/sessions.go b/app/server/handlers/sessions.goindex fe47190f..699b86ec 100644--- a/app/server/handlers/sessions.go+++ b/app/server/handlers/sessions.go@@ -11,7 +11,6 @@ import ("plandex-server/email""strings"- "github.com/davecgh/go-spew/spew""github.com/plandex/plandex/shared")@@ -146,8 +145,6 @@ func CheckEmailPinHandler(w http.ResponseWriter, r *http.Request) {}req.Email = strings.ToLower(req.Email)- spew.Dump(req)-_, err = db.ValidateEmailVerification(req.Email, req.Pin)if err != nil {@@ -164,6 +161,43 @@ func CheckEmailPinHandler(w http.ResponseWriter, r *http.Request) {log.Println("Successfully verified email pin")}+// sign in codes allow users to authenticate between different clients+// like UI to CLI or vice versa+func CreateSignInCodeHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for CreateSignInCodeHandler")++ auth := Authenticate(w, r, true)++ if auth == nil {+ return+ }++ // create pin - 6 alphanumeric characters+ pinBytes, err := shared.GetRandomAlphanumeric(6)+ if err != nil {+ log.Printf("Error generating random pin: %v\n", err)+ http.Error(w, "Error generating random pin: "+err.Error(), http.StatusInternalServerError)+ return+ }++ // get sha256 hash of pin+ hashBytes := sha256.Sum256(pinBytes)+ pinHash := hex.EncodeToString(hashBytes[:])++ err = db.CreateSignInCode(auth.User.Id, auth.OrgId, pinHash)++ if err != nil {+ log.Printf("Error creating sign in code: %v\n", err)+ http.Error(w, "Error creating sign in code: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully created sign in code")++ // return the pin as a response+ w.Write(pinBytes)+}+func SignInHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for SignInHandler")@@ -182,34 +216,60 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)return}- req.Email = strings.ToLower(req.Email)- user, err := db.GetUserByEmail(req.Email)+ var user *db.User+ var emailVerificationId string+ var signInCodeId string+ var signInCodeOrgId string- if err != nil {- log.Printf("Error getting user: %v\n", err)- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)- return- }+ if req.IsSignInCode {+ res, err := db.ValidateSignInCode(req.Pin)- if user == nil {- log.Printf("User not found for email: %v\n", req.Email)- http.Error(w, "Not found", http.StatusNotFound)- return- }+ if err != nil {+ log.Printf("Error validating sign in code: %v\n", err)+ http.Error(w, "Error validating sign in code: "+err.Error(), http.StatusInternalServerError)+ return+ }- if user.IsTrial {- log.Printf("Trial user can't sign in: %v\n", req.Email)- http.Error(w, "Trial user can't sign in", http.StatusForbidden)- return- }+ user, err = db.GetUser(res.UserId)- emailVerificationId, err := db.ValidateEmailVerification(req.Email, req.Pin)+ if err != nil {+ log.Printf("Error getting user: %v\n", err)+ http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)+ return+ }- if err != nil {- log.Printf("Error validating email verification: %v\n", err)- http.Error(w, "Error validating email verification: "+err.Error(), http.StatusInternalServerError)- return+ if user == nil {+ log.Printf("User not found for id: %v\n", res.UserId)+ http.Error(w, "User not found", http.StatusNotFound)+ return+ }++ signInCodeId = res.Id+ signInCodeOrgId = res.OrgId+ } else {+ req.Email = strings.ToLower(req.Email)+ user, err = db.GetUserByEmail(req.Email)++ if err != nil {+ log.Printf("Error getting user: %v\n", err)+ http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)+ return+ }++ if user == nil {+ log.Printf("User not found for email: %v\n", req.Email)+ http.Error(w, "Not found", http.StatusNotFound)+ return+ }++ emailVerificationId, err = db.ValidateEmailVerification(req.Email, req.Pin)++ if err != nil {+ log.Printf("Error validating email verification: %v\n", err)+ http.Error(w, "Error validating email verification: "+err.Error(), http.StatusInternalServerError)+ return+ }}// start a transaction@@ -240,8 +300,19 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {return}- // update email verification with user and auth token ids- _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", user.Id, authTokenId, emailVerificationId)+ if req.IsSignInCode {+ // update sign in code with auth token id+ _, err = tx.Exec("UPDATE sign_in_codes SET auth_token_id = $1 WHERE id = $2", authTokenId, signInCodeId)++ if err != nil {+ log.Printf("Error updating sign in code: %v\n", err)+ http.Error(w, "Error updating sign in code: "+err.Error(), http.StatusInternalServerError)+ return+ }+ } else {+ // update email verification with user and auth token ids+ _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", user.Id, authTokenId, emailVerificationId)+ }if err != nil {log.Printf("Error updating email verification: %v\n", err)@@ -266,6 +337,16 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {return}+ if req.IsSignInCode {+ filteredOrgs := []*db.Org{}+ for _, org := range orgs {+ if org.Id == signInCodeOrgId {+ filteredOrgs = append(filteredOrgs, org)+ }+ }+ orgs = filteredOrgs+ }+apiOrgs, apiErr := toApiOrgs(orgs)if apiErr != nil {diff --git a/app/server/migrations/2024091800_sign_in_codes.down.sql b/app/server/migrations/2024091800_sign_in_codes.down.sqlnew file mode 100644index 00000000..14e7ad8f--- /dev/null+++ b/app/server/migrations/2024091800_sign_in_codes.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS sign_in_codes;\ No newline at end of filediff --git a/app/server/migrations/2024091800_sign_in_codes.up.sql b/app/server/migrations/2024091800_sign_in_codes.up.sqlnew file mode 100644index 00000000..a576fd15--- /dev/null+++ b/app/server/migrations/2024091800_sign_in_codes.up.sql@@ -0,0 +1,12 @@+CREATE TABLE IF NOT EXISTS sign_in_codes (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ pin_hash VARCHAR(64) NOT NULL,+ user_id UUID REFERENCES users(id),+ org_id UUID REFERENCES orgs(id),+ auth_token_id UUID REFERENCES auth_tokens(id),+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()+);+CREATE TRIGGER update_sign_in_codes_modtime BEFORE UPDATE ON sign_in_codes FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();++CREATE UNIQUE INDEX sign_in_codes_idx ON sign_in_codes(pin_hash, created_at DESC);\ No newline at end of filediff --git a/app/server/routes/routes.go b/app/server/routes/routes.goindex 4ff84543..358f9c83 100644--- a/app/server/routes/routes.go+++ b/app/server/routes/routes.go@@ -28,6 +28,7 @@ func AddApiRoutes(r *mux.Router) {r.HandleFunc("/accounts/email_verifications", handlers.CreateEmailVerificationHandler).Methods("POST")r.HandleFunc("/accounts/email_verifications/check_pin", handlers.CheckEmailPinHandler).Methods("POST")+ r.HandleFunc("/accounts/sign_in_codes", handlers.CreateSignInCodeHandler).Methods("POST")r.HandleFunc("/accounts/sign_in", handlers.SignInHandler).Methods("POST")r.HandleFunc("/accounts/sign_out", handlers.SignOutHandler).Methods("POST")r.HandleFunc("/accounts", handlers.CreateAccountHandler).Methods("POST")diff --git a/app/shared/req_res.go b/app/shared/req_res.goindex 7c1b0112..ca097b7b 100644--- a/app/shared/req_res.go+++ b/app/shared/req_res.go@@ -23,8 +23,9 @@ type VerifyEmailPinRequest struct {}type SignInRequest struct {- Email string `json:"email"`- Pin string `json:"pin"`+ Email string `json:"email"`+ Pin string `json:"pin"`+ IsSignInCode bool `json:"isSignInCode"`}type CreateAccountRequest struct {