package service_test import ( "context" "log/slog" "testing" "gitea.michaelthomson.dev/mthomson/habits/internal/auth" authservice "gitea.michaelthomson.dev/mthomson/habits/internal/auth/service" "gitea.michaelthomson.dev/mthomson/habits/internal/test" "gitea.michaelthomson.dev/mthomson/habits/internal/user/repository" userservice "gitea.michaelthomson.dev/mthomson/habits/internal/user/service" "github.com/gofrs/uuid/v5" ) func TestLogin(t *testing.T) { t.Parallel() ctx := context.Background() logger := slog.Default() tdb := test.NewTestDatabase(t) defer tdb.TearDown() userRepository := repository.NewUserRepository(logger, tdb.Db) argon2IdHash := auth.NewArgon2IdHash(1, 32, 64*1024, 32, 256) userService := userservice.NewUserService(logger, userRepository, argon2IdHash) authService := authservice.NewAuthService(logger, []byte("secretkey"), userRepository, argon2IdHash) _, err := userService.Register(ctx, "test@test.com", "supersecurepassword") AssertNoError(t, err) t.Run("login existing user with correct credentials", func(t *testing.T) { want, err := authService.CreateToken(ctx, "test@test.com") AssertNoError(t, err) got, err := authService.Login(ctx, "test@test.com", "supersecurepassword") AssertNoError(t, err) AssertTokens(t, got, want) }) t.Run("login existing user with incorrect credentials", func(t *testing.T) { _, err := authService.Login(ctx, "test@test.com", "superwrongpassword") AssertErrors(t, err, authservice.ErrUnauthorized) }) t.Run("login nonexistant user", func(t *testing.T) { _, err := authService.Login(ctx, "foo@test.com", "supersecurepassword") AssertErrors(t, err, authservice.ErrNotFound) }) } func AssertErrors(t testing.TB, got, want error) { t.Helper() if got != want { t.Errorf("got error: %v, want error: %v", want, got) } } func AssertNoError(t testing.TB, err error) { t.Helper() if err != nil { t.Errorf("expected no error, got %v", err) } } func AssertTokens(t testing.TB, got, want string) { t.Helper() if got != want { t.Errorf("expected matching tokens, got %q, want %q", got, want) } } func NewUUID(t testing.TB) uuid.UUID { t.Helper() uuid, err := uuid.NewV4() if err != nil { t.Errorf("error generation uuid: %v", err) } return uuid }