user_test.go
·
76 строк
·
2.2 KB
| 1 | package user |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "path/filepath" |
| 7 | "testing" |
| 8 | |
| 9 | "polar/internal/db" |
| 10 | ) |
| 11 | |
| 12 | func TestValidateUsername(t *testing.T) { |
| 13 | valid := []string{"alice", "rin", "dev_01", "git-user-99", "ab"} |
| 14 | for _, u := range valid { |
| 15 | if err := ValidateUsername(u); err != nil { |
| 16 | t.Errorf("expected username %q to be valid, got %v", u, err) |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | invalid := []string{ |
| 21 | "", "a", "-alice", "alice-", "alice..dev", "../etc", "foo/bar", |
| 22 | `foo\bar`, "repo.git", "admin", "login", "register", "settings", |
| 23 | "_ui", "healthz", "explore", "alice--user", |
| 24 | } |
| 25 | for _, u := range invalid { |
| 26 | if err := ValidateUsername(u); err == nil { |
| 27 | t.Errorf("expected username %q to be rejected", u) |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func TestFirstUserAdminAndRegistrationToggle(t *testing.T) { |
| 33 | ctx := context.Background() |
| 34 | database, err := db.Open(ctx, filepath.Join(t.TempDir(), "users.db"), true) |
| 35 | if err != nil { |
| 36 | t.Fatalf("open db: %v", err) |
| 37 | } |
| 38 | defer database.Close() |
| 39 | |
| 40 | svc := NewService(database) |
| 41 | |
| 42 | // First user becomes admin even if regEnabled is false |
| 43 | first, err := svc.Register(ctx, "alice", "alice@example.com", "supersecret123", false) |
| 44 | if err != nil { |
| 45 | t.Fatalf("Register first user failed: %v", err) |
| 46 | } |
| 47 | if !first.IsAdmin { |
| 48 | t.Fatalf("expected first registered user to be admin") |
| 49 | } |
| 50 | |
| 51 | // Second user when regEnabled is false must fail |
| 52 | _, err = svc.Register(ctx, "bob", "bob@example.com", "supersecret123", false) |
| 53 | if !errors.Is(err, ErrRegistrationDisabled) { |
| 54 | t.Fatalf("expected ErrRegistrationDisabled, got %v", err) |
| 55 | } |
| 56 | |
| 57 | // Second user when regEnabled is true succeeds and is NOT admin |
| 58 | second, err := svc.Register(ctx, "bob", "bob@example.com", "supersecret123", true) |
| 59 | if err != nil { |
| 60 | t.Fatalf("Register second user failed: %v", err) |
| 61 | } |
| 62 | if second.IsAdmin { |
| 63 | t.Fatalf("expected second user NOT to be admin") |
| 64 | } |
| 65 | |
| 66 | // Authenticate by username and email |
| 67 | if _, err := svc.Authenticate(ctx, "alice", "supersecret123"); err != nil { |
| 68 | t.Fatalf("Authenticate by username failed: %v", err) |
| 69 | } |
| 70 | if _, err := svc.Authenticate(ctx, "ALICE@example.com", "supersecret123"); err != nil { |
| 71 | t.Fatalf("Authenticate by email failed: %v", err) |
| 72 | } |
| 73 | if _, err := svc.Authenticate(ctx, "alice", "wrongpassword"); err == nil { |
| 74 | t.Fatalf("expected error for wrong password") |
| 75 | } |
| 76 | } |
| 77 |