Files
mtusi2026lab5/internal/storage/postgres/session_repository_test.go
T
2026-10-29 23:36:12 +03:00

82 lines
2.2 KiB
Go

//go:build integration
package postgres_test
import (
"testing"
"time"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
"mtusi-messenger/internal/platform/token"
)
type SessionRepositorySuite struct {
BaseSuite
}
func TestSessionRepositorySuite(t *testing.T) {
suite.Run(t, new(SessionRepositorySuite))
}
func (s *SessionRepositorySuite) TestCredentials() {
alice := s.createUser("alice")
credentials, err := s.store.Sessions().Credentials(s.T().Context(), "alice")
s.Require().NoError(err)
s.Equal(alice.ID, credentials.User.ID)
s.True(password.Verify("strong-test-password", credentials.PasswordHash))
s.False(password.Verify("wrong-password-value", credentials.PasswordHash))
}
func (s *SessionRepositorySuite) TestCredentialsUnknownUser() {
_, err := s.store.Sessions().Credentials(s.T().Context(), "nobody")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestCreateResolveRevoke() {
alice := s.createUser("alice")
_, hash, err := token.New().Generate()
s.Require().NoError(err)
expiresAt := time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond)
created, err := s.store.Sessions().Create(s.T().Context(), domain.NewSession{
TokenHash: hash,
UserID: alice.ID,
ExpiresAt: expiresAt,
})
s.Require().NoError(err)
s.Equal(expiresAt, created.ExpiresAt)
resolved, err := s.store.Sessions().Resolve(s.T().Context(), hash)
s.Require().NoError(err)
s.Equal(alice.ID, resolved.User.ID)
s.Equal(created.ExpiresAt, resolved.ExpiresAt)
s.Require().NoError(s.store.Sessions().Revoke(s.T().Context(), alice.ID, hash))
_, err = s.store.Sessions().Resolve(s.T().Context(), hash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestResolveRejectsExpiredToken() {
alice := s.createUser("alice")
_, hash, err := token.New().Generate()
s.Require().NoError(err)
_, err = s.store.Sessions().Create(s.T().Context(), domain.NewSession{
TokenHash: hash,
UserID: alice.ID,
ExpiresAt: time.Now().UTC().Add(-time.Minute),
})
s.Require().NoError(err)
_, err = s.store.Sessions().Resolve(s.T().Context(), hash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}