From 6b7ce5b719380abb950b1b9c13ac32fbe117f660 Mon Sep 17 00:00:00 2001 From: vinchent Date: Tue, 13 Aug 2024 21:39:33 +0200 Subject: [PATCH] Create a function to generate a token --- internal/models/tokens.go | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 internal/models/tokens.go diff --git a/internal/models/tokens.go b/internal/models/tokens.go new file mode 100644 index 0000000..26282a6 --- /dev/null +++ b/internal/models/tokens.go @@ -0,0 +1,42 @@ +package models + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base32" + "time" +) + +const ( + ScopeAuthentication = "authentication" +) + +// Token is the type for authentication tokens +type Token struct { + PlainText string `json:"token"` + UserID int64 `json:"-"` + Hash []byte `json:"-"` + Expiry time.Time `json:"expiry"` + Scope string `json:"-"` +} + +// GenerateToken Generates a token that lasts for ttl, and returns it +func GenerateToken(userID int, ttl time.Duration, scope string) (*Token, error) { + token := &Token{ + UserID: int64(userID), + Expiry: time.Now().Add(ttl), + Scope: scope, + } + + randomBytes := make([]byte, 16) + _, err := rand.Read(randomBytes) + if err != nil { + return nil, err + } + + token.PlainText = base32.StdEncoding.WithPadding((base32.NoPadding)). + EncodeToString((randomBytes)) + hash := sha256.Sum256([]byte(token.PlainText)) + token.Hash = hash[:] + return token, nil +}