heruvym/jwt_adapter/jwt_adapter.go
2021-05-15 23:10:07 +03:00

121 lines
2.1 KiB
Go

package jwt_adapter
import (
"context"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/rs/xid"
"github.com/skeris/identity/cookie"
"os"
"time"
)
var _ cookie.Cookie = new(JwtAdapter)
func init() {
aS := os.Getenv("JWT_SECRET")
if len(aS) != 0 {
accessSecret = aS
}
}
type JwtAdapter struct {
ID string
Session string
User string
Tariff uint8
Created int64
LastSeen int64
jwt.StandardClaims
}
func (c *JwtAdapter) Init() {
if c.ID == "" {
c.ID = xid.New().String()
}
c.Session = xid.New().String()
c.User = ""
c.Tariff = uint8(0)
t := Timestamp()
c.Created = t
c.LastSeen = t
}
func Get(ctx context.Context) *JwtAdapter {
if adapter, ok := ctx.Value(DefaultHeaderKey).(*JwtAdapter); ok {
return adapter
}
return nil
}
func (c *JwtAdapter) SetUserID(id string) {
c.User = id
}
func (c *JwtAdapter) GetUserID() string {
return c.User
}
func (c *JwtAdapter) GetTariff() uint8 {
return c.Tariff
}
func (c *JwtAdapter) SetTariff(status uint8) {
c.Tariff = status
}
func (c *JwtAdapter) GetSessionID() string {
return c.Session
}
func (c *JwtAdapter) SetSessionID(id string) {
c.Session = id
c.User = ""
}
const (
DefaultAccessSecret = "awesomeAC"
DefaultHeaderKey = "Authorization"
)
var accessSecret = DefaultAccessSecret
func (c *JwtAdapter) Encode() (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
ss, err := token.SignedString([]byte(accessSecret))
return ss, err
}
func Decode(tokenString string) (*JwtAdapter, error) {
claims := JwtAdapter{}
token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
//Make sure that the token method conform to "SigningMethodHMAC"
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(accessSecret), nil
})
if err != nil {
return nil, err
}
if _, ok := token.Claims.(jwt.Claims); !ok && !token.Valid {
return nil, fmt.Errorf("ErrorNoValidClaims")
}
return &claims, nil
}
func Timestamp() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}