Add JWT encoding & decoding

This commit is contained in:
perp 2024-06-03 13:51:42 +01:00
parent b94b872f3f
commit eacc0b5dc9
4 changed files with 86 additions and 0 deletions

View File

@ -22,6 +22,7 @@ import (
"git.supernets.org/perp/gopay/internal/config"
"git.supernets.org/perp/gopay/internal/context"
"git.supernets.org/perp/gopay/internal/database"
"git.supernets.org/perp/gopay/internal/jwt"
"git.supernets.org/perp/gopay/internal/router"
"github.com/rs/zerolog/log"
)
@ -37,6 +38,9 @@ func main() {
cfg := config.Parse(content)
config.SetupLogger(cfg.Log)
// Create JWT
jwt.New(cfg.Auth.Secret)
// Create database
db := database.New(cfg.Database)

29
internal/jwt/decode.go Normal file
View File

@ -0,0 +1,29 @@
package jwt
import (
"github.com/golang-jwt/jwt"
"github.com/rs/zerolog/log"
)
// Decode a token
func Decode(token string) (*Claims, error) {
// Create token claims
tokenClaims, err := jwt.ParseWithClaims(
token,
&Claims{},
func(token *jwt.Token) (interface{}, error) {
return secret, nil
},
)
// Found token
if tokenClaims != nil {
// Map to claims struct & if ok & valid then return
if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
return claims, nil
}
}
log.Err(err).Msg("Could not decode JWT claims")
return nil, err
}

36
internal/jwt/encode.go Normal file
View File

@ -0,0 +1,36 @@
package jwt
import (
"fmt"
"time"
"github.com/golang-jwt/jwt"
"github.com/rs/zerolog/log"
)
// Encode a token
func Encode(id int) (string, error) {
// Get time
now := time.Now()
// Create claims
claims := &Claims{
jwt.StandardClaims{
IssuedAt: now.Unix(),
ExpiresAt: now.Add(time.Hour * 12).Unix(),
},
id,
}
// Create token claims
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign token with secret
token, err := tokenClaims.SignedString(secret)
if err != nil {
log.Err(err).Str("id", fmt.Sprintf("%d", id)).Msg("Could not encode JWT claims")
return "", err
}
return token, nil
}

17
internal/jwt/jwt.go Normal file
View File

@ -0,0 +1,17 @@
package jwt
import "github.com/golang-jwt/jwt"
// JWT secret
var secret string
// JWT claims
type Claims struct {
jwt.StandardClaims
ID int `json:"id"` // User ID
}
// Set the JWT secret
func New(sec string) {
secret = sec
}