gotunnelserver/util/entity.go

65 lines
1.3 KiB
Go

package util
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"math/rand"
"time"
)
type Entity struct {
Username string `json:"username"`
// Token string `json:"token"`
}
type AuthEntity struct {
Entity
Time int64 `json:"time"`
Authtoken string `json:"authtoken"`
}
func VerifyAuth(a *AuthEntity, salt string) bool {
current := time.Now()
if current.Sub(time.Unix(a.Time, 0)).Minutes() > 5 {
return false
}
return a.Authtoken == GenAuthToken(a, salt)
}
func GenAuthToken(a *AuthEntity, salt string) string {
str := fmt.Sprintf("%s:%d:%s", a.Username, a.Time, salt)
h := md5.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
func ParseAuthEntity(str string) (a *AuthEntity, err error) {
dbytes, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return nil, err
}
a = new(AuthEntity)
err = json.Unmarshal(dbytes, a)
return a, err
}
func GenRandomstring(n int) string {
// 生成长度为n的随机字符串
// rand.Seed(time.Now().UnixNano())
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func GenRandomInt() int32 {
// rand.Seed(time.Now().UnixNano())
return int32(rand.Intn(65534) + 1)
}