diff options
| author | mo khan <mo@mokhan.ca> | 2025-03-15 15:20:53 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-03-15 15:20:53 -0600 |
| commit | b27894fcfee8a8422ca191ccd87f641eb8befcf0 (patch) | |
| tree | 503b19478f05ca2433082a3c9838e0c6ae401772 /pkg/app/app.go | |
| parent | 80f1b83544b3482cbcdab8cdf521a92f2afdfa16 (diff) | |
refactor: authorize unsigned JWT in requests
Diffstat (limited to 'pkg/app/app.go')
| -rw-r--r-- | pkg/app/app.go | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/pkg/app/app.go b/pkg/app/app.go new file mode 100644 index 0000000..fd6a3f1 --- /dev/null +++ b/pkg/app/app.go @@ -0,0 +1,44 @@ +package app + +import ( + "fmt" + "net" + "net/http" + + "github.com/casbin/casbin/v3" + "github.com/xlgmokha/x/pkg/x" + "gitlab.com/mokhax/spike/pkg/authz" + "gitlab.com/mokhax/spike/pkg/cfg" + "gitlab.com/mokhax/spike/pkg/srv" +) + +func WithCasbin() authz.Authorizer { + enforcer := x.Must(casbin.NewEnforcer("model.conf", "policy.csv")) + + return authz.AuthorizerFunc(func(r *http.Request) bool { + host, _, err := net.SplitHostPort(r.Host) + if err != nil { + return false + } + + subject, found := authz.TokenFrom(r).Subject() + if !found { + subject = "*" + } + ok, err := enforcer.Enforce(subject, host, r.Method, r.URL.Path) + if err != nil { + fmt.Printf("%v\n", err) + return false + } + + fmt.Printf("%v: %v -> %v %v%v\n", ok, subject, r.Method, host, r.URL.Path) + return ok + }) +} + +func Start(bindAddr string) error { + return srv.Run(cfg.New( + bindAddr, + cfg.WithMux(authz.HTTP(WithCasbin(), Routes())), + )) +} |
