85 lines
1.7 KiB
Go
85 lines
1.7 KiB
Go
package utils
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"strconv"
|
|
"time"
|
|
|
|
glide "github.com/valkey-io/valkey-glide/go/v2"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Application struct {
|
|
Logger *slog.Logger
|
|
DB *gorm.DB
|
|
Client *glide.Client
|
|
}
|
|
|
|
type Session struct {
|
|
Token string
|
|
UserID uint
|
|
MandantId uint
|
|
}
|
|
|
|
func (s *Session) Deserialize(t string, m map[string]string) (*Session, error) {
|
|
userid, err := strconv.Atoi(m["userid"])
|
|
if err != nil {
|
|
return nil, errors.New("Userid from cache not an int")
|
|
}
|
|
|
|
mandantid, err := strconv.Atoi(m["mandantid"])
|
|
if err != nil {
|
|
return nil, errors.New("Mandantid from cache not an int")
|
|
}
|
|
|
|
s.Token = t
|
|
s.UserID = uint(userid)
|
|
s.MandantId = uint(mandantid)
|
|
|
|
return s, nil
|
|
}
|
|
|
|
func (s *Session) Serialize() map[string]string {
|
|
m := make(map[string]string)
|
|
m["userid"] = strconv.Itoa(int(s.UserID))
|
|
m["mandantid"] = strconv.Itoa(int(s.MandantId))
|
|
return m
|
|
}
|
|
|
|
func (a *Application) AddSession(s *Session) {
|
|
// options.HSetExOptions{Expiry: options.NewExpiryIn(time.Hour * 2)}
|
|
_, err := a.Client.HSet(context.Background(), s.Token, s.Serialize())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = a.Client.Expire(context.Background(), s.Token, time.Hour*2)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func (a *Application) GetSessionFromToken(token string) (*Session, error) {
|
|
s, err := a.Client.HGetAll(context.Background(), token)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = a.Client.Expire(context.Background(), token, time.Hour*2)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return (&Session{}).Deserialize(token, s)
|
|
}
|
|
|
|
func (a *Application) RemoveSession(token string) {
|
|
_, err := a.Client.HDel(context.Background(), token, []string{"userid", "mandantid"})
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|