2023-03-01 20:12:04 +01:00
|
|
|
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"
|
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
|
|
|
|
HashedToken [32]byte
|
|
|
|
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-03 16:37:39 +01:00
|
|
|
func CreateNewPAT(description string, expirationInDays int, createdBy string) (*PersonalAccessToken, string) {
|
2023-03-01 20:12:04 +01:00
|
|
|
hashedToken, plainToken := generateNewToken()
|
|
|
|
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-01 20:12:04 +01:00
|
|
|
}, plainToken
|
|
|
|
}
|
|
|
|
|
|
|
|
func generateNewToken() ([32]byte, string) {
|
2023-03-06 13:51:32 +01:00
|
|
|
secret := randStringRunes(30)
|
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-06 13:51:32 +01:00
|
|
|
plainToken := "nbp_" + secret + paddedChecksum
|
2023-03-01 20:12:04 +01:00
|
|
|
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)
|
|
|
|
}
|