lab2
This commit is contained in:
@@ -9,8 +9,6 @@ import (
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
//go:generate go tool mockery
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
|
||||
|
||||
@@ -9,8 +9,6 @@ import (
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
//go:generate go tool mockery
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
|
||||
ListVisible(
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, session)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, session)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewSession) error); ok {
|
||||
r1 = returnFunc(ctx, session)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - session domain.NewSession
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, session any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, session)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, session domain.NewSession)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.NewSession
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.NewSession)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(session1 domain.Session, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(session1, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, session domain.NewSession) (domain.Session, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Credentials provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
|
||||
ret := _mock.Called(ctx, username)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Credentials")
|
||||
}
|
||||
|
||||
var r0 domain.UserCredentials
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.UserCredentials, error)); ok {
|
||||
return returnFunc(ctx, username)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.UserCredentials); ok {
|
||||
r0 = returnFunc(ctx, username)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.UserCredentials)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, username)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Credentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Credentials'
|
||||
type MockRepository_Credentials_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Credentials is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - username string
|
||||
func (_e *MockRepository_Expecter) Credentials(ctx any, username any) *MockRepository_Credentials_Call {
|
||||
return &MockRepository_Credentials_Call{Call: _e.mock.On("Credentials", ctx, username)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) Run(run func(ctx context.Context, username string)) *MockRepository_Credentials_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) Return(userCredentials domain.UserCredentials, err error) *MockRepository_Credentials_Call {
|
||||
_c.Call.Return(userCredentials, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) RunAndReturn(run func(ctx context.Context, username string) (domain.UserCredentials, error)) *MockRepository_Credentials_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Resolve provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, tokenHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Resolve")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, tokenHash)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, tokenHash)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok {
|
||||
r1 = returnFunc(ctx, tokenHash)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
|
||||
type MockRepository_Resolve_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Resolve is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - tokenHash []byte
|
||||
func (_e *MockRepository_Expecter) Resolve(ctx any, tokenHash any) *MockRepository_Resolve_Call {
|
||||
return &MockRepository_Resolve_Call{Call: _e.mock.On("Resolve", ctx, tokenHash)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) Run(run func(ctx context.Context, tokenHash []byte)) *MockRepository_Resolve_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 []byte
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].([]byte)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) Return(session domain.Session, err error) *MockRepository_Resolve_Call {
|
||||
_c.Call.Return(session, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) RunAndReturn(run func(ctx context.Context, tokenHash []byte) (domain.Session, error)) *MockRepository_Resolve_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Revoke provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
ret := _mock.Called(ctx, userID, tokenHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Revoke")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []byte) error); ok {
|
||||
r0 = returnFunc(ctx, userID, tokenHash)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockRepository_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
|
||||
type MockRepository_Revoke_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Revoke is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - tokenHash []byte
|
||||
func (_e *MockRepository_Expecter) Revoke(ctx any, userID any, tokenHash any) *MockRepository_Revoke_Call {
|
||||
return &MockRepository_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, tokenHash)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte)) *MockRepository_Revoke_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 []byte
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]byte)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) Return(err error) *MockRepository_Revoke_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte) error) *MockRepository_Revoke_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockTokens creates a new instance of MockTokens. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockTokens(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockTokens {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockTokens{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockTokens is an autogenerated mock type for the Tokens type
|
||||
type MockTokens struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockTokens_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockTokens) EXPECT() *MockTokens_Expecter {
|
||||
return &MockTokens_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Generate provides a mock function for the type MockTokens
|
||||
func (_mock *MockTokens) Generate() (string, []byte, error) {
|
||||
ret := _mock.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Generate")
|
||||
}
|
||||
|
||||
var r0 string
|
||||
var r1 []byte
|
||||
var r2 error
|
||||
if returnFunc, ok := ret.Get(0).(func() (string, []byte, error)); ok {
|
||||
return returnFunc()
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func() string); ok {
|
||||
r0 = returnFunc()
|
||||
} else {
|
||||
r0 = ret.Get(0).(string)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func() []byte); ok {
|
||||
r1 = returnFunc()
|
||||
} else {
|
||||
if ret.Get(1) != nil {
|
||||
r1 = ret.Get(1).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func() error); ok {
|
||||
r2 = returnFunc()
|
||||
} else {
|
||||
r2 = ret.Error(2)
|
||||
}
|
||||
return r0, r1, r2
|
||||
}
|
||||
|
||||
// MockTokens_Generate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Generate'
|
||||
type MockTokens_Generate_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Generate is a helper method to define mock.On call
|
||||
func (_e *MockTokens_Expecter) Generate() *MockTokens_Generate_Call {
|
||||
return &MockTokens_Generate_Call{Call: _e.mock.On("Generate")}
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) Run(run func()) *MockTokens_Generate_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) Return(s string, bytes []byte, err error) *MockTokens_Generate_Call {
|
||||
_c.Call.Return(s, bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) RunAndReturn(run func() (string, []byte, error)) *MockTokens_Generate_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Hash provides a mock function for the type MockTokens
|
||||
func (_mock *MockTokens) Hash(raw string) ([]byte, error) {
|
||||
ret := _mock.Called(raw)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Hash")
|
||||
}
|
||||
|
||||
var r0 []byte
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(string) ([]byte, error)); ok {
|
||||
return returnFunc(raw)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(string) []byte); ok {
|
||||
r0 = returnFunc(raw)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = returnFunc(raw)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockTokens_Hash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Hash'
|
||||
type MockTokens_Hash_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Hash is a helper method to define mock.On call
|
||||
// - raw string
|
||||
func (_e *MockTokens_Expecter) Hash(raw any) *MockTokens_Hash_Call {
|
||||
return &MockTokens_Hash_Call{Call: _e.mock.On("Hash", raw)}
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) Run(run func(raw string)) *MockTokens_Hash_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 string
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) Return(bytes []byte, err error) *MockTokens_Hash_Call {
|
||||
_c.Call.Return(bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) RunAndReturn(run func(raw string) ([]byte, error)) *MockTokens_Hash_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
Credentials(ctx context.Context, username string) (domain.UserCredentials, error)
|
||||
Create(ctx context.Context, session domain.NewSession) (domain.Session, error)
|
||||
Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error)
|
||||
Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error
|
||||
}
|
||||
|
||||
type Tokens interface {
|
||||
Generate() (string, []byte, error)
|
||||
Hash(raw string) ([]byte, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
sessions Repository
|
||||
tokens Tokens
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewService(sessions Repository, tokens Tokens, ttl time.Duration) *Service {
|
||||
return &Service{sessions: sessions, tokens: tokens, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *Service) Authenticate(ctx context.Context, username, plain string) (domain.User, error) {
|
||||
credentials, err := s.sessions.Credentials(ctx, username)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", err)
|
||||
}
|
||||
|
||||
if !password.Verify(plain, credentials.PasswordHash) {
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
return credentials.User, nil
|
||||
}
|
||||
|
||||
func (s *Service) Resolve(ctx context.Context, raw string) (domain.User, error) {
|
||||
hash, err := s.tokens.Hash(raw)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("resolve session: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
session, err := s.sessions.Resolve(ctx, hash)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("resolve session: %w", err)
|
||||
}
|
||||
|
||||
return session.User, nil
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, user domain.User) (domain.Session, error) {
|
||||
raw, hash, err := s.tokens.Generate()
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
|
||||
session, err := s.sessions.Create(ctx, domain.NewSession{
|
||||
TokenHash: hash,
|
||||
UserID: user.ID,
|
||||
ExpiresAt: time.Now().UTC().Add(s.ttl),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
|
||||
session.Token = raw
|
||||
session.User = user
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *Service) Revoke(ctx context.Context, userID uuid.UUID, raw string) error {
|
||||
hash, err := s.tokens.Hash(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke session: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
if err := s.sessions.Revoke(ctx, userID, hash); err != nil {
|
||||
return fmt.Errorf("revoke session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package session_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/service/session"
|
||||
"mtusi-messenger/internal/service/session/mocks"
|
||||
)
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
sessions *mocks.MockRepository
|
||||
tokens *mocks.MockTokens
|
||||
service *session.Service
|
||||
ttl time.Duration
|
||||
user domain.User
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.sessions = mocks.NewMockRepository(s.T())
|
||||
s.tokens = mocks.NewMockTokens(s.T())
|
||||
s.ttl = time.Hour
|
||||
s.service = session.NewService(s.sessions, s.tokens, s.ttl)
|
||||
s.user = domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestResolveHashesTokenBeforeStorage() {
|
||||
hash := []byte("hashed-token")
|
||||
stored := domain.Session{ExpiresAt: time.Now().Add(time.Hour), User: s.user}
|
||||
|
||||
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
|
||||
s.sessions.EXPECT().Resolve(mock.Anything, hash).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Resolve(s.T().Context(), "raw-token")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestResolveRejectsMalformedTokenWithoutStorage() {
|
||||
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
|
||||
|
||||
_, err := s.service.Resolve(s.T().Context(), "garbage")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateGeneratesTokenAndReturnsIt() {
|
||||
hash := []byte("hashed-token")
|
||||
expiresAt := time.Now().Add(s.ttl)
|
||||
|
||||
s.tokens.EXPECT().Generate().Return("raw-token", hash, nil).Once()
|
||||
s.sessions.EXPECT().
|
||||
Create(mock.Anything, mock.MatchedBy(func(candidate domain.NewSession) bool {
|
||||
return bytes.Equal(candidate.TokenHash, hash) &&
|
||||
candidate.UserID == s.user.ID &&
|
||||
candidate.ExpiresAt.After(time.Now())
|
||||
})).
|
||||
Return(domain.Session{ExpiresAt: expiresAt}, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Create(s.T().Context(), s.user)
|
||||
s.Require().NoError(err)
|
||||
s.Equal("raw-token", got.Token)
|
||||
s.Equal(s.user, got.User)
|
||||
s.Equal(expiresAt, got.ExpiresAt)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreatePropagatesTokenGenerationError() {
|
||||
s.tokens.EXPECT().Generate().Return("", nil, errors.New("no entropy")).Once()
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), s.user)
|
||||
s.Require().Error(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRevokeHashesTokenBeforeStorage() {
|
||||
hash := []byte("hashed-token")
|
||||
userID := uuid.New()
|
||||
|
||||
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
|
||||
s.sessions.EXPECT().Revoke(mock.Anything, userID, hash).Return(nil).Once()
|
||||
|
||||
s.Require().NoError(s.service.Revoke(s.T().Context(), userID, "raw-token"))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRevokeRejectsMalformedToken() {
|
||||
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
|
||||
|
||||
err := s.service.Revoke(s.T().Context(), uuid.New(), "garbage")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticateVerifiesPassword() {
|
||||
hash, err := password.Hash("secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticateRejectsWrongPassword() {
|
||||
hash, err := password.Hash("secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
|
||||
Once()
|
||||
|
||||
_, err = s.service.Authenticate(s.T().Context(), "alice", "wrong-password-value")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticatePropagatesUnknownUser() {
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "nobody").
|
||||
Return(domain.UserCredentials{}, domain.ErrUnauthenticated).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Authenticate(s.T().Context(), "nobody", "secret-password-123")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.UserDraft) (domain.User, error) {
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.NewUser) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
@@ -58,15 +58,15 @@ func (_mock *MockRepository) Create(ctx context.Context, draft domain.UserDraft)
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.UserDraft) (domain.User, error)); ok {
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.UserDraft) domain.User); ok {
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) domain.User); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.UserDraft) error); ok {
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewUser) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
@@ -81,20 +81,20 @@ type MockRepository_Create_Call struct {
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.UserDraft
|
||||
// - draft domain.NewUser
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.UserDraft)) *MockRepository_Create_Call {
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.NewUser)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.UserDraft
|
||||
var arg1 domain.NewUser
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.UserDraft)
|
||||
arg1 = args[1].(domain.NewUser)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
@@ -109,7 +109,7 @@ func (_c *MockRepository_Create_Call) Return(user domain.User, err error) *MockR
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.UserDraft) (domain.User, error)) *MockRepository_Create_Call {
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.NewUser) (domain.User, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
@@ -7,12 +7,11 @@ import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
//go:generate go tool mockery
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.UserDraft) (domain.User, error)
|
||||
Create(ctx context.Context, draft domain.NewUser) (domain.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||
}
|
||||
|
||||
@@ -29,7 +28,16 @@ func (s *Service) Register(ctx context.Context, draft domain.UserDraft) (domain.
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
user, err := s.users.Create(ctx, draft)
|
||||
hash, err := password.Hash(draft.Password)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
|
||||
user, err := s.users.Create(ctx, domain.NewUser{
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
PasswordHash: hash,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
@@ -34,8 +35,8 @@ func (s *ServiceSuite) SetupTest() {
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterReturnsStoredUser() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса"}
|
||||
func (s *ServiceSuite) TestRegisterHashesPasswordAndReturnsStoredUser() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
|
||||
stored := domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: draft.Username,
|
||||
@@ -43,7 +44,15 @@ func (s *ServiceSuite) TestRegisterReturnsStoredUser() {
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.users.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
s.users.EXPECT().
|
||||
Create(s.T().Context(), mock.MatchedBy(func(candidate domain.NewUser) bool {
|
||||
return candidate.Username == draft.Username &&
|
||||
candidate.DisplayName == draft.DisplayName &&
|
||||
candidate.PasswordHash != "" &&
|
||||
candidate.PasswordHash != draft.Password
|
||||
})).
|
||||
Return(stored, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
@@ -51,16 +60,26 @@ func (s *ServiceSuite) TestRegisterReturnsStoredUser() {
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterRejectsBlankDisplayNameWithoutRepositoryCall() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: " "}
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: " ", Password: "very-secret-password"}
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterRejectsShortPasswordWithoutRepositoryCall() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterPropagatesUsernameConflict() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса"}
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
|
||||
|
||||
s.users.EXPECT().Create(s.T().Context(), draft).Return(domain.User{}, domain.ErrUsernameTaken).Once()
|
||||
s.users.EXPECT().
|
||||
Create(s.T().Context(), mock.Anything).
|
||||
Return(domain.User{}, domain.ErrUsernameTaken).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
|
||||
|
||||
Reference in New Issue
Block a user