2024-08-14 10:36:43 +00:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
2024-08-14 15:24:57 +00:00
|
|
|
"git.sch9.ru/new_gate/ms-auth/internal/lib"
|
2024-08-14 10:36:43 +00:00
|
|
|
"github.com/golang-jwt/jwt"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Session struct {
|
|
|
|
Id *string
|
|
|
|
UserId *int32
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSession(userId int32) *Session {
|
|
|
|
return &Session{
|
|
|
|
Id: lib.AsStringP(uuid.NewString()),
|
|
|
|
UserId: &userId,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s Session) Valid() error {
|
|
|
|
if s.Id == nil {
|
|
|
|
return lib.ErrBadSession
|
|
|
|
}
|
|
|
|
if s.UserId == nil {
|
|
|
|
return lib.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 "", lib.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, lib.ErrBadSession
|
|
|
|
}
|
|
|
|
session := parsedToken.Claims.(*Session)
|
|
|
|
if err = session.Valid(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return session, nil
|
|
|
|
}
|