Clean public release with: - Go/Gin/PostgreSQL/Redis architecture - Multi-tenant support - JWT authentication - Docker Compose deployment - Environment-based configuration
47 lines
1.1 KiB
Go
47 lines
1.1 KiB
Go
package application
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
type Claims struct {
|
|
UserID uint `json:"user_id"`
|
|
TenantID string `json:"tenant_id"`
|
|
Type string `json:"type"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func GenerateToken(userID uint, tenantID, tokenType string, expiry time.Duration, secret, issuer string) (string, error) {
|
|
claims := Claims{
|
|
UserID: userID,
|
|
TenantID: tenantID,
|
|
Type: tokenType,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expiry)),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
Issuer: issuer,
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(secret))
|
|
}
|
|
|
|
func ParseToken(tokenString, secret string) (*Claims, error) {
|
|
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
|
return []byte(secret), nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
claims, ok := token.Claims.(*Claims)
|
|
if !ok || !token.Valid {
|
|
return nil, jwt.ErrTokenInvalidClaims
|
|
}
|
|
|
|
return claims, nil
|
|
}
|