ms-auth/internal/models/session.go

66 lines
1.3 KiB
Go
Raw Normal View History

2024-08-14 10:36:43 +00:00
package models
import (
2024-12-30 15:04:26 +00:00
"encoding/json"
"errors"
2024-08-14 10:36:43 +00:00
"github.com/google/uuid"
2024-12-30 15:04:26 +00:00
"time"
2024-08-14 10:36:43 +00:00
)
type Session struct {
2024-12-30 15:04:26 +00:00
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"`
2024-08-14 10:36:43 +00:00
}
func (s Session) Valid() error {
2024-12-30 15:04:26 +00:00
if uuid.Validate(s.Id) != nil {
return errors.New("invalid session id")
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
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")
2024-08-14 10:36:43 +00:00
}
return nil
}
2024-12-30 15:04:26 +00:00
func NewSession(userId int32, role Role) (string, string, error) {
s := &Session{
Id: uuid.NewString(),
UserId: userId,
Role: role,
CreatedAt: time.Now(),
}
2024-08-14 10:36:43 +00:00
if err := s.Valid(); err != nil {
2024-12-30 15:04:26 +00:00
return "", "", err
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
b, err := json.Marshal(s)
2024-08-14 10:36:43 +00:00
if err != nil {
2024-12-30 15:04:26 +00:00
return "", "", err
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
return string(b), s.Id, nil
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
func ParseSession(s string) (*Session, error) {
sess := &Session{}
if err := json.Unmarshal([]byte(s), sess); err != nil {
return nil, err
2024-08-14 10:36:43 +00:00
}
2024-12-30 15:04:26 +00:00
if err := sess.Valid(); err != nil {
2024-08-14 10:36:43 +00:00
return nil, err
}
2024-12-30 15:04:26 +00:00
return sess, nil
2024-08-14 10:36:43 +00:00
}