This commit is contained in:
Daniel 2024-08-04 08:55:12 -04:00
parent aff226940f
commit 8742029109
5 changed files with 32 additions and 14 deletions

View file

@ -1,6 +1,12 @@
db:
driver: pgx
connect: 'postgres://postgres:password@localhost:5432/example'
jwtsecret: 'super secret string'
auth:
jwtsecret: 'super secret string'
# this is the JWT cookie domain
domain: example.com
# this allows the JWT cookie to be served over plain HTTP only for these Host: header values
allowInsecureFor:
"localhost:3050": true
listen: ':3050'
public: true

View file

@ -4,6 +4,7 @@ import (
"errors"
"net/http"
"dynatron.me/x/stillbox/pkg/gordio/config"
"github.com/go-chi/jwtauth/v5"
)
@ -28,13 +29,14 @@ type Authenticator interface {
type authenticator struct {
domain string
jwt *jwtauth.JWTAuth
cfg *config.Auth
}
// NewAuthenticator creates a new Authenticator with the provided JWT secret and cookie domain.
func NewAuthenticator(jwtSecret string, domain string) Authenticator {
// NewAuthenticator creates a new Authenticator with the provided config.
func NewAuthenticator(cfg *config.Auth) Authenticator {
return &authenticator{
domain: domain,
jwt: jwtauth.New("HS256", []byte(jwtSecret), nil),
domain: cfg.Domain,
jwt: jwtauth.New("HS256", []byte(cfg.JWTSecret), nil),
}
}

View file

@ -3,7 +3,6 @@ package auth
import (
"context"
"net/http"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
@ -94,6 +93,11 @@ func (a *authenticator) PublicRoutes(r chi.Router) {
r.Post("/login", a.routeAuth)
}
func (a *authenticator) allowInsecureCookie(r *http.Request) bool {
v, has := a.cfg.AllowInsecure[r.Host]
return has && v == true
}
func (a *authenticator) routeAuth(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
@ -115,7 +119,7 @@ func (a *authenticator) routeAuth(w http.ResponseWriter, r *http.Request) {
Name: "jwt",
Value: tok,
HttpOnly: true,
Secure: !strings.HasPrefix(r.Host, "localhost:"),
Secure: a.allowInsecureCookie(r),
Domain: a.domain,
})

View file

@ -1,22 +1,28 @@
package config
import (
"os"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"os"
)
type Config struct {
DB DB `yaml:"db"`
JWTSecret string `yaml:"jwtsecret"`
Auth Auth `yaml:"auth"`
Listen string `yaml:"listen"`
Public bool `yaml:"public"`
Domain string `yaml:"domain"`
configPath string
}
type Auth struct {
JWTSecret string `yaml:"jwtsecret"`
Domain string `yaml:"domain"`
AllowInsecure map[string]bool `yaml:"allowInsecureFor"`
}
type DB struct {
Connect string `yaml:"connect"`
Driver string `yaml:"driver"`

View file

@ -30,7 +30,7 @@ func New(cfg *config.Config) (*Server, error) {
}
r := chi.NewRouter()
authenticator := auth.NewAuthenticator(cfg.JWTSecret, cfg.Domain)
authenticator := auth.NewAuthenticator(&cfg.Auth)
srv := &Server{
auth: authenticator,
conf: cfg,