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 Patch /principal/:id
天舟49e22b1095ae
diff --git a/backend/api/principal.go b/backend/api/principal.goindex 39761798f1..4a3aed75d6 100644--- a/backend/api/principal.go+++ b/backend/api/principal.go@@ -31,8 +31,13 @@ type Principal struct {PasswordHash string}+type PrincipalPatch struct {+ Name *string `jsonapi:"attr,name"`+}+type PrincipalService interface {FindPrincipalList(ctx context.Context) ([]*Principal, error)FindPrincipalByEmail(ctx context.Context, email string) (*Principal, error)- FindPrincipalByID(ctx context.Context, ID int) (*Principal, error)+ FindPrincipalByID(ctx context.Context, id int) (*Principal, error)+ PatchPrincipalByID(ctx context.Context, id int, patch *PrincipalPatch) (*Principal, error)}diff --git a/backend/server/auth.go b/backend/server/auth.goindex 8b530049ac..c363a5f0d8 100644--- a/backend/server/auth.go+++ b/backend/server/auth.go@@ -15,7 +15,7 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {g.POST("/auth/login", func(c echo.Context) error {login := &api.Login{}if err := jsonapi.UnmarshalPayload(c.Request().Body, login); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted login request")+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted login request.")}user, err := s.PrincipalService.FindPrincipalByEmail(context.Background(), login.Email)@@ -23,24 +23,24 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {return echo.NewHTTPError(http.StatusUnauthorized)}- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user")+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user.")}// Compare the stored hashed password, with the hashed version of the password that was received.if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(login.Password)); err != nil {// If the two passwords don't match, return a 401 status.- return echo.NewHTTPError(http.StatusUnauthorized, "Password is incorrect")+ return echo.NewHTTPError(http.StatusUnauthorized, "Password is incorrect.")}// If password is correct, generate tokens and set cookies.if err := GenerateTokensAndSetCookies(user, c); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token")+ 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 login response")+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal login response.")}return nildiff --git a/backend/server/principal.go b/backend/server/principal.goindex d5d12b25ac..31b47f1786 100644--- a/backend/server/principal.go+++ b/backend/server/principal.go@@ -3,10 +3,12 @@ package serverimport ("context""fmt"+ "log""net/http""strconv""github.com/bytebase/bytebase"+ "github.com/bytebase/bytebase/api""github.com/google/jsonapi""github.com/labstack/echo/v4")@@ -49,4 +51,33 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {return nil})++ g.PATCH("/principal/:id", func(c echo.Context) error {+ id, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s.", c.Param("id")))+ }++ principalPatch := &api.PrincipalPatch{}+ if err := jsonapi.UnmarshalPayload(c.Request().Body, principalPatch); err != nil {+ log.Println(err)+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch principal request.")+ }++ principal, err := s.PrincipalService.PatchPrincipalByID(context.Background(), id, principalPatch)+ if err != nil {+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to find principal with ID: %v", id))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch principal.")+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ c.Response().WriteHeader(http.StatusOK)+ if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal principal.")+ }++ return nil+ })}diff --git a/backend/sqlite/principal.go b/backend/sqlite/principal.goindex cac5d980b5..3851091401 100644--- a/backend/sqlite/principal.go+++ b/backend/sqlite/principal.go@@ -22,7 +22,7 @@ func NewPrincipalService(db *DB) *PrincipalService {return &PrincipalService{db: db}}-// FindPrincipalList retrieves a principal by email.+// FindPrincipalByEmail 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)@@ -40,6 +40,8 @@ func (s *PrincipalService) FindPrincipalByEmail(ctx context.Context, email strinreturn list[0], nil}+// FindPrincipalByID retrieves a principal by id.+// Returns ENOTFOUND if no matching id.func (s *PrincipalService) FindPrincipalByID(ctx context.Context, id int) (*api.Principal, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {@@ -47,13 +49,7 @@ func (s *PrincipalService) FindPrincipalByID(ctx context.Context, id int) (*api.}defer tx.Rollback()- list, err := findPrincipalList(ctx, tx, principalFilter{ID: &id})- 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+ return findPrincipalByID(ctx, tx, id)}// FindPrincipalList retrieves a list of principals.@@ -72,11 +68,32 @@ func (s *PrincipalService) FindPrincipalList(ctx context.Context) ([]*api.Princireturn list, nil}+// PatchPrincipalByID updates an existing principal by ID.+// Returns ENOTFOUND if principal does not exist.+func (s *PrincipalService) PatchPrincipalByID(ctx context.Context, id int, patch *api.PrincipalPatch) (*api.Principal, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()++ principal, err := patchPrincipal(ctx, tx, id, patch)+ if err != nil {+ return nil, err+ }++ if err := tx.Commit(); err != nil {+ return nil, err+ }++ return principal, nil+}+// principalFilter represents a filter passed to findPrincipalList().type principalFilter struct {// Filtering fields.ID *int- email *string `json:"email"`+ email *string}func findPrincipalList(ctx context.Context, tx *Tx, filter principalFilter) (_ []*api.Principal, err error) {@@ -114,7 +131,7 @@ func findPrincipalList(ctx context.Context, tx *Tx, filter principalFilter) (_ [list := make([]*api.Principal, 0)for rows.Next() {var principal api.Principal- if rows.Scan(+ if err := rows.Scan(&principal.ID,&principal.CreatorId,&principal.CreatorTs,@@ -126,7 +143,7 @@ func findPrincipalList(ctx context.Context, tx *Tx, filter principalFilter) (_ [&principal.Email,&principal.PasswordHash,); err != nil {- return nil, err+ return nil, FormatError(err)}list = append(list, &principal)@@ -137,3 +154,61 @@ func findPrincipalList(ctx context.Context, tx *Tx, filter principalFilter) (_ [return list, nil}++// findPrincipalByID retrieves a principal by id.+// Returns ENOTFOUND if no matching id.+func findPrincipalByID(ctx context.Context, tx *Tx, id int) (*api.Principal, error) {+ list, err := findPrincipalList(ctx, tx, principalFilter{ID: &id})+ 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+}++// patchPrincipal updates a principal by ID. Returns the new state of the principal after update.+func patchPrincipal(ctx context.Context, tx *Tx, id int, patch *api.PrincipalPatch) (*api.Principal, error) {+ principal := api.Principal{}+ // Update fields, if set.+ if v := patch.Name; v != nil {+ principal.Name = *v+ }++ // Execute update query with RETURNING.+ rows, err := tx.QueryContext(ctx, `+ UPDATE principal+ SET name = ?+ WHERE id = ?+ RETURNING *+ `,+ principal.Name,+ id,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()++ if rows.Next() {+ var principal api.Principal+ if err := 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, FormatError(err)+ }++ return &principal, nil+ }++ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: "Principal not found."}+}