Skip to content

Commit

Permalink
Merge pull request #29 from jwma/fix/admin_specified_id
Browse files Browse the repository at this point in the history
fix: 管理员添加短连接时,指定 ID 无效
  • Loading branch information
jwma authored Jul 11, 2020
2 parents 09b0c9c + b8a16b3 commit a0ca418
Showing 1 changed file with 33 additions and 30 deletions.
63 changes: 33 additions & 30 deletions internal/app/handlers/shortlink.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func GetShortLinkAPI() gin.HandlerFunc {

func CreateShortLinkAPI() gin.HandlerFunc {
return Authenticator(func(c *gin.Context, user *models.User) {
var err error
s := &models.ShortLink{CreatedBy: user.Username}
params := &models.CreateShortLinkParameter{}
params.ShortLink = s
Expand All @@ -66,41 +67,43 @@ func CreateShortLinkAPI() gin.HandlerFunc {

if user.Role == models.RoleUser {
s.Id = "" // 如果是普通用户,创建时不可以指定 ID
}

if s.Id != "" {
// 如果管理员指定了 ID,则检查 ID 是否可用
checkShortLink, _ := repo.Get(s.Id)

if checkShortLink.Id != "" {
c.JSON(http.StatusOK, gin.H{
"msg": fmt.Sprintf("%s 已被占用,请使用其他 ID。", s.Id),
"code": 4999,
"data": nil,
})
return
}
} else {
if s.Id != "" { // 如果管理员指定了 ID,则检查 ID 是否可用
checkShortLink, _ := repo.Get(s.Id)

if checkShortLink.Id != "" {
c.JSON(http.StatusOK, gin.H{
"msg": fmt.Sprintf("%s 已被占用,请使用其他 ID。", s.Id),
"code": 4999,
"data": nil,
})
return
}
} else { // 如果管理员没有指定 ID,则计算随机 ID 的长度
idMinimumLength := cfg.GetIntValue("idMinimumLength", 2)
idMaximumLength := cfg.GetIntValue("idMaximumLength", 10)

if idMinimumLength <= params.IdLength && params.IdLength <= idMaximumLength { // 检查是否在合法的范围内
idLen = params.IdLength
}
// 如果管理员没有指定 ID,则计算随机 ID 的长度
idMinimumLength := cfg.GetIntValue("idMinimumLength", 2)
idMaximumLength := cfg.GetIntValue("idMaximumLength", 10)

if idMinimumLength <= params.IdLength && params.IdLength <= idMaximumLength { // 检查是否在合法的范围内
idLen = params.IdLength
}
}

id, err := repo.GenerateId(idLen) // 生成 ID
id, err := repo.GenerateId(idLen) // 生成指定长度的随机 ID

if err != nil {
log.Printf("generate id failed, error: %v\n", err)
c.JSON(http.StatusOK, gin.H{
"msg": "服务器繁忙,请稍后再试",
"code": 4999,
"data": nil,
})
return
}
if err != nil {
log.Printf("generate id failed, error: %v\n", err)
c.JSON(http.StatusOK, gin.H{
"msg": "服务器繁忙,请稍后再试",
"code": 4999,
"data": nil,
})
return
}

s.Id = utils.TrimShortLinkId(id)
s.Id = utils.TrimShortLinkId(id)
}

if s.Id == "" {
log.Println("短链接 ID 为空")
Expand Down

0 comments on commit a0ca418

Please sign in to comment.