ms-auth/internal/models/session.go
Vyacheslav1557 3b03447d2f feat(user):
2024-12-30 20:04:26 +05:00

66 lines
1.3 KiB
Go

package models
import (
"encoding/json"
"errors"
"github.com/google/uuid"
"time"
)
type Session struct {
Id string `json:"id" db:"id"`
UserId int32 `json:"user_id" db:"user_id"`
Role Role `json:"role" db:"role"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
//UserAgent string `json:"user_agent"`
//Ip string `json:"ip"`
}
func (s Session) Valid() error {
if uuid.Validate(s.Id) != nil {
return errors.New("invalid session id")
}
if s.UserId == 0 {
return errors.New("empty user id")
}
if s.CreatedAt.IsZero() {
return errors.New("empty created at")
}
if !s.Role.IsAdmin() && !s.Role.IsModerator() && !s.Role.IsParticipant() {
return errors.New("invalid role")
}
return nil
}
func NewSession(userId int32, role Role) (string, string, error) {
s := &Session{
Id: uuid.NewString(),
UserId: userId,
Role: role,
CreatedAt: time.Now(),
}
if err := s.Valid(); err != nil {
return "", "", err
}
b, err := json.Marshal(s)
if err != nil {
return "", "", err
}
return string(b), s.Id, nil
}
func ParseSession(s string) (*Session, error) {
sess := &Session{}
if err := json.Unmarshal([]byte(s), sess); err != nil {
return nil, err
}
if err := sess.Valid(); err != nil {
return nil, err
}
return sess, nil
}