netbird/management/server/personal_access_token.go

59 lines
1.4 KiB
Go
Raw Normal View History

package server
import (
"crypto/sha256"
"fmt"
"hash/crc32"
"math/rand"
"time"
"codeberg.org/ac/base62"
2023-03-02 16:19:31 +01:00
"github.com/rs/xid"
)
type PersonalAccessToken struct {
2023-03-02 16:19:31 +01:00
ID string
Description string
HashedToken [32]byte
ExpirationDate time.Time
// scope could be added in future
CreatedBy string
CreatedAt time.Time
LastUsed time.Time
}
func CreateNewPAT(description string, expirationInDays int, createdBy string) (*PersonalAccessToken, string) {
hashedToken, plainToken := generateNewToken()
currentTime := time.Now().UTC()
return &PersonalAccessToken{
2023-03-02 16:19:31 +01:00
ID: xid.New().String(),
Description: description,
HashedToken: hashedToken,
ExpirationDate: currentTime.AddDate(0, 0, expirationInDays),
CreatedBy: createdBy,
CreatedAt: currentTime,
2023-03-06 13:49:07 +01:00
LastUsed: currentTime,
}, plainToken
}
func generateNewToken() ([32]byte, string) {
2023-03-06 13:51:32 +01:00
secret := randStringRunes(30)
2023-03-06 13:51:32 +01:00
checksum := crc32.ChecksumIEEE([]byte(secret))
encodedChecksum := base62.Encode(checksum)
paddedChecksum := fmt.Sprintf("%06s", encodedChecksum)
2023-03-06 13:51:32 +01:00
plainToken := "nbp_" + secret + paddedChecksum
hashedToken := sha256.Sum256([]byte(plainToken))
return hashedToken, plainToken
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
func randStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}