forked from mtusi2026/mtusi2026lab7
60 lines
2.0 KiB
Go
60 lines
2.0 KiB
Go
package chat_test
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
type recordedSessions struct{ value domain.Session }
|
|
|
|
func (s *recordedSessions) Put(_ context.Context, _ string, value domain.Session) error {
|
|
s.value = value
|
|
return nil
|
|
}
|
|
func (*recordedSessions) Get(context.Context, string) (domain.Session, bool, error) {
|
|
return domain.Session{}, false, nil
|
|
}
|
|
func (*recordedSessions) Delete(context.Context, string) (bool, error) { return false, nil }
|
|
func (*recordedSessions) Ready(context.Context) error { return nil }
|
|
|
|
func TestPasswordUpgradeOnSuccessfulLogin(t *testing.T) {
|
|
ctx := context.Background()
|
|
repo := repository.NewMemory()
|
|
sessions := &recordedSessions{}
|
|
useCase := chat.New(repo, sessions, time.Minute)
|
|
const secret = "synthetic-legacy-password"
|
|
legacy, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.MinCost)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
user, err := repo.CreateUser(ctx, "legacy", "Legacy", string(legacy))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if _, err := useCase.CreateSession(ctx, user.Username, "synthetic-wrong-password"); err == nil {
|
|
t.Fatal("wrong password accepted")
|
|
}
|
|
if _, hash, _, _ := repo.UserByUsername(ctx, user.Username); hash != string(legacy) {
|
|
t.Fatal("failed login changed hash")
|
|
}
|
|
login, err := useCase.CreateSession(ctx, user.Username, secret)
|
|
if err != nil || login.Token == "" || sessions.value.UserID != user.ID {
|
|
t.Fatal("legacy login failed")
|
|
}
|
|
_, hash, _, _ := repo.UserByUsername(ctx, user.Username)
|
|
if password.NeedsRehash(hash) {
|
|
t.Fatal("successful login did not upgrade hash")
|
|
}
|
|
if ok, err := password.Verify(ctx, secret, hash); err != nil || !ok {
|
|
t.Fatal("replacement hash rejects original password")
|
|
}
|
|
}
|