netbird/management/server/personal_access_token.go

63 lines
1.7 KiB
Go
Raw Normal View History

package server
import (
"crypto/sha256"
"fmt"
"hash/crc32"
"time"
"codeberg.org/ac/base62"
2023-03-08 11:36:03 +01:00
b "github.com/hashicorp/go-secure-stdlib/base62"
2023-03-02 16:19:31 +01:00
"github.com/rs/xid"
)
2023-03-08 11:54:10 +01:00
const (
PATPrefix = "nbp_"
secretLength = 30
)
2023-03-06 14:46:04 +01:00
// PersonalAccessToken holds all information about a PAT including a hashed version of it for verification
type PersonalAccessToken struct {
2023-03-02 16:19:31 +01:00
ID string
Description string
2023-03-08 11:30:09 +01:00
HashedToken string
ExpirationDate time.Time
// scope could be added in future
CreatedBy string
CreatedAt time.Time
LastUsed time.Time
}
2023-03-06 14:46:04 +01:00
// CreateNewPAT will generate a new PersonalAccessToken that can be assigned to a User.
// Additionally, it will return the token in plain text once, to give to the user and only save a hashed version
2023-03-08 11:36:03 +01:00
func CreateNewPAT(description string, expirationInDays int, createdBy string) (*PersonalAccessToken, string, error) {
hashedToken, plainToken, err := generateNewToken()
if err != nil {
return nil, "", err
}
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,
2023-03-08 11:36:03 +01:00
}, plainToken, nil
}
2023-03-08 11:36:03 +01:00
func generateNewToken() (string, string, error) {
2023-03-08 11:54:10 +01:00
secret, err := b.Random(secretLength)
2023-03-08 11:36:03 +01:00
if err != nil {
return "", "", err
}
2023-03-06 13:51:32 +01:00
checksum := crc32.ChecksumIEEE([]byte(secret))
encodedChecksum := base62.Encode(checksum)
paddedChecksum := fmt.Sprintf("%06s", encodedChecksum)
2023-03-08 11:54:10 +01:00
plainToken := PATPrefix + secret + paddedChecksum
hashedToken := sha256.Sum256([]byte(plainToken))
2023-03-08 11:36:03 +01:00
return string(hashedToken[:]), plainToken, nil
}