Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

some refactoring and an endpoint to check validity of email verification pins

Dane Schneider213f1c4c8c41
diff --git a/app/server/db/account_helpers.go b/app/server/db/account_helpers.go
new file mode 100644
index 00000000..76bfead8
--- /dev/null
+++ b/app/server/db/account_helpers.go
@@ -0,0 +1,52 @@
+package db
+
+import (
+ "fmt"
+
+ "github.com/jmoiron/sqlx"
+)
+
+type CreateAccountResult struct {
+ User *User
+ OrgId string
+ Token string
+}
+
+func CreateAccount(name, email, emailVerificationId string, tx *sqlx.Tx) (*CreateAccountResult, error) {
+ // create user
+ user, err := CreateUser(name, email, tx)
+
+ if err != nil {
+ return nil, fmt.Errorf("error creating user: %v", err)
+ }
+
+ userId := user.Id
+ domain := user.Domain
+
+ // create auth token
+ token, authTokenId, err := CreateAuthToken(userId, false, tx)
+
+ if err != nil {
+ return nil, fmt.Errorf("error creating auth token: %v", err)
+ }
+
+ // 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", userId, authTokenId, emailVerificationId)
+
+ if err != nil {
+ return nil, fmt.Errorf("error updating email verification: %v", err)
+ }
+
+ // add to org matching domain if one exists and auto add domain users is true for that org
+ orgId, err := AddToOrgForDomain(domain, userId, tx)
+
+ if err != nil {
+ return nil, fmt.Errorf("error adding user to org for domain: %v", err)
+ }
+
+ return &CreateAccountResult{
+ User: user,
+ OrgId: orgId,
+ Token: token,
+ }, nil
+}
diff --git a/app/server/db/auth_helpers.go b/app/server/db/auth_helpers.go
index b1b8967d..d6fbc46b 100644
--- a/app/server/db/auth_helpers.go
+++ b/app/server/db/auth_helpers.go
@@ -76,6 +76,8 @@ func CreateEmailVerification(email string, userId, pinHash string) error {
// email verifications expire in 5 minutes
const emailVerificationExpirationMinutes = 5
+const InvalidOrExpiredPinError = "invalid or expired pin"
+
func ValidateEmailVerification(email, pin string) (id string, err error) {
pinHashBytes := sha256.Sum256([]byte(pin))
pinHash := hex.EncodeToString(pinHashBytes[:])
@@ -91,7 +93,7 @@ func ValidateEmailVerification(email, pin string) (id string, err error) {
err = Conn.QueryRow(query, pinHash, email, time.Now().Add(-emailVerificationExpirationMinutes*time.Minute)).Scan(&id, &authTokenId)
if err != nil {
if err == sql.ErrNoRows {
- return "", errors.New("invalid or expired pin")
+ return "", errors.New(InvalidOrExpiredPinError)
}
return "", fmt.Errorf("error validating email verification: %v", err)
}
diff --git a/app/server/db/db.go b/app/server/db/db.go
index b2088b68..f787d730 100644
--- a/app/server/db/db.go
+++ b/app/server/db/db.go
@@ -86,7 +86,7 @@ func migrationsUp(dir string) error {
// Uncomment below (and update migration version) to reset migration state to a specific version after a failure
// if os.Getenv("GOENV") == "development" {
- // migrateVersion := 2024081400
+ // migrateVersion := 2024062100
// if err := m.Force(migrateVersion); err != nil {
// return fmt.Errorf("error forcing migration version: %v", err)
// }
@@ -105,13 +105,14 @@ func migrationsUp(dir string) error {
// log.Println("ran down migrations - database was reset")
// }
- // Uncomment below to go back ONE migration
+ // Uncomment below and edit 'stepsBack' to go back a specific number of migrations
// if os.Getenv("GOENV") == "development" {
- // err = m.Steps(-1)
+ // stepsBack := 2
+ // err = m.Steps(-stepsBack)
// if err != nil {
// return fmt.Errorf("error running down migrations: %v", err)
// }
- // log.Println("went down 1 migration")
+ // log.Printf("went down %d migration\n", stepsBack)
// }
err = m.Up()
diff --git a/app/server/db/org_helpers.go b/app/server/db/org_helpers.go
index 49726862..185c0672 100644
--- a/app/server/db/org_helpers.go
+++ b/app/server/db/org_helpers.go
@@ -219,3 +219,33 @@ func ListOrgRoles(orgId string) ([]*OrgRole, error) {
return orgRoles, nil
}
+
+func AddToOrgForDomain(userId, domain string, tx *sqlx.Tx) (string, error) {
+ org, err := GetOrgForDomain(domain)
+
+ if err != nil {
+ return "", fmt.Errorf("error getting org for domain: %v", err)
+ }
+
+ if org != nil && org.AutoAddDomainUsers {
+ // get org owner role id
+ orgOwnerRoleId, err := GetOrgOwnerRoleId()
+
+ if err != nil {
+ return "", fmt.Errorf("error getting org owner role id: %v", err)
+ }
+
+ err = CreateOrgUser(org.Id, userId, orgOwnerRoleId, tx)
+
+ if err != nil {
+ return "", fmt.Errorf("error adding org user: %v", err)
+ }
+ }
+
+ var orgId string
+ if org != nil {
+ orgId = org.Id
+ }
+
+ return orgId, nil
+}
diff --git a/app/server/db/user_helpers.go b/app/server/db/user_helpers.go
index 4840e6dc..4cf0fd21 100644
--- a/app/server/db/user_helpers.go
+++ b/app/server/db/user_helpers.go
@@ -3,6 +3,7 @@ package db
import (
"database/sql"
"fmt"
+ "strings"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
@@ -98,8 +99,29 @@ func ListUsers(orgId string) ([]*User, error) {
return users, nil
}
-func CreateUser(user *User, tx *sqlx.Tx) error {
- return tx.QueryRow("INSERT INTO users (name, email, domain, is_trial) VALUES ($1, $2, $3, $4) RETURNING id", user.Name, user.Email, user.Domain, user.IsTrial).Scan(&user.Id)
+func CreateUser(name, email string, tx *sqlx.Tx) (*User, error) {
+ emailSplit := strings.Split(email, "@")
+ if len(emailSplit) != 2 {
+ return nil, fmt.Errorf("invalid email: %v", email)
+ }
+ domain := emailSplit[1]
+
+ user := User{
+ Name: name,
+ Email: email,
+ Domain: domain,
+ }
+
+ err := tx.QueryRow("INSERT INTO users (name, email, domain, is_trial) VALUES ($1, $2, $3, $4) RETURNING id", user.Name, user.Email, user.Domain, user.IsTrial).Scan(&user.Id)
+
+ if err != nil {
+ if IsNonUniqueErr(err) {
+ return nil, fmt.Errorf("user already exists for email: %v", email)
+ }
+ return nil, fmt.Errorf("error creating user: %v", err)
+ }
+
+ return &user, nil
}
func NumUsersWithRole(orgId, roleId string) (int, error) {
diff --git a/app/server/handlers/accounts.go b/app/server/handlers/accounts.go
index 51dbb889..7efd16bd 100644
--- a/app/server/handlers/accounts.go
+++ b/app/server/handlers/accounts.go
@@ -59,90 +59,22 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {
}
}()
- // create user
- emailSplit := strings.Split(req.Email, "@")
- if len(emailSplit) != 2 {
- log.Printf("Invalid email: %v\n", req.Email)
- http.Error(w, "Invalid email: "+req.Email, http.StatusBadRequest)
- return
- }
- domain := emailSplit[1]
-
- user := db.User{
- Name: req.UserName,
- Email: req.Email,
- Domain: domain,
- }
- err = db.CreateUser(&user, tx)
+ res, err := db.CreateAccount(req.UserName, req.Email, emailVerificationId, tx)
if err != nil {
- if db.IsNonUniqueErr(err) {
- log.Printf("User already exists for email: %v\n", req.Email)
- http.Error(w, "User already exists for email: "+req.Email, http.StatusConflict)
- return
- }
-
- log.Printf("Error creating user: %v\n", err)
- http.Error(w, "Error creating user: "+err.Error(), http.StatusInternalServerError)
+ log.Printf("Error creating account: %v\n", err)
+ http.Error(w, "Error creating account: "+err.Error(), http.StatusInternalServerError)
return
}
+ user := res.User
userId := user.Id
-
- // create auth token
- token, authTokenId, err := db.CreateAuthToken(userId, false, tx)
-
- if err != nil {
- log.Printf("Error creating auth token: %v\n", err)
- http.Error(w, "Error creating auth token: "+err.Error(), http.StatusInternalServerError)
- 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", userId, authTokenId, emailVerificationId)
-
- if err != nil {
- log.Printf("Error updating email verification: %v\n", err)
- http.Error(w, "Error updating email verification: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // add to org matching domain if one exists and auto add domain users is true for that org
- org, err := db.GetOrgForDomain(domain)
-
- if err != nil {
- log.Printf("Error getting org for domain: %v\n", err)
- http.Error(w, "Error getting org for domain: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if org != nil && org.AutoAddDomainUsers {
- // get org owner role id
- orgOwnerRoleId, err := db.GetOrgOwnerRoleId()
-
- if err != nil {
- log.Printf("Error getting org owner role: %v\n", err)
- http.Error(w, "Error getting org owner role: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- err = db.CreateOrgUser(org.Id, userId, orgOwnerRoleId, tx)
-
- if err != nil {
- log.Printf("Error adding org user: %v\n", err)
- http.Error(w, "Error adding org user: "+err.Error(), http.StatusInternalServerError)
- return
- }
- }
-
- var orgId string
- if org != nil {
- orgId = org.Id
- }
+ token := res.Token
+ orgId := res.OrgId
err = hooks.ExecHook(hooks.CreateAccount, hooks.HookParams{
W: w,
- User: &user,
+ User: user,
OrgId: orgId,
})
if err != nil {
@@ -158,7 +90,7 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {
}
// get orgs
- orgs, err := db.GetAccessibleOrgsForUser(&user)
+ orgs, err := db.GetAccessibleOrgsForUser(user)
if err != nil {
log.Printf("Error getting orgs for user: %v\n", err)
diff --git a/app/server/handlers/sessions.go b/app/server/handlers/sessions.go
index 7e4ce289..e7c261b4 100644
--- a/app/server/handlers/sessions.go
+++ b/app/server/handlers/sessions.go
@@ -95,6 +95,42 @@ func CreateEmailVerificationHandler(w http.ResponseWriter, r *http.Request) {
w.Write(bytes)
}
+func CheckEmailPinHandler(w http.ResponseWriter, r *http.Request) {
+ log.Println("Received request for VerifyEmailPinHandler")
+
+ // read the request body
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ log.Printf("Error reading request body: %v\n", err)
+ http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ var req shared.VerifyEmailPinRequest
+ err = json.Unmarshal(body, &req)
+ if err != nil {
+ log.Printf("Error unmarshalling request: %v\n", err)
+ http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ req.Email = strings.ToLower(req.Email)
+
+ _, err = db.ValidateEmailVerification(req.Email, req.Pin)
+
+ if err != nil {
+ if err.Error() == db.InvalidOrExpiredPinError {
+ http.Error(w, "Invalid or expired pin", http.StatusNotFound)
+ return
+ }
+
+ log.Printf("Error validating email verification: %v\n", err)
+ http.Error(w, "Error validating email verification: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ log.Println("Successfully verified email pin")
+}
+
func SignInHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for SignInHandler")
diff --git a/app/server/routes/routes.go b/app/server/routes/routes.go
index 3163c4b0..b037c93e 100644
--- a/app/server/routes/routes.go
+++ b/app/server/routes/routes.go
@@ -27,6 +27,7 @@ func AddRoutes(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", 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.go
index 669a996a..53f37e81 100644
--- a/app/shared/req_res.go
+++ b/app/shared/req_res.go
@@ -6,15 +6,6 @@ import (
"github.com/sashabaranov/go-openai"
)
-type StartTrialResponse struct {
- UserId string `json:"userId"`
- Token string `json:"token"`
- OrgId string `json:"orgId"`
- Email string `json:"email"`
- UserName string `json:"userName"`
- OrgName string `json:"orgName"`
-}
-
type CreateEmailVerificationRequest struct {
Email string `json:"email"`
UserId string `json:"userId"`
@@ -24,6 +15,11 @@ type CreateEmailVerificationResponse struct {
HasAccount bool `json:"hasAccount"`
}
+type VerifyEmailPinRequest struct {
+ Email string `json:"email"`
+ Pin string `json:"pin"`
+}
+
type SignInRequest struct {
Email string `json:"email"`
Pin string `json:"pin"`