2024-08-14 10:36:43 +00:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
2024-10-09 17:07:38 +00:00
|
|
|
"git.sch9.ru/new_gate/ms-auth/pkg/utils"
|
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{
|
2024-10-09 17:07:38 +00:00
|
|
|
Id: utils.AsStringP(uuid.NewString()),
|
2024-08-14 10:36:43 +00:00
|
|
|
UserId: &userId,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s Session) Valid() error {
|
|
|
|
if s.Id == nil {
|
2024-10-09 17:07:38 +00:00
|
|
|
return utils.ErrBadSession
|
2024-08-14 10:36:43 +00:00
|
|
|
}
|
|
|
|
if s.UserId == nil {
|
2024-10-09 17:07:38 +00:00
|
|
|
return utils.ErrBadSession
|
2024-08-14 10:36:43 +00:00
|
|
|
}
|
|
|
|
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 {
|
2024-10-09 17:07:38 +00:00
|
|
|
return "", utils.ErrBadSession
|
2024-08-14 10:36:43 +00:00
|
|
|
}
|
|
|
|
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 {
|
2024-10-09 17:07:38 +00:00
|
|
|
return nil, utils.ErrBadSession
|
2024-08-14 10:36:43 +00:00
|
|
|
}
|
|
|
|
session := parsedToken.Claims.(*Session)
|
|
|
|
if err = session.Valid(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return session, nil
|
|
|
|
}
|