Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Supporting changing password
天舟f4a45f12e22b
diff --git a/api/principal.go b/api/principal.goindex d9e2d8052b..abea69cc30 100644--- a/api/principal.go+++ b/api/principal.go@@ -37,7 +37,7 @@ type Principal struct {Type PrincipalType `jsonapi:"attr,type"`Name string `jsonapi:"attr,name"`Email string `jsonapi:"attr,email"`- // No need to return to the client+ // Do not return to the clientPasswordHash string// Role is stored in the member table, but we include it when returning the principal.// This simplifies the client code where it won't require order depenendency to fetch the related member info first.@@ -80,6 +80,7 @@ type PrincipalCreate struct {Type PrincipalTypeName string `jsonapi:"attr,name"`Email string `jsonapi:"attr,email"`+ Password string `jsonapi:"attr,password"`PasswordHash string}@@ -106,7 +107,9 @@ type PrincipalPatch struct {UpdaterId int// Domain specific fields- Name *string `jsonapi:"attr,name"`+ Name *string `jsonapi:"attr,name"`+ Password *string `jsonapi:"attr,password"`+ PasswordHash *string}type PrincipalService interface {diff --git a/frontend/src/store/modules/auth.ts b/frontend/src/store/modules/auth.tsindex df8e94895c..cacf997a80 100644--- a/frontend/src/store/modules/auth.ts+++ b/frontend/src/store/modules/auth.ts@@ -8,6 +8,7 @@ import {ActivateInfo,ResourceObject,unknown,+ PrincipalId,} from "../../types";import { getIntCookie, removeCookie } from "../../utils";@@ -100,6 +101,20 @@ const actions = {return unknown("PRINCIPAL") as Principal;},+ async refreshUserIfNeeded(+ { commit, state, rootGetters }: any,+ principalId: PrincipalId+ ) {+ if (principalId == state.currentUser.id) {+ const refreshedUser = rootGetters["principal/principalById"](+ state.currentUser.id+ );+ if (!isEqual(refreshedUser, state.currentUser)) {+ commit("setCurrentUser", refreshedUser);+ }+ }+ },+async logout({ commit }: any) {removeCookie("user");console.log("logout:", getIntCookie("user"));diff --git a/frontend/src/store/modules/principal.ts b/frontend/src/store/modules/principal.tsindex 33c6130614..66f3f62035 100644--- a/frontend/src/store/modules/principal.ts+++ b/frontend/src/store/modules/principal.ts@@ -112,7 +112,7 @@ const actions = {},async patchPrincipal(- { commit }: any,+ { commit, dispatch }: any,{principalId,principalPatch,@@ -134,6 +134,8 @@ const actions = {commit("upsertPrincipalInList", updatedPrincipal);+ dispatch("auth/refreshUserIfNeeded", updatedPrincipal.id, { root: true });+return updatedPrincipal;},};diff --git a/frontend/src/types/principal.ts b/frontend/src/types/principal.tsindex ba255a40d9..4993b178ec 100644--- a/frontend/src/types/principal.ts+++ b/frontend/src/types/principal.ts@@ -34,4 +34,5 @@ export type PrincipalCreate = {export type PrincipalPatch = {// Domain specific fieldsname?: string;+ password?: string;};diff --git a/frontend/src/views/ProfileDashboard.vue b/frontend/src/views/ProfileDashboard.vueindex 71d69160cd..37c4de2f03 100644--- a/frontend/src/views/ProfileDashboard.vue+++ b/frontend/src/views/ProfileDashboard.vue@@ -41,7 +41,7 @@</svg><span>Message</span></button>- <template v-if="isCurrentUser">+ <template v-if="allowEdit"><template v-if="state.editing"><buttontype="button"@@ -97,6 +97,7 @@<inputv-if="state.editing"required+ autocomplete="off"id="name"name="name"type="text"@@ -116,7 +117,7 @@<!-- Description list --><divv-if="principal.type == 'END_USER'"- class="mt-6 max-w-5xl mx-auto px-4 sm:px-6 lg:px-8"+ class="mt-6 mb-2 max-w-5xl mx-auto px-4 sm:px-6 lg:px-8"><dl class="grid grid-cols-1 gap-x-4 gap-y-8 sm:grid-cols-2"><div class="sm:col-span-1">@@ -145,6 +146,22 @@{{ principal.email }}</dd></div>++ <div v-if="state.editing" class="sm:col-span-1">+ <dt class="text-sm font-medium text-control-light">Password</dt>+ <dd class="mt-1 text-sm text-main">+ <input+ id="password"+ name="password"+ type="text"+ class="textfield mt-1 w-full"+ autocomplete="off"+ placeholder="sensitive - write only"+ :value="state.editingPrincipal.password"+ @input="updatePrincipal('password', $event.target.value)"+ />+ </dd>+ </div></dl></div></article>@@ -158,6 +175,7 @@ import PrincipalAvatar from "../components/PrincipalAvatar.vue";import cloneDeep from "lodash-es/cloneDeep";import isEqual from "lodash-es/isEqual";import { Principal, PrincipalPatch } from "../types";+import { isOwner } from "../utils";interface LocalState {editing: boolean;@@ -168,7 +186,7 @@ export default {name: "ProfileDashboard",props: {principalId: {- type: Number,+ type: String,},},components: { PrincipalAvatar },@@ -211,13 +229,20 @@ export default {const principal = computed(() => {if (props.principalId) {- return store.getters["principal/principalById"](props.principalId);+ return store.getters["principal/principalById"](+ parseInt(props.principalId)+ );}return currentUser.value;});- const isCurrentUser = computed(() => {- return currentUser.value.id == principal.value.id;+ // User can change her own info.+ // Besides, owner can also change anyone's info. This is for resetting password in case user forgets.+ const allowEdit = computed(() => {+ return (+ currentUser.value.id == principal.value.id ||+ isOwner(currentUser.value.role)+ );});const valueChanged = computed(() => {@@ -252,7 +277,6 @@ export default {.then(() => {state.editingPrincipal = undefined;state.editing = false;- store.dispatch("auth/refreshUser");});};@@ -260,7 +284,7 @@ export default {editNameTextField,state,hasAdminFeature,- isCurrentUser,+ allowEdit,principal,valueChanged,updatePrincipal,diff --git a/server/principal.go b/server/principal.goindex f071af426c..dfb794fc44 100644--- a/server/principal.go+++ b/server/principal.go@@ -10,6 +10,7 @@ import ("github.com/bytebase/bytebase/api""github.com/google/jsonapi""github.com/labstack/echo/v4"+ "golang.org/x/crypto/bcrypt")func (s *Server) registerPrincipalRoutes(g *echo.Group) {@@ -21,7 +22,11 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {principalCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)principalCreate.Type = api.EndUser- principalCreate.PasswordHash = ""+ passwordHash, err := bcrypt.GenerateFromPassword([]byte(principalCreate.Password), bcrypt.DefaultCost)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)+ }+ principalCreate.PasswordHash = string(passwordHash)principal, err := s.PrincipalService.CreatePrincipal(context.Background(), principalCreate)if err != nil {@@ -30,6 +35,8 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {}return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create principal").SetInternal(err)}+ // Assign Developer role to the just created principal+ principal.Role = api.Developerc.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {@@ -86,10 +93,19 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {principalPatch := &api.PrincipalPatch{ID: id,- UpdaterId: c.Get(GetPrincipalIdContextKey()).(int)}+ UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),+ }if err := jsonapi.UnmarshalPayload(c.Request().Body, principalPatch); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch principal request").SetInternal(err)}+ if principalPatch.Password != nil && *principalPatch.Password != "" {+ passwordHash, err := bcrypt.GenerateFromPassword([]byte(*principalPatch.Password), bcrypt.DefaultCost)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)+ }+ passwordHashStr := string(passwordHash)+ principalPatch.PasswordHash = &passwordHashStr+ }principal, err := s.PrincipalService.PatchPrincipal(context.Background(), principalPatch)if err != nil {@@ -98,6 +114,9 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {}return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch principal ID: %v", id)).SetInternal(err)}+ if err := s.ComposePrincipalRole(context.Background(), principal); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch role for principal: %v", principal.Name)).SetInternal(err)+ }c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {diff --git a/store/principal.go b/store/principal.goindex 71c5b8e703..5c7688bef2 100644--- a/store/principal.go+++ b/store/principal.go@@ -209,22 +209,24 @@ func findPrincipalList(ctx context.Context, tx *Tx, find *api.PrincipalFind) (_// patchPrincipal updates a principal by ID. Returns the new state of the principal after update.func patchPrincipal(ctx context.Context, tx *Tx, patch *api.PrincipalPatch) (*api.Principal, error) {- principal := api.Principal{}- // Update fields, if set.+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}if v := patch.Name; v != nil {- principal.Name = *v+ set, args = append(set, "name = ?"), append(args, *v)}+ if v := patch.PasswordHash; v != nil {+ set, args = append(set, "password_hash = ?"), append(args, *v)+ }++ args = append(args, patch.ID)// Execute update query with RETURNING.row, err := tx.QueryContext(ctx, `UPDATE principal- SET name = ?, updater_id = ?+ SET `+strings.Join(set, ", ")+`WHERE id = ?RETURNING id, creator_id, created_ts, updater_id, updated_ts, type, name, email, password_hash`,- principal.Name,- patch.UpdaterId,- patch.ID,+ args...,)if err != nil {return nil, FormatError(err)