docs: document auth helpers and expand README
Add godoc comments to the exported auth package helpers. Expand the README with feature and tech stack overviews, setup instructions, an API reference, and make targets for development workflows.
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
// Package auth provides password hashing, JWT, and token helpers used to
|
||||
// authenticate and authorize API requests.
|
||||
package auth
|
||||
|
||||
import (
|
||||
@@ -13,14 +15,18 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// HashPassword hashes a plaintext password using argon2id.
|
||||
func HashPassword(password string) (string, error) {
|
||||
return argon2id.CreateHash(password, argon2id.DefaultParams)
|
||||
}
|
||||
|
||||
// CheckPasswordHash reports whether password matches the given argon2id hash.
|
||||
func CheckPasswordHash(password string, hash string) (bool, error) {
|
||||
return argon2id.ComparePasswordAndHash(password, hash)
|
||||
}
|
||||
|
||||
// MakeJWT creates a signed HS256 JWT for the given user that expires after
|
||||
// expiresIn.
|
||||
func MakeJWT(userID uuid.UUID, tokenSecret []byte, expiresIn time.Duration) (string, error) {
|
||||
token := jwt.New(jwt.GetSigningMethod(jwt.SigningMethodHS256.Name))
|
||||
|
||||
@@ -34,6 +40,7 @@ func MakeJWT(userID uuid.UUID, tokenSecret []byte, expiresIn time.Duration) (str
|
||||
return token.SignedString(tokenSecret)
|
||||
}
|
||||
|
||||
// ValidateJWT verifies the token signature and returns the subject's user ID.
|
||||
func ValidateJWT(tokenString string, tokenSecret []byte) (uuid.UUID, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &jwt.RegisteredClaims{}, func(t *jwt.Token) (any, error) {
|
||||
return tokenSecret, nil
|
||||
@@ -58,6 +65,7 @@ func ValidateJWT(tokenString string, tokenSecret []byte) (uuid.UUID, error) {
|
||||
return validUserId, nil
|
||||
}
|
||||
|
||||
// GetBearerToken extracts the "Bearer" token from the Authorization header.
|
||||
func GetBearerToken(headers http.Header) (string, error) {
|
||||
authorizationHeader := headers.Get("Authorization")
|
||||
|
||||
@@ -70,6 +78,8 @@ func GetBearerToken(headers http.Header) (string, error) {
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// GetAPIKey extracts the API key from the Authorization header using the
|
||||
// "ApiKey" scheme.
|
||||
func GetAPIKey(headers http.Header) (string, error) {
|
||||
authorizationHeader := headers.Get("Authorization")
|
||||
|
||||
@@ -82,6 +92,8 @@ func GetAPIKey(headers http.Header) (string, error) {
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
// MakeRefreshToken generates a cryptographically random, hex-encoded refresh
|
||||
// token.
|
||||
func MakeRefreshToken() string {
|
||||
bytes := make([]byte, 32)
|
||||
rand.Read(bytes)
|
||||
|
||||
Reference in New Issue
Block a user