diff --git a/common/utils.go b/common/utils.go index 4892404c..de15ce17 100644 --- a/common/utils.go +++ b/common/utils.go @@ -5,6 +5,7 @@ import ( "github.com/google/uuid" "html/template" "log" + "math/rand" "net" "os/exec" "runtime" @@ -133,6 +134,29 @@ func GetUUID() string { return code } +const keyChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + +func init() { + rand.Seed(time.Now().UnixNano()) +} + +func GenerateKey() string { + rand.Seed(time.Now().UnixNano()) + key := make([]byte, 48) + for i := 0; i < 16; i++ { + key[i] = keyChars[rand.Intn(len(keyChars))] + } + uuid_ := GetUUID() + for i := 0; i < 32; i++ { + c := uuid_[i] + if i%2 == 0 && c >= 'a' && c <= 'z' { + c = c - 'a' + 'A' + } + key[i+16] = c + } + return string(key) +} + func GetTimestamp() int64 { return time.Now().Unix() } diff --git a/controller/token.go b/controller/token.go index 180c4259..c486e341 100644 --- a/controller/token.go +++ b/controller/token.go @@ -119,7 +119,7 @@ func AddToken(c *gin.Context) { cleanToken := model.Token{ UserId: c.GetInt("id"), Name: token.Name, - Key: common.GetUUID(), + Key: common.GenerateKey(), CreatedTime: common.GetTimestamp(), AccessedTime: common.GetTimestamp(), ExpiredTime: token.ExpiredTime, diff --git a/model/token.go b/model/token.go index ef2d914b..4adf42e5 100644 --- a/model/token.go +++ b/model/token.go @@ -11,7 +11,7 @@ import ( type Token struct { Id int `json:"id"` UserId int `json:"user_id"` - Key string `json:"key" gorm:"type:char(32);uniqueIndex"` + Key string `json:"key" gorm:"type:char(48);uniqueIndex"` Status int `json:"status" gorm:"default:1"` Name string `json:"name" gorm:"index" ` CreatedTime int64 `json:"created_time" gorm:"bigint"` diff --git a/web/src/components/TokensTable.js b/web/src/components/TokensTable.js index fa77a32d..0a48a2ed 100644 --- a/web/src/components/TokensTable.js +++ b/web/src/components/TokensTable.js @@ -238,11 +238,12 @@ const TokensTable = () => { size={'small'} positive onClick={async () => { - if (await copy(token.key)) { + let key = "sk-" + token.key; + if (await copy(key)) { showSuccess('已复制到剪贴板!'); } else { showWarning('无法复制到剪贴板,请手动复制,已将令牌填入搜索框。'); - setSearchKeyword(token.key); + setSearchKeyword(key); } }} >