f
This commit is contained in:
35
internal/application/subordinate/invite_token.go
Normal file
35
internal/application/subordinate/invite_token.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package subordinate
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
const (
|
||||
// 邀请码固定 6 位,字符集为大写字母+数字
|
||||
inviteTokenLength = 6
|
||||
inviteTokenCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
)
|
||||
|
||||
// HashInviteToken 邀请码 SHA256 十六进制
|
||||
func HashInviteToken(raw string) string {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// GenerateInviteToken 生成随机邀请明文与存储用哈希
|
||||
func GenerateInviteToken() (raw string, hash string, err error) {
|
||||
token := make([]byte, inviteTokenLength)
|
||||
charsetSize := big.NewInt(int64(len(inviteTokenCharset)))
|
||||
for i := range token {
|
||||
n, e := rand.Int(rand.Reader, charsetSize)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
token[i] = inviteTokenCharset[n.Int64()]
|
||||
}
|
||||
raw = string(token)
|
||||
return raw, HashInviteToken(raw), nil
|
||||
}
|
||||
Reference in New Issue
Block a user