fix(user): Check whether the username meets the requirements when the user update it.

This commit is contained in:
LinkinStar 2022-12-30 10:51:54 +08:00
parent 34d600006f
commit 913a78a1af
4 changed files with 57 additions and 16 deletions

View File

@ -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
}
}

View File

@ -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 config

View File

@ -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.UpdateInfoReq
userInfo.Location = req.Location
userInfo.Website = req.Website
userInfo.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) {

View File

@ -2,19 +2,31 @@ package checker
import (
"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 reserved
func IsReservedUsername(username string) bool {
reservedUsernameInit.Do(initReservedUsername)
return reservedUsernameMapping[username]
}