2023-03-01 20:12:04 +01:00
|
|
|
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-01 20:12:04 +01:00
|
|
|
)
|
|
|
|
|
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
|
2023-03-01 20:12:04 +01:00
|
|
|
type PersonalAccessToken struct {
|
2023-03-02 16:19:31 +01:00
|
|
|
ID string
|
2023-03-01 20:12:04 +01:00
|
|
|
Description string
|
2023-03-08 11:30:09 +01:00
|
|
|
HashedToken string
|
2023-03-01 20:12:04 +01:00
|
|
|
ExpirationDate time.Time
|
|
|
|
// scope could be added in future
|
2023-03-03 16:37:39 +01:00
|
|
|
CreatedBy string
|
2023-03-01 20:12:04 +01:00
|
|
|
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
|
|
|
|
}
|
2023-03-01 20:12:04 +01:00
|
|
|
currentTime := time.Now().UTC()
|
|
|
|
return &PersonalAccessToken{
|
2023-03-02 16:19:31 +01:00
|
|
|
ID: xid.New().String(),
|
2023-03-01 20:12:04 +01:00
|
|
|
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-01 20:12:04 +01:00
|
|
|
}
|
|
|
|
|
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-01 20:12:04 +01:00
|
|
|
|
2023-03-06 13:51:32 +01:00
|
|
|
checksum := crc32.ChecksumIEEE([]byte(secret))
|
2023-03-01 20:12:04 +01:00
|
|
|
encodedChecksum := base62.Encode(checksum)
|
|
|
|
paddedChecksum := fmt.Sprintf("%06s", encodedChecksum)
|
2023-03-08 11:54:10 +01:00
|
|
|
plainToken := PATPrefix + secret + paddedChecksum
|
2023-03-01 20:12:04 +01:00
|
|
|
hashedToken := sha256.Sum256([]byte(plainToken))
|
2023-03-08 11:36:03 +01:00
|
|
|
return string(hashedToken[:]), plainToken, nil
|
2023-03-01 20:12:04 +01:00
|
|
|
}
|