fix(user): Add rules to restrict username during installation. fix #181

This commit is contained in:
LinkinStar 2023-01-28 10:40:01 +08:00
parent eacb307328
commit d355c823c3
4 changed files with 29 additions and 9 deletions

View File

@ -5,6 +5,10 @@ import (
"net/url"
"strings"
"github.com/answerdev/answer/internal/base/reason"
"github.com/answerdev/answer/internal/base/validator"
"github.com/answerdev/answer/pkg/checker"
"github.com/segmentfault/pacman/errors"
"xorm.io/xorm/schemas"
)
@ -82,6 +86,18 @@ type InitBaseInfoReq struct {
AdminEmail string `validate:"required,email,gt=0,lte=500" json:"email"`
}
func (r *InitBaseInfoReq) Check() (errFields []*validator.FormErrorField, err error) {
if checker.IsInvalidUsername(r.AdminName) {
errField := &validator.FormErrorField{
ErrorField: "name",
ErrorMsg: reason.UsernameInvalid,
}
errFields = append(errFields, errField)
return errFields, errors.BadRequest(reason.UsernameInvalid)
}
return
}
func (r *InitBaseInfoReq) FormatSiteUrl() {
parsedUrl, err := url.Parse(r.SiteURL)
if err != nil {

View File

@ -2,7 +2,6 @@ package schema
import (
"encoding/json"
"regexp"
"github.com/answerdev/answer/internal/base/reason"
"github.com/answerdev/answer/internal/base/validator"
@ -301,10 +300,7 @@ type AvatarInfo struct {
func (req *UpdateInfoRequest) Check() (errFields []*validator.FormErrorField, err error) {
if len(req.Username) > 0 {
errFields := make([]*validator.FormErrorField, 0)
re := regexp.MustCompile(`^[a-z0-9._-]{4,30}$`)
match := re.MatchString(req.Username)
if !match {
if checker.IsInvalidUsername(req.Username) {
errField := &validator.FormErrorField{
ErrorField: "username",
ErrorMsg: reason.UsernameInvalid,

View File

@ -4,7 +4,6 @@ import (
"context"
"encoding/hex"
"math/rand"
"regexp"
"strings"
"github.com/Chain-Zhang/pinyin"
@ -120,9 +119,7 @@ func (us *UserCommon) MakeUsername(ctx context.Context, displayName string) (use
username = strings.ToLower(username)
suffix := ""
re := regexp.MustCompile(`^[a-z0-9._-]{4,30}$`)
match := re.MatchString(username)
if !match {
if checker.IsInvalidUsername(username) {
return "", errors.BadRequest(reason.UsernameInvalid)
}

11
pkg/checker/username.go Normal file
View File

@ -0,0 +1,11 @@
package checker
import "regexp"
var (
usernameReg = regexp.MustCompile(`^[a-z0-9._-]{4,30}$`)
)
func IsInvalidUsername(username string) bool {
return !usernameReg.MatchString(username)
}