A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.
fix(user): Check whether the username meets the requirements when the user update it.
LinkinStar913a78a1af78
diff --git a/internal/cli/install.go b/internal/cli/install.goindex 6737da98..b8ac0422 100644--- a/internal/cli/install.go+++ b/internal/cli/install.go@@ -12,8 +12,9 @@ import ()const (- DefaultConfigFileName = "config.yaml"- DefaultCacheFileName = "cache.db"+ DefaultConfigFileName = "config.yaml"+ DefaultCacheFileName = "cache.db"+ DefaultReservedUsernamesConfigFileName = "reserved-usernames.json")var (@@ -40,6 +41,7 @@ func InstallAllInitialEnvironment(dataDirPath string) {FormatAllPath(dataDirPath)installUploadDir()installI18nBundle()+ installReservedUsernames()fmt.Println("install all initial environment done")}@@ -112,3 +114,16 @@ func installI18nBundle() {}}}++func installReservedUsernames() {+ reservedUsernamesJsonFilePath := filepath.Join(ConfigFileDir, DefaultReservedUsernamesConfigFileName)+ if !dir.CheckFileExist(reservedUsernamesJsonFilePath) {+ err := writer.WriteFile(reservedUsernamesJsonFilePath, string(configs.ReservedUsernames))+ if err != nil {+ fmt.Printf("[%s] write file fail: %s\n", DefaultReservedUsernamesConfigFileName, err)+ } else {+ fmt.Printf("[%s] write file success\n", DefaultReservedUsernamesConfigFileName)+ }+ return+ }+}diff --git a/internal/controller/user_controller.go b/internal/controller/user_controller.goindex a62d96f9..cc632b7f 100644--- a/internal/controller/user_controller.go+++ b/internal/controller/user_controller.go@@ -384,8 +384,11 @@ func (uc *UserController) UserUpdateInfo(ctx *gin.Context) {return}req.UserID = middleware.GetLoginUserIDFromContext(ctx)- err := uc.userService.UpdateInfo(ctx, req)- handler.HandleResponse(ctx, err, nil)+ errFields, err := uc.userService.UpdateInfo(ctx, req)+ for _, field := range errFields {+ field.ErrorMsg = translator.GlobalTrans.Tr(handler.GetLang(ctx), field.ErrorMsg)+ }+ handler.HandleResponse(ctx, err, errFields)}// UserUpdateInterface update user interface configdiff --git a/internal/service/user_service.go b/internal/service/user_service.goindex 6dbf4edf..8afefa93 100644--- a/internal/service/user_service.go+++ b/internal/service/user_service.go@@ -20,6 +20,7 @@ import ("github.com/answerdev/answer/internal/service/service_config""github.com/answerdev/answer/internal/service/siteinfo_common"usercommon "github.com/answerdev/answer/internal/service/user_common"+ "github.com/answerdev/answer/pkg/checker""github.com/google/uuid""github.com/segmentfault/pacman/errors""github.com/segmentfault/pacman/log"@@ -240,20 +241,31 @@ func (us *UserService) UserModifyPassword(ctx context.Context, request *schema.U}// UpdateInfo update user info-func (us *UserService) UpdateInfo(ctx context.Context, req *schema.UpdateInfoRequest) (err error) {+func (us *UserService) UpdateInfo(ctx context.Context, req *schema.UpdateInfoRequest) (+ errFields []*validator.FormErrorField, err error) {if len(req.Username) > 0 {userInfo, exist, err := us.userRepo.GetByUsername(ctx, req.Username)if err != nil {- return err+ return nil, err}if exist && userInfo.ID != req.UserID {- return errors.BadRequest(reason.UsernameDuplicate)+ errFields = append(errFields, &validator.FormErrorField{+ ErrorField: "username",+ ErrorMsg: reason.UsernameDuplicate,+ })+ return errFields, errors.BadRequest(reason.UsernameDuplicate)+ }+ if checker.IsReservedUsername(req.Username) {+ errFields = append(errFields, &validator.FormErrorField{+ ErrorField: "username",+ ErrorMsg: reason.UsernameInvalid,+ })+ return errFields, errors.BadRequest(reason.UsernameInvalid)}}avatar, err := json.Marshal(req.Avatar)if err != nil {- err = errors.BadRequest(reason.UserSetAvatar).WithError(err).WithStack()- return err+ return nil, errors.BadRequest(reason.UserSetAvatar).WithError(err).WithStack()}userInfo := entity.User{}userInfo.ID = req.UserID@@ -264,10 +276,8 @@ func (us *UserService) UpdateInfo(ctx context.Context, req *schema.UpdateInfoRequserInfo.Location = req.LocationuserInfo.Website = req.WebsiteuserInfo.Username = req.Username- if err := us.userRepo.UpdateInfo(ctx, &userInfo); err != nil {- return err- }- return nil+ err = us.userRepo.UpdateInfo(ctx, &userInfo)+ return nil, err}func (us *UserService) UserEmailHas(ctx context.Context, email string) (bool, error) {diff --git a/pkg/checker/reserved_username.go b/pkg/checker/reserved_username.goindex 91b5f9ac..4d5dd356 100644--- a/pkg/checker/reserved_username.go+++ b/pkg/checker/reserved_username.go@@ -2,19 +2,31 @@ package checkerimport ("encoding/json"+ "os"+ "path/filepath"+ "sync""github.com/answerdev/answer/configs"- "github.com/segmentfault/pacman/log"+ "github.com/answerdev/answer/internal/cli"+ "github.com/answerdev/answer/pkg/dir")var (reservedUsernameMapping = make(map[string]bool)+ reservedUsernameInit sync.Once)-func init() {+func initReservedUsername() {+ reservedUsernamesJsonFilePath := filepath.Join(cli.ConfigFileDir, cli.DefaultReservedUsernamesConfigFileName)+ if dir.CheckFileExist(reservedUsernamesJsonFilePath) {+ // if reserved username file exists, read it and replace configuration+ reservedUsernamesJsonFile, err := os.ReadFile(reservedUsernamesJsonFilePath)+ if err == nil {+ configs.ReservedUsernames = reservedUsernamesJsonFile+ }+ }var usernames []string_ = json.Unmarshal(configs.ReservedUsernames, &usernames)- log.Debugf("get reserved usernames %d", len(usernames))for _, username := range usernames {reservedUsernameMapping[username] = true}@@ -22,5 +34,6 @@ func init() {// IsReservedUsername checks whether the username is reservedfunc IsReservedUsername(username string) bool {+ reservedUsernameInit.Do(initReservedUsername)return reservedUsernameMapping[username]}