all clients should be saved in cache
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
var secretKey = []byte("replace-with-env-variable")
|
||||
|
||||
type UserClaims struct {
|
||||
Name string `json:"name"`
|
||||
Color [3]byte `json:"color"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func GetToken(client *Client) (string, error) {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256,
|
||||
UserClaims{
|
||||
Name: client.Name,
|
||||
Color: client.Color,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: strconv.Itoa(int(client.Id)),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
},
|
||||
)
|
||||
return token.SignedString(secretKey)
|
||||
}
|
||||
|
||||
func SetClientFromToken(client *Client, tokenString string) error {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return secretKey, nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*UserClaims)
|
||||
if !ok || !token.Valid {
|
||||
return errors.New("invalid token")
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(claims.Subject, 10, 32)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid subject: %w", err)
|
||||
}
|
||||
|
||||
client.Id = uint32(id)
|
||||
client.Name = claims.Name
|
||||
client.Color = claims.Color
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user