Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Implement FindPrincipalByEmail and FindPrincipalList
天舟90987f5fd591
diff --git a/backend/api/auth.go b/backend/api/auth.goindex cb85f12fae..70198a527c 100644--- a/backend/api/auth.go+++ b/backend/api/auth.go@@ -4,7 +4,3 @@ type Login struct {Email string `jsonapi:"attr,email"`Password string `jsonapi:"attr,password"`}--type AuthService interface {- FindPrincipalByEmail(email string) (*Principal, error)-}diff --git a/backend/api/principal.go b/backend/api/principal.goindex ecf95c13f2..25035333cd 100644--- a/backend/api/principal.go+++ b/backend/api/principal.go@@ -1,7 +1,37 @@package api+import "context"++type PrincipalStatus string++const (+ Unknown PrincipalStatus = "UNKNOWN"+ Invited PrincipalStatus = "INVITED"+ Active PrincipalStatus = "ACTIVE"+)++type PrincipalType string++const (+ EndUser PrincipalType = "END_USER"+ BOT PrincipalType = "BOT"+)+type Principal struct {- ID uint `jsonapi:"primary,principal"`- Name string `jsonapi:"attr,name"`- Email string `jsonapi:"attr,email"`+ ID uint `jsonapi:"primary,principal"`+ CreatorId uint `jsonapi:"attr,creatorId"`+ CreatorTs int64 `jsonapi:"attr,creatorTs"`+ UpdaterId uint `jsonapi:"attr,updaterId"`+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`+ Status PrincipalStatus `jsonapi:"attr,status"`+ Type PrincipalType `jsonapi:"attr,type"`+ Name string `jsonapi:"attr,name"`+ Email string `jsonapi:"attr,email"`+ // Not needed to return to the client+ PasswordHash string+}++type PrincipalService interface {+ FindPrincipalList(ctx context.Context) ([]*Principal, error)+ FindPrincipalByEmail(ctx context.Context, email string) (*Principal, error)}diff --git a/backend/cmd/echo/main.go b/backend/cmd/echo/main.goindex 7cf2d7a551..6693e20e0e 100644--- a/backend/cmd/echo/main.go+++ b/backend/cmd/echo/main.go@@ -35,7 +35,8 @@ func (m *Main) Run() error {m.db = dbserver := server.NewServer()- server.AuthService = sqlite.NewAuthService(db)+ server.PrincipalService = sqlite.NewPrincipalService(db)+m.server = serverif err := server.Run(); err != nil {return errdiff --git a/backend/server/auth.go b/backend/server/auth.goindex e7eb28c67c..4d1eb6c2cd 100644--- a/backend/server/auth.go+++ b/backend/server/auth.go@@ -1,6 +1,7 @@package serverimport (+ "context""net/http""github.com/bytebase/bytebase"@@ -16,7 +17,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformatted login request")}- user, err := s.AuthService.FindPrincipalByEmail(login.Email)+ user, err := s.PrincipalService.FindPrincipalByEmail(context.Background(), login.Email)if err != nil {if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {return echo.NewHTTPError(http.StatusUnauthorized)@@ -37,7 +38,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)c.Response().WriteHeader(http.StatusOK)- if err := jsonapi.MarshalPayload(c.Response().Writer, login); err != nil {+ if err := jsonapi.MarshalPayload(c.Response().Writer, user); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal login response")}diff --git a/backend/server/principal.go b/backend/server/principal.gonew file mode 100644index 0000000000..e26f165b5f--- /dev/null+++ b/backend/server/principal.go@@ -0,0 +1,26 @@+package server++import (+ "context"+ "net/http"++ "github.com/google/jsonapi"+ "github.com/labstack/echo/v4"+)++func (s *Server) registerPrincipalRoutes(g *echo.Group) {+ g.GET("/principal", func(c echo.Context) error {+ list, err := s.PrincipalService.FindPrincipalList(context.Background())+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed fetch principal list.")+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ c.Response().WriteHeader(http.StatusOK)+ if err := jsonapi.MarshalPayload(c.Response().Writer, list); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal principal list")+ }++ return nil+ })+}diff --git a/backend/server/server.go b/backend/server/server.goindex 8a875bdc5e..340693da7a 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -13,7 +13,7 @@ import ()type Server struct {- AuthService api.AuthService+ PrincipalService api.PrincipalServiceEnvironmentService api.EnvironmentServicee *echo.Echo@@ -65,7 +65,7 @@ func NewServer() *Server {g.Use(middleware.JWTWithConfig(middleware.JWTConfig{Skipper: func(c echo.Context) bool {- return strings.HasPrefix(c.Path(), "/api/auth")+ return strings.HasPrefix(c.Path(), "/api/auth") || strings.HasPrefix(c.Path(), "/api/principal")},Claims: &Claims{},SigningMethod: middleware.AlgorithmHS256,@@ -81,6 +81,8 @@ func NewServer() *Server {s.registerAuthRoutes(g)+ s.registerPrincipalRoutes(g)+s.registerEnvironmentRoutes(g)return sdiff --git a/backend/sqlite/auth.go b/backend/sqlite/auth.godeleted file mode 100644index 918ba300d1..0000000000--- a/backend/sqlite/auth.go+++ /dev/null@@ -1,21 +0,0 @@-package sqlite--import "github.com/bytebase/bytebase/api"--var (- _ api.AuthService = (*AuthService)(nil)-)--// AuthService represents a service for managing auth.-type AuthService struct {- db *DB-}--// NewAuthService returns a new instance of AuthService.-func NewAuthService(db *DB) *AuthService {- return &AuthService{db: db}-}--func (s *AuthService) FindPrincipalByEmail(email string) (*api.Principal, error) {- return &api.Principal{ID: 1, Email: "[email protected]"}, nil-}diff --git a/backend/sqlite/migration/0001_init_schema.up.sql b/backend/sqlite/migration/0001_init_schema.up.sqlindex f8da5634e7..cb55244e37 100644--- a/backend/sqlite/migration/0001_init_schema.up.sql+++ b/backend/sqlite/migration/0001_init_schema.up.sql@@ -1,15 +1,15 @@CREATE TABLE principal (id INTEGER PRIMARY KEY AUTOINCREMENT,creator_id INTEGER NOT NULL REFERENCES principal (id),- created_ts BIGINT NOT NULL DEFAULT CURRENT_TIMESTAMP,+ created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),updater_id INTEGER NOT NULL REFERENCES principal (id),- updated_ts BIGINT NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),-- "INVITED" | "ACTIVE"`status` TEXT NOT NULL,-- "END_USER" | "SYSTEM_BOT"`type` TEXT NOT NULL,name TEXT NOT NULL,- email TEXT NOT NULL,+ email TEXT NOT NULL UNIQUE,password_hash TEXT NOT NULL);@@ -45,9 +45,9 @@ VALUESCREATE TABLE workspace (id INTEGER PRIMARY KEY AUTOINCREMENT,creator_id INTEGER NOT NULL REFERENCES principal (id),- created_ts BIGINT NOT NULL DEFAULT CURRENT_TIMESTAMP,+ created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),updater_id INTEGER NOT NULL REFERENCES principal (id),- updated_ts BIGINT NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),-- "NORMAL" | "ARCHIVED" | "PENDING_DELETE"row_status TEXT NOT NULL,slug TEXT NOT NULL UNIQUE,diff --git a/backend/sqlite/principal.go b/backend/sqlite/principal.gonew file mode 100644index 0000000000..2a8bd74b9b--- /dev/null+++ b/backend/sqlite/principal.go@@ -0,0 +1,123 @@+package sqlite++import (+ "context"+ "strings"++ "github.com/bytebase/bytebase"+ "github.com/bytebase/bytebase/api"+)++var (+ _ api.PrincipalService = (*PrincipalService)(nil)+)++// PrincipalService represents a service for managing principal.+type PrincipalService struct {+ db *DB+}++// NewAuthService returns a new instance of AuthService.+func NewPrincipalService(db *DB) *PrincipalService {+ return &PrincipalService{db: db}+}++// FindPrincipalList retrieves a principal by email.+// Returns ENOTFOUND if no matching email.+func (s *PrincipalService) FindPrincipalByEmail(ctx context.Context, email string) (*api.Principal, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()++ list, err := findPrincipalList(ctx, tx, principalFilter{email: &email})+ if err != nil {+ return nil, err+ } else if len(list) == 0 {+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: "Principal not found."}+ }+ return list[0], nil+}++// FindPrincipalList retrieves a list of principals.+func (s *PrincipalService) FindPrincipalList(ctx context.Context) ([]*api.Principal, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()++ list, err := findPrincipalList(ctx, tx, principalFilter{})+ if err != nil {+ return []*api.Principal{}, err+ }++ return list, nil+}++// principalFilter represents a filter passed to findPrincipalList().+type principalFilter struct {+ // Filtering fields.+ ID *int+ email *string `json:"email"`+}++func findPrincipalList(ctx context.Context, tx *Tx, filter principalFilter) (_ []*api.Principal, err error) {+ // Build WHERE clause.+ where, args := []string{"1 = 1"}, []interface{}{}+ if v := filter.ID; v != nil {+ where, args = append(where, "id = ?"), append(args, *v)+ }+ if v := filter.email; v != nil {+ where, args = append(where, "email = ?"), append(args, *v)+ }++ rows, err := tx.QueryContext(ctx, `+ SELECT+ id,+ creator_id,+ created_ts,+ updater_id,+ updated_ts,+ status,+ type,+ name,+ email,+ password_hash+ FROM principal+ WHERE `+strings.Join(where, " AND "),+ args...,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()++ // Iterate over result set and deserialize rows into list.+ list := make([]*api.Principal, 0)+ for rows.Next() {+ var principal api.Principal+ if rows.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, err+ }++ list = append(list, &principal)+ }+ if err := rows.Err(); err != nil {+ return nil, FormatError(err)+ }++ return list, nil+}diff --git a/backend/sqlite/sqlite.go b/backend/sqlite/sqlite.goindex 3b5c9e8387..dd80eceaf9 100644--- a/backend/sqlite/sqlite.go+++ b/backend/sqlite/sqlite.go@@ -238,3 +238,18 @@ type Tx struct {db *DBnow time.Time}++// FormatError returns err as a bytebase error, if possible.+// Otherwise returns the original error.+func FormatError(err error) error {+ if err == nil {+ return nil+ }++ switch err.Error() {+ // case "UNIQUE constraint failed: dial_memberships.dial_id, dial_memberships.user_id":+ // return bytebase.Errorf(bytebase.ECONFLICT, "Dial membership already exists.")+ default:+ return err+ }+}