edge/pkg/module/auth/module.go

70 lines
1.5 KiB
Go
Raw Normal View History

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