package auth import ( "net/http" "forge.cadoles.com/arcad/edge/pkg/app" edgeHTTP "forge.cadoles.com/arcad/edge/pkg/http" "forge.cadoles.com/arcad/edge/pkg/module/util" "github.com/dop251/goja" "github.com/pkg/errors" ) const ( ClaimSubject = "sub" ) type Module struct { server *app.Server getClaimFunc GetClaimFunc } func (m *Module) Name() string { return "auth" } func (m *Module) Export(export *goja.Object) { if err := export.Set("getClaim", m.getClaim); err != nil { panic(errors.Wrap(err, "could not set 'getClaim' function")) } if err := export.Set("CLAIM_SUBJECT", ClaimSubject); err != nil { panic(errors.Wrap(err, "could not set 'CLAIM_SUBJECT' property")) } } func (m *Module) getClaim(call goja.FunctionCall, rt *goja.Runtime) goja.Value { ctx := util.AssertContext(call.Argument(0), rt) claimName := util.AssertString(call.Argument(1), rt) req, ok := ctx.Value(edgeHTTP.ContextKeyOriginRequest).(*http.Request) if !ok { panic(rt.ToValue(errors.New("could not find http request in context"))) } claim, err := m.getClaimFunc(ctx, req, claimName) if err != nil { if errors.Is(err, ErrUnauthenticated) || errors.Is(err, ErrClaimNotFound) { return nil } panic(rt.ToValue(errors.WithStack(err))) } return rt.ToValue(claim) } func ModuleFactory(funcs ...OptionFunc) app.ServerModuleFactory { opt := defaultOptions() for _, fn := range funcs { fn(opt) } return func(server *app.Server) app.ServerModule { return &Module{ server: server, getClaimFunc: opt.GetClaim, } } }