42 строки
852 B
Go
42 строки
852 B
Go
// Package concerns provides functionality.
|
|
package concerns
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
)
|
|
|
|
// HasToken provides functionality.
|
|
type HasToken struct {
|
|
Token string `json:"-" gorm:"unique_index"`
|
|
}
|
|
|
|
// SetToken provides functionality.
|
|
func (m *HasToken) SetToken() {
|
|
tk := RandomToken(32)
|
|
m.Token = base64.RawURLEncoding.EncodeToString(tk)
|
|
if m.Token == "" {
|
|
panic("RandomToken failed: token not set")
|
|
}
|
|
if len(m.Token) < 32 {
|
|
panic("RandomToken failed: token too short")
|
|
}
|
|
}
|
|
|
|
// RandomToken provides functionality.
|
|
func RandomToken(tokenLen int) []byte {
|
|
b := make([]byte, tokenLen)
|
|
n, err := rand.Read(b)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if n != tokenLen {
|
|
panic("RandomToken failed: bad len")
|
|
}
|
|
if bytes.Equal(b, make([]byte, tokenLen)) {
|
|
panic("RandomToken failed: generated empty token")
|
|
}
|
|
return b
|
|
}
|