This commit is contained in:
2025-03-11 21:48:05 +02:00
parent 6661fdf89b
commit 5fe09f0a2f
6 changed files with 224 additions and 7 deletions

View File

@@ -1,7 +1,21 @@
package auth
import (
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"net/http"
"strings"
"time"
)
type TokenType string
const (
// TokenTypeAccess -
TokenTypeAccess TokenType = "chirpy-access"
)
func HashPassword(password string) (string, error) {
@@ -12,3 +26,61 @@ func HashPassword(password string) (string, error) {
func CheckPasswordHash(password, hash string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}
// MakeJWT -
func MakeJWT(
userID uuid.UUID,
tokenSecret string,
expiresIn time.Duration,
) (string, error) {
signingKey := []byte(tokenSecret)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
Issuer: string(TokenTypeAccess),
IssuedAt: jwt.NewNumericDate(time.Now().UTC()),
ExpiresAt: jwt.NewNumericDate(time.Now().UTC().Add(expiresIn)),
Subject: userID.String(),
})
return token.SignedString(signingKey)
}
// ValidateJWT -
func ValidateJWT(tokenString, tokenSecret string) (uuid.UUID, error) {
claimsStruct := jwt.RegisteredClaims{}
token, err := jwt.ParseWithClaims(
tokenString,
&claimsStruct,
func(token *jwt.Token) (interface{}, error) { return []byte(tokenSecret), nil },
)
if err != nil {
return uuid.Nil, err
}
userIDString, err := token.Claims.GetSubject()
if err != nil {
return uuid.Nil, err
}
issuer, err := token.Claims.GetIssuer()
if err != nil {
return uuid.Nil, err
}
if issuer != string(TokenTypeAccess) {
return uuid.Nil, errors.New("invalid issuer")
}
id, err := uuid.Parse(userIDString)
if err != nil {
return uuid.Nil, fmt.Errorf("invalid user ID: %w", err)
}
return id, nil
}
func GetBearerToken(headers http.Header) (string, error) {
auth := headers.Get("Authorization")
auth = strings.TrimPrefix(auth, "Bearer ")
if auth == "" {
return "", errors.New("missing Authorization header")
}
return auth, nil
}

110
internal/auth/auth_test.go Normal file
View File

@@ -0,0 +1,110 @@
package auth
import (
"github.com/google/uuid"
"testing"
"time"
)
func TestCheckPasswordHash(t *testing.T) {
// First, we need to create some hashed passwords for testing
password1 := "correctPassword123!"
password2 := "anotherPassword456!"
hash1, _ := HashPassword(password1)
hash2, _ := HashPassword(password2)
tests := []struct {
name string
password string
hash string
wantErr bool
}{
{
name: "Correct password",
password: password1,
hash: hash1,
wantErr: false,
},
{
name: "Incorrect password",
password: "wrongPassword",
hash: hash1,
wantErr: true,
},
{
name: "Password doesn't match different hash",
password: password1,
hash: hash2,
wantErr: true,
},
{
name: "Empty password",
password: "",
hash: hash1,
wantErr: true,
},
{
name: "Invalid hash",
password: password1,
hash: "invalidhash",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := CheckPasswordHash(tt.password, tt.hash)
if (err != nil) != tt.wantErr {
t.Errorf("CheckPasswordHash() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestValidateJWT(t *testing.T) {
userID := uuid.New()
validToken, _ := MakeJWT(userID, "secret", time.Hour)
tests := []struct {
name string
tokenString string
tokenSecret string
wantUserID uuid.UUID
wantErr bool
}{
{
name: "Valid token",
tokenString: validToken,
tokenSecret: "secret",
wantUserID: userID,
wantErr: false,
},
{
name: "Invalid token",
tokenString: "invalid.token.string",
tokenSecret: "secret",
wantUserID: uuid.Nil,
wantErr: true,
},
{
name: "Wrong secret",
tokenString: validToken,
tokenSecret: "wrong_secret",
wantUserID: uuid.Nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotUserID, err := ValidateJWT(tt.tokenString, tt.tokenSecret)
if (err != nil) != tt.wantErr {
t.Errorf("ValidateJWT() error = %v, wantErr %v", err, tt.wantErr)
return
}
if gotUserID != tt.wantUserID {
t.Errorf("ValidateJWT() gotUserID = %v, want %v", gotUserID, tt.wantUserID)
}
})
}
}

View File

@@ -19,3 +19,11 @@ type User struct {
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
}
type UserWithToken struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
Token string `json:"token"`
}