package models import ( "git.sch9.ru/new_gate/ms-auth/pkg/utils" "github.com/golang-jwt/jwt" "github.com/google/uuid" ) type Session struct { Id *string UserId *int32 } func NewSession(userId int32) *Session { return &Session{ Id: utils.AsStringP(uuid.NewString()), UserId: &userId, } } func (s Session) Valid() error { if s.Id == nil { return utils.ErrBadSession } if s.UserId == nil { return utils.ErrBadSession } return nil } func (s Session) Token(secret string) (string, error) { if err := s.Valid(); err != nil { return "", err } refreshToken := jwt.NewWithClaims(jwt.SigningMethodHS256, s) str, err := refreshToken.SignedString([]byte(secret)) if err != nil { return "", utils.ErrBadSession } return str, nil } func Parse(tkn string, secret string) (*Session, error) { parsedToken, err := jwt.ParseWithClaims(tkn, &Session{}, func(token *jwt.Token) (interface{}, error) { return []byte(secret), nil }) if err != nil { return nil, utils.ErrBadSession } session := parsedToken.Claims.(*Session) if err = session.Valid(); err != nil { return nil, err } return session, nil }