security

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package security provides HTTP security middleware, authentication, and rate limiting backed by a database.

security.New(
    security.WithNonce(),
    security.WithHeaders(),
    security.WithRateLimit(db, 100, 60),
)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidToken = errors.New("invalid token")
	ErrExpiredToken = errors.New("token expired")
)

Functions

func CheckPassword

func CheckPassword(hash, password string) bool

CheckPassword compares a bcrypt hash with a plaintext password. Returns true if they match.

func ClearSessionCookie

func ClearSessionCookie(w http.ResponseWriter, name string)

ClearSessionCookie removes a session cookie.

func ClientIP

func ClientIP(r *http.Request) string

ClientIP extracts the client IP from a request, respecting X-Forwarded-For.

func CreateToken

func CreateToken(claims map[string]any, secret string, expiry time.Duration) (string, error)

CreateToken creates an HS256 JWT with the given claims, secret, and expiry.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword hashes a password with bcrypt.

func New

func New(opts ...Option) func(http.Handler) http.Handler

New creates a security policy middleware from functional options. The returned middleware composes all enabled features into one handler.

func NonceFrom

func NonceFrom(ctx context.Context) string

NonceFrom returns the per-request nonce, or empty string if none.

func SessionFromRequest

func SessionFromRequest(r *http.Request, name string) string

SessionFromRequest extracts a session cookie value from the request. Returns empty string if not found.

func SetSessionCookie

func SetSessionCookie(w http.ResponseWriter, name, token string, expiry time.Duration)

SetSessionCookie sets a secure session cookie with the given token.

func ValidateToken

func ValidateToken(token, secret string) (map[string]any, error)

ValidateToken validates an HS256 JWT and returns its claims.

Types

type Option

type Option func(*Policy)

Option configures a security policy.

func WithHeaders

func WithHeaders() Option

WithHeaders enables security response headers (CSP, X-Frame-Options, etc).

func WithNonce

func WithNonce() Option

WithNonce enables per-request CSP nonce generation.

func WithRateLimit

func WithRateLimit(db *database.Database, n, windowSeconds int) Option

WithRateLimit enables IP-based rate limiting backed by a database. n is the max requests per window. windowSeconds is the time period.

type Policy

type Policy struct {
	// contains filtered or unexported fields
}

Policy composes security middleware into a single handler chain.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL