password_test.go49 lines, 1.4 KB
| 1 | package auth_test |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | "testing" |
| 6 | |
| 7 | "github.com/fiston-user/payments/internal/auth" |
| 8 | ) |
| 9 | |
| 10 | const password = "correct horse battery staple" |
| 11 | |
| 12 | func TestPassword(t *testing.T) { |
| 13 | t.Parallel() |
| 14 | hash, err := auth.HashPassword(t.Context(), password) |
| 15 | if err != nil { |
| 16 | t.Fatalf("hash: %v", err) |
| 17 | } |
| 18 | if !strings.HasPrefix(hash, "$argon2id$v=19$m=65536,t=3,p=4$") { |
| 19 | t.Errorf("hash = %s, want a PHC string with the default params", hash) |
| 20 | } |
| 21 | // The same password again: a new salt, so a different hash. |
| 22 | again, err := auth.HashPassword(t.Context(), password) |
| 23 | if err != nil || again == hash { |
| 24 | t.Fatalf("second hash = %s, %v: want a different hash", again, err) |
| 25 | } |
| 26 | |
| 27 | tests := []struct { |
| 28 | name, password, hash string |
| 29 | match bool |
| 30 | }{ |
| 31 | {"right password", password, hash, true}, |
| 32 | {"right password, other salt", password, again, true}, |
| 33 | {"one letter more", password + "s", hash, false}, |
| 34 | {"other case", strings.ToUpper(password), hash, false}, |
| 35 | {"empty", "", hash, false}, |
| 36 | } |
| 37 | for _, tt := range tests { |
| 38 | t.Run(tt.name, func(t *testing.T) { |
| 39 | match, err := auth.VerifyPassword(t.Context(), tt.password, tt.hash) |
| 40 | if err != nil || match != tt.match { |
| 41 | t.Errorf("match = %t, %v; want %t", match, err, tt.match) |
| 42 | } |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | if _, err := auth.VerifyPassword(t.Context(), password, "$2a$10$notargon"); err == nil { |
| 47 | t.Error("a hash in another format verified without an error") |
| 48 | } |
| 49 | } |