Skip to content

Commit 6de806c

Browse files
committed
Add tests for jwt and password
1 parent 40c81dd commit 6de806c

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

internal/auth/jwt_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package auth
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/golang-jwt/jwt/v5"
8+
)
9+
10+
func TestGenerateJWTAndCheckJWT(t *testing.T) {
11+
tokenString, err := GenerateJWT("bob")
12+
if err != nil {
13+
t.Fatalf("Error generating JWT %v", err)
14+
}
15+
16+
token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
17+
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
18+
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
19+
}
20+
return []byte("secret_key"), nil
21+
})
22+
23+
if err != nil {
24+
t.Fatalf("Error parsing token %v", err)
25+
}
26+
27+
claims, ok := token.Claims.(*MyClaims)
28+
if !ok || !token.Valid {
29+
t.Fatalf("Error validating token: %v", err)
30+
}
31+
32+
if claims.Username != "bob" {
33+
t.Fatalf("Invalid username in claims: %s", claims.Username)
34+
}
35+
}

internal/auth/password_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package auth
2+
3+
import "testing"
4+
5+
func TestHashPasswordAndCheckPasswordHash(t *testing.T) {
6+
password := "password"
7+
8+
hashed, err := HashPassword(password)
9+
if err != nil {
10+
t.Fatalf("Failed to hash password: %v", err)
11+
}
12+
if !CheckPasswordHash(password, hashed) {
13+
t.Fatalf("Hashed password does not match")
14+
}
15+
}

0 commit comments

Comments
 (0)