Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Implement createPrincipal and use it in the /api/auth/signup

天舟2cde3195e852
diff --git a/backend/api/auth.go b/backend/api/auth.go
index 227858a458..b4e7d6a523 100644
--- a/backend/api/auth.go
+++ b/backend/api/auth.go
@@ -5,3 +5,10 @@ type Login struct {
Email string `jsonapi:"attr,email"`
Password string `jsonapi:"attr,password"`
}
+
+type Signup struct {
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Email string `jsonapi:"attr,email"`
+ Password string `jsonapi:"attr,password"`
+}
diff --git a/backend/api/principal.go b/backend/api/principal.go
index 4e1d4438c7..697caaa7d5 100644
--- a/backend/api/principal.go
+++ b/backend/api/principal.go
@@ -2,6 +2,8 @@ package api
import "context"
+const SYSTEM_BOT_ID = 1
+
type PrincipalStatus string
const (
@@ -35,6 +37,20 @@ type Principal struct {
PasswordHash string
}
+type PrincipalCreate struct {
+ // Standard fields
+ // For signup, value is SYSTEM_BOT_ID
+ // For invite, value is assigned from the jwt subject field passed by the client.
+ CreatorId int
+
+ // Domain specific fields
+ Status PrincipalStatus `jsonapi:"attr,status"`
+ Type PrincipalType
+ Name string `jsonapi:"attr,name"`
+ Email string `jsonapi:"attr,email"`
+ PasswordHash string
+}
+
type PrincipalPatch struct {
// Standard fields
// Value is assigned from the jwt subject field passed by the client.
@@ -45,6 +61,7 @@ type PrincipalPatch struct {
}
type PrincipalService interface {
+ CreatePrincipal(ctx context.Context, create *PrincipalCreate) (*Principal, error)
FindPrincipalList(ctx context.Context) ([]*Principal, error)
FindPrincipalByEmail(ctx context.Context, email string) (*Principal, error)
FindPrincipalByID(ctx context.Context, id int) (*Principal, error)
diff --git a/backend/server/auth.go b/backend/server/auth.go
index c363a5f0d8..91586b9e23 100644
--- a/backend/server/auth.go
+++ b/backend/server/auth.go
@@ -45,4 +45,45 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
return nil
})
+
+ g.POST("/auth/signup", func(c echo.Context) error {
+ signup := &api.Signup{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, signup); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted signup request.")
+ }
+
+ passwordHash, err := bcrypt.GenerateFromPassword([]byte(signup.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash.")
+ }
+
+ principalCreate := &api.PrincipalCreate{
+ CreatorId: api.SYSTEM_BOT_ID,
+ Status: api.Active,
+ Type: api.EndUser,
+ Name: signup.Name,
+ Email: signup.Email,
+ PasswordHash: string(passwordHash),
+ }
+
+ user, err := s.PrincipalService.CreatePrincipal(context.Background(), principalCreate)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ECONFLICT {
+ return echo.NewHTTPError(http.StatusConflict)
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup user.")
+ }
+
+ if err := GenerateTokensAndSetCookies(user, c); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token.")
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ c.Response().WriteHeader(http.StatusOK)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, user); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal signup response.")
+ }
+
+ return nil
+ })
}
diff --git a/backend/server/jwt.go b/backend/server/jwt.go
index c9ed957890..08f2d979ff 100644
--- a/backend/server/jwt.go
+++ b/backend/server/jwt.go
@@ -2,6 +2,7 @@ package server
import (
"fmt"
+ "log"
"net/http"
"strconv"
"strings"
@@ -193,7 +194,6 @@ func TokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// JWTErrorChecker will be executed when user try to access a protected path.
func JWTErrorChecker(err error, c echo.Context) error {
- // Redirects to the signIn form.
- fmt.Printf("Unauthorized to access protected route %s, err: %v\n", c.Path(), err)
+ log.Printf("Unauthorized to access protected route %s, err: %v\n", c.Path(), err)
return err
}
diff --git a/backend/sqlite/principal.go b/backend/sqlite/principal.go
index e0de64b34a..a2b8f47359 100644
--- a/backend/sqlite/principal.go
+++ b/backend/sqlite/principal.go
@@ -22,6 +22,26 @@ func NewPrincipalService(db *DB) *PrincipalService {
return &PrincipalService{db: db}
}
+// CreatePrincipal creates a new principal.
+func (s *PrincipalService) CreatePrincipal(ctx context.Context, create *api.PrincipalCreate) (*api.Principal, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+
+ principal, err := createPrincipal(ctx, tx, create)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+
+ return principal, nil
+}
+
// FindPrincipalByEmail retrieves a principal by email.
// Returns ENOTFOUND if no matching email.
func (s *PrincipalService) FindPrincipalByEmail(ctx context.Context, email string) (*api.Principal, error) {
@@ -89,6 +109,56 @@ func (s *PrincipalService) PatchPrincipalByID(ctx context.Context, id int, patch
return principal, nil
}
+// createPrincipal creates a new principal.
+func createPrincipal(ctx context.Context, tx *Tx, create *api.PrincipalCreate) (*api.Principal, error) {
+ // Insert row into database.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO principal (
+ creator_id,
+ updater_id,
+ status,
+ type,
+ name,
+ email,
+ password_hash
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ RETURNING *
+ `,
+ create.CreatorId,
+ create.CreatorId,
+ create.Status,
+ create.Type,
+ create.Name,
+ create.Email,
+ create.PasswordHash,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var principal api.Principal
+ if err := row.Scan(
+ &principal.ID,
+ &principal.CreatorId,
+ &principal.CreatorTs,
+ &principal.UpdaterId,
+ &principal.UpdatedTs,
+ &principal.Status,
+ &principal.Type,
+ &principal.Name,
+ &principal.Email,
+ &principal.PasswordHash,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &principal, nil
+}
+
// principalFilter represents a filter passed to findPrincipalList().
type principalFilter struct {
// Filtering fields.
@@ -176,7 +246,7 @@ func patchPrincipal(ctx context.Context, tx *Tx, id int, patch *api.PrincipalPat
}
// Execute update query with RETURNING.
- rows, err := tx.QueryContext(ctx, `
+ row, err := tx.QueryContext(ctx, `
UPDATE principal
SET name = ?, updater_id = ?
WHERE id = ?
@@ -189,11 +259,11 @@ func patchPrincipal(ctx context.Context, tx *Tx, id int, patch *api.PrincipalPat
if err != nil {
return nil, FormatError(err)
}
- defer rows.Close()
+ defer row.Close()
- if rows.Next() {
+ if row.Next() {
var principal api.Principal
- if err := rows.Scan(
+ if err := row.Scan(
&principal.ID,
&principal.CreatorId,
&principal.CreatorTs,
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 18bd1e0c0e..326efc6bb4 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -89,6 +89,7 @@ axios.interceptors.request.use((request) => {
isDemo() ||
(!request.url!.startsWith("/api/ping") &&
!request.url!.startsWith("/api/auth/login") &&
+ !request.url!.startsWith("/api/auth/signup") &&
!request.url!.startsWith("/api/principal"))
) {
request.url = request.url!.replace("/api", "/mock");