ms-auth/internal/services/session.go

103 lines
2.5 KiB
Go
Raw Normal View History

2024-07-14 21:26:34 +00:00
package services
import (
"context"
2024-08-14 15:24:57 +00:00
"git.sch9.ru/new_gate/ms-auth/internal/lib"
"git.sch9.ru/new_gate/ms-auth/internal/models"
2024-07-14 21:26:34 +00:00
)
type SessionProvider interface {
CreateSession(ctx context.Context, userId int32) error
2024-08-14 10:36:43 +00:00
ReadSessionByToken(ctx context.Context, token string) (*models.Session, error)
ReadSessionByUserId(ctx context.Context, userId int32) (*models.Session, error)
UpdateSession(ctx context.Context, session *models.Session) error
2024-07-14 21:26:34 +00:00
DeleteSessionByToken(ctx context.Context, token string) error
DeleteSessionByUserId(ctx context.Context, userId int32) error
}
type SessionService struct {
sessionProvider SessionProvider
2024-08-14 10:36:43 +00:00
userProvider UserStorage
cfg lib.Config
2024-07-14 21:26:34 +00:00
}
2024-08-14 10:36:43 +00:00
func NewSessionService(sessionProvider SessionProvider, userProvider UserStorage, cfg lib.Config) *SessionService {
2024-07-14 21:26:34 +00:00
return &SessionService{
sessionProvider: sessionProvider,
userProvider: userProvider,
cfg: cfg,
}
}
func (s *SessionService) Create(ctx context.Context, handle, password string) (*string, error) {
var (
err error
2024-08-14 10:36:43 +00:00
user *models.User
2024-07-14 21:26:34 +00:00
)
if lib.ValidUsername(handle) == nil {
user, err = s.userProvider.ReadUserByUsername(ctx, handle)
} else if lib.ValidEmail(handle) == nil {
user, err = s.userProvider.ReadUserByEmail(ctx, handle)
} else {
return nil, lib.ErrBadHandleOrPassword
}
if err != nil {
return nil, err
}
err = user.ComparePassword(password)
if err != nil {
return nil, err
}
2024-08-14 10:36:43 +00:00
err = s.sessionProvider.CreateSession(ctx, *user.Id)
2024-07-14 21:26:34 +00:00
if err != nil {
return nil, err
}
2024-08-14 10:36:43 +00:00
session, err := s.sessionProvider.ReadSessionByUserId(ctx, *user.Id)
2024-07-14 21:26:34 +00:00
if err != nil {
return nil, err
}
token, err := session.Token(s.cfg.JWTSecret)
if err != nil {
return nil, err
}
return &token, nil
}
func (s *SessionService) Read(ctx context.Context, token string) (*int32, error) {
session, err := s.sessionProvider.ReadSessionByToken(ctx, token)
if err != nil {
return nil, err
}
return session.UserId, nil
}
func (s *SessionService) Update(ctx context.Context, token string) error {
session, err := s.sessionProvider.ReadSessionByToken(ctx, token)
if err != nil {
return err
}
err = s.sessionProvider.UpdateSession(ctx, session)
if err != nil {
return err
}
return nil
}
func (s *SessionService) Delete(ctx context.Context, token string) error {
session, err := s.sessionProvider.ReadSessionByToken(ctx, token)
if err != nil {
return err
}
err = s.sessionProvider.DeleteSessionByUserId(ctx, *session.UserId)
if err != nil {
return err
}
return nil
}