Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions api/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package user

import (
"github.com/0xJacky/Nginx-UI/api"
internalUser "github.com/0xJacky/Nginx-UI/internal/user"
"github.com/0xJacky/Nginx-UI/model"
"github.com/0xJacky/Nginx-UI/query"
"github.com/0xJacky/Nginx-UI/settings"
Expand All @@ -12,6 +13,10 @@ import (
"net/http"
)

const (
ErrDuplicateName = 4409
)

func GetUsers(c *gin.Context) {
cosy.Core[model.User](c).SetFussy("name").PagingList()
}
Expand Down Expand Up @@ -58,10 +63,16 @@ func AddUser(c *gin.Context) {
}

// duplicate name
_, err = u.Where(u.Name.Eq(json.Name)).First()
if !(err != nil && err.Error() == "record not found") {
existUser, err := u.Where(u.Name.Eq(json.Name)).Find()
if err != nil {
api.ErrHandler(c, err)
return
}
err = internalUser.CheckDuplicateName(existUser)
if err != nil {
c.JSON(http.StatusConflict, gin.H{
"message": "name already exists",
"message": err.Error(),
"code": ErrDuplicateName,
})
}

Expand Down Expand Up @@ -114,6 +125,20 @@ func EditUser(c *gin.Context) {
edit.Password = string(pwd)
}

// duplicate name
existUser, err := u.Where(u.Name.Eq(json.Name)).Find()
if err != nil {
api.ErrHandler(c, err)
return
}
err = internalUser.CheckDuplicateName(existUser)
if err != nil {
c.JSON(http.StatusConflict, gin.H{
"message": err.Error(),
"code": ErrDuplicateName,
})
}

_, err = u.Where(u.ID.Eq(userId)).Updates(&edit)

if err != nil {
Expand Down
11 changes: 11 additions & 0 deletions internal/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import (
"time"
)

var (
ErrDuplicateName = errors.New("name already exists")
)

const ExpiredTime = 24 * time.Hour

type JWTClaims struct {
Expand Down Expand Up @@ -109,3 +113,10 @@ func ValidateJWT(tokenStr string) (claims *JWTClaims, err error) {
}
return nil, errors.New("invalid claims type")
}

func CheckDuplicateName(users []*model.User) error {
if len(users) > 0 {
return ErrDuplicateName
}
return nil
}