package services import ( "context" "git.sch9.ru/new_gate/ms-auth/internal/lib" "git.sch9.ru/new_gate/ms-auth/internal/models" ) type SessionProvider interface { CreateSession(ctx context.Context, userId int32) error 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 DeleteSessionByToken(ctx context.Context, token string) error DeleteSessionByUserId(ctx context.Context, userId int32) error } type SessionService struct { sessionProvider SessionProvider userProvider UserStorage cfg lib.Config } func NewSessionService(sessionProvider SessionProvider, userProvider UserStorage, cfg lib.Config) *SessionService { return &SessionService{ sessionProvider: sessionProvider, userProvider: userProvider, cfg: cfg, } } func (s *SessionService) Create(ctx context.Context, handle, password string) (*string, error) { var ( err error user *models.User ) 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 } err = s.sessionProvider.CreateSession(ctx, *user.Id) if err != nil { return nil, err } session, err := s.sessionProvider.ReadSessionByUserId(ctx, *user.Id) 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 }