package db import ( "context" "os" "testing" "time" "code.lila.network/adoralaura/go-urlsh/internal/config" "code.lila.network/adoralaura/go-urlsh/models" "github.com/rs/zerolog" "github.com/uptrace/bun" ) // createTestingUser creates the necessary testing users for testing MFA. func createTestingUser(t *testing.T, db *bun.DB, user *models.User) { mfaconfig := models.MFAConfig{ UserName: user.UserName, TOTPSecret: "abcd", ExpiresAt: time.Now().Add(5 * time.Minute), Active: false, } _, err := db.NewInsert().Model(user).Exec(context.Background()) if err != nil { t.Fatalf("Couldn't insert test user into DB: %q\n", err) } _, err = db.NewInsert().Model(&mfaconfig).Exec(context.Background()) if err != nil { t.Fatalf("Couldn't insert test mfa config into DB: %q\n", err) } } // removeTestingUser is used as deferred cleanup in multifactor tests. // It removes models.User and models.MFAConfig with given username from DB. func removeTestingUser(t *testing.T, db *bun.DB, username string) { _, err := db.NewInsert().Model((*models.User)(nil)). Where("username = ?", username).Exec(context.Background()) if err != nil { t.Fatalf("Couldn't remove test user %q from DB: %q\n", username, err) } _, err = db.NewInsert().Model((*models.MFAConfig)(nil)). Where("username = ?", username).Exec(context.Background()) if err != nil { t.Fatalf("Couldn't remove test mfa config for %q from DB: %q\n", username, err) } } func TestUserHasFailedMFAAttemptTrue(t *testing.T) { cfgfile := os.Getenv("GOURLSH_TEST_CONFIGFILE") logger := config.NewLogger(zerolog.InfoLevel) cfg := config.NewConfig(cfgfile) // setup test environment testdb := InitializeDB(cfg, logger) testUserName := "test_mfafailedtrue" mfauser := models.User{ UserName: testUserName, Created: time.Now(), } createTestingUser(t, testdb, &mfauser) defer removeTestingUser(t, testdb, testUserName) answer, err := UserHasFailedMFAAttempt(mfauser) if err != nil { t.Fatalf("Error running UserHasFailedMFAAttempt in tests: %q\n", err) } if answer == false { t.Fatalf("db.UserHasFailedMFAAttempt() = false, want true") } } func TestUserHasFailedMFAAttemptFalse(t *testing.T) { cfgfile := os.Getenv("GOURLSH_TEST_CONFIGFILE") cfg := config.NewConfig(cfgfile) logger := config.NewLogger(zerolog.InfoLevel) // setup test environment testdb := InitializeDB(cfg, logger) testUserName := "test_mfafailed" mfauser := models.User{ UserName: testUserName, Created: time.Now(), } createTestingUser(t, testdb, &mfauser) defer removeTestingUser(t, testdb, testUserName) answer, err := UserHasFailedMFAAttempt(mfauser) if err != nil { t.Fatalf("Error running UserHasFailedMFAAttempt in tests: %q\n", err) } if answer == true { t.Fatalf("db.UserHasFailedMFAAttempt() = true, want false") } } func TestGenerateNewScratchcodes(t *testing.T) { }