Use jo-micro/components
continuous-integration/drone/tag Build is passing Details

main v0.4.0
René Jochum 1 year ago
parent f6178c1c4c
commit 5a35566a37
Signed by: jochum
GPG Key ID: F7D906F5E51E8E5E

@ -5,6 +5,6 @@ var (
)
const (
Name = "go.micro.auth"
Name = "jo.micro.auth"
PkgPath = "jochum.dev/jo-micro/auth2"
)

@ -4,12 +4,12 @@ import (
"context"
"fmt"
"jochum.dev/jo-micro/auth2/internal/ibun"
"jochum.dev/jo-micro/buncomponent"
)
func RoleGetId(ctx context.Context, name string) (string, error) {
var result string
err := ibun.Bun.NewSelect().Table("roles").Column("id").Limit(1).Where("name = ?", name).Scan(ctx, &result)
err := buncomponent.Must(ctx).Bun().NewSelect().Table("roles").Column("id").Limit(1).Where("name = ?", name).Scan(ctx, &result)
if err != nil || len(result) < 1 {
return "", fmt.Errorf("role '%s' not found", name)
}

@ -7,7 +7,7 @@ import (
"github.com/google/uuid"
"github.com/uptrace/bun"
"jochum.dev/jo-micro/auth2/internal/ibun"
"jochum.dev/jo-micro/buncomponent"
)
type User struct {
@ -29,7 +29,7 @@ type User struct {
func UserList(ctx context.Context, limit, offset uint64) ([]User, error) {
// Get the data from the db.
var users []User
err := ibun.Bun.NewSelect().
err := buncomponent.Must(ctx).Bun().NewSelect().
Model(&users).
ColumnExpr("u.*").
ColumnExpr("array(SELECT r.name FROM users_roles AS ur LEFT JOIN roles AS r ON ur.role_id = r.id WHERE ur.user_id = u.id) AS roles").
@ -44,7 +44,7 @@ func UserList(ctx context.Context, limit, offset uint64) ([]User, error) {
func UserDetail(ctx context.Context, id string) (*User, error) {
user := User{}
err := ibun.Bun.NewSelect().
err := buncomponent.Must(ctx).Bun().NewSelect().
Model(&user).
ColumnExpr("u.*").
ColumnExpr("array(SELECT r.name FROM users_roles AS ur LEFT JOIN roles AS r ON ur.role_id = r.id WHERE ur.user_id = u.id) AS roles").
@ -61,7 +61,7 @@ func UserDetail(ctx context.Context, id string) (*User, error) {
func UserDelete(ctx context.Context, id string) error {
user := User{}
_, err := ibun.Bun.NewDelete().Model(&user).Where("id = ?", id).Exec(ctx)
_, err := buncomponent.Must(ctx).Bun().NewDelete().Model(&user).Where("id = ?", id).Exec(ctx)
return err
}
@ -77,7 +77,7 @@ func UserUpdateRoles(ctx context.Context, id string, roles []string) (*User, err
}
// Delete all current roles
_, err := ibun.Bun.NewDelete().Table("users_roles").Where("user_id = ?", id).Exec(ctx)
_, err := buncomponent.Must(ctx).Bun().NewDelete().Table("users_roles").Where("user_id = ?", id).Exec(ctx)
if err != nil {
return nil, err
}
@ -93,7 +93,7 @@ func UserUpdateRoles(ctx context.Context, id string, roles []string) (*User, err
"user_id": id,
"role_id": roleId,
}
_, err = ibun.Bun.NewInsert().Model(&values).TableExpr("users_roles").Exec(ctx)
_, err = buncomponent.Must(ctx).Bun().NewInsert().Model(&values).TableExpr("users_roles").Exec(ctx)
if err != nil {
return nil, err
}
@ -104,7 +104,7 @@ func UserUpdateRoles(ctx context.Context, id string, roles []string) (*User, err
func UserFindByUsername(ctx context.Context, username string) (*User, error) {
user := User{}
err := ibun.Bun.NewSelect().
err := buncomponent.Must(ctx).Bun().NewSelect().
Model(&user).
ColumnExpr("u.*").
ColumnExpr("array(SELECT r.name FROM users_roles AS ur LEFT JOIN roles AS r ON ur.role_id = r.id WHERE ur.user_id = u.id) AS roles").
@ -121,7 +121,7 @@ func UserFindByUsername(ctx context.Context, username string) (*User, error) {
func UserFindById(ctx context.Context, id string) (*User, error) {
user := User{}
err := ibun.Bun.NewSelect().
err := buncomponent.Must(ctx).Bun().NewSelect().
Model(&user).
ColumnExpr("u.*").
ColumnExpr("array(SELECT r.name FROM users_roles AS ur LEFT JOIN roles AS r ON ur.role_id = r.id WHERE ur.user_id = u.id) AS roles").
@ -142,7 +142,7 @@ func UserCreate(ctx context.Context, username, password, email string, roles []s
user.Username = username
user.Password = password
user.Email = email
_, err := ibun.Bun.NewInsert().Model(&user).Exec(ctx, &user)
_, err := buncomponent.Must(ctx).Bun().NewInsert().Model(&user).Exec(ctx, &user)
if err != nil {
return nil, err
}

@ -20,12 +20,13 @@ import (
"jochum.dev/jo-micro/auth2"
"jochum.dev/jo-micro/auth2/cmd/microauth2sqld/config"
"jochum.dev/jo-micro/auth2/cmd/microauth2sqld/handler"
"jochum.dev/jo-micro/auth2/internal/ibun"
"jochum.dev/jo-micro/auth2/internal/ilogger"
"jochum.dev/jo-micro/auth2/internal/proto/authpb"
"jochum.dev/jo-micro/buncomponent"
"jochum.dev/jo-micro/components"
"jochum.dev/jo-micro/logruscomponent"
"jochum.dev/jo-micro/router"
_ "jochum.dev/jo-micro/auth2/plugins/client/jwt"
"jochum.dev/jo-micro/auth2/plugins/client/jwt"
"jochum.dev/jo-micro/auth2/plugins/verifier/endpointroles"
)
@ -92,12 +93,14 @@ func generateRSAPEMKeyPair(bits int) (string, string, error) {
}
func main() {
srv := micro.NewService()
service := micro.NewService()
cReg := components.New(service, "auth2", logruscomponent.New(), auth2.ClientAuthComponent(), buncomponent.New(), router.New())
auth2ClientReg := auth2.ClientAuthRegistry()
auth2ClientReg := auth2.ClientAuthMustReg(cReg)
auth2ClientReg.Register(jwt.New())
auth2ClientReg.ForcePlugin("jwt")
flags := ibun.AppendFlags(ilogger.AppendFlags(auth2ClientReg.MergeFlags([]cli.Flag{
flags := []cli.Flag{
// Generate
&cli.BoolFlag{
Name: "auth2_generate_keys",
@ -159,24 +162,17 @@ func main() {
Usage: "Add and expect this JWT audience",
EnvVars: []string{"MICRO_AUTH2_JWT_AUDIENCES"},
},
})))
}
authHandler := handler.NewHandler()
opts := []micro.Option{
micro.Name(config.Name),
micro.Version(config.Version),
micro.Flags(flags...),
micro.WrapHandler(auth2ClientReg.Wrapper()),
micro.Flags(components.FilterDuplicateFlags(cReg.AppendFlags(flags))...),
micro.WrapHandler(cReg.WrapHandler()),
micro.Action(func(c *cli.Context) error {
// Start the logger
if err := ilogger.Start(c); err != nil {
logger.Fatal(err)
return err
}
if c.Bool("auth2_generate_keys") {
var (
aPubKey string
aPrivKey string
@ -186,40 +182,46 @@ func main() {
)
// Just generate keys and print them to the commandline
switch c.String("auth2_generate_format") {
case "Ed25519":
aPubKey, aPrivKey, err = generateEd25519PEMKeyPair()
if err != nil {
ilogger.Logrus().Fatal(err)
logger.Fatal(err)
return err
}
rPubKey, rPrivKey, err = generateEd25519PEMKeyPair()
if err != nil {
ilogger.Logrus().Fatal(err)
logger.Fatal(err)
return err
}
case "RSA4096":
aPubKey, aPrivKey, err = generateRSAPEMKeyPair(4096)
if err != nil {
ilogger.Logrus().Fatal(err)
logger.Fatal(err)
return err
}
rPubKey, rPrivKey, err = generateRSAPEMKeyPair(4096)
if err != nil {
ilogger.Logrus().Fatal(err)
logger.Fatal(err)
return err
}
case "RSA2048":
aPubKey, aPrivKey, err = generateRSAPEMKeyPair(2048)
if err != nil {
ilogger.Logrus().Fatal(err)
logger.Fatal(err)
return err
}
rPubKey, rPrivKey, err = generateRSAPEMKeyPair(2048)
if err != nil {
ilogger.Logrus().Fatal(err)
logger.Fatal(err)
return err
}
default:
ilogger.Logrus().Fatalf("unknown key format: %s", c.String("auth2_generate_format"))
logger.Fatalf("unknown key format: %s", c.String("auth2_generate_format"))
return err
}
absPath, err := exec.LookPath(os.Args[0])
@ -237,12 +239,16 @@ func main() {
os.Exit(0)
}
if err := auth2ClientReg.Init(auth2.CliContext(c), auth2.Service(srv), auth2.Logrus(ilogger.Logrus())); err != nil {
ilogger.Logrus().Fatal(err)
// Start the components
if err := cReg.Init(c); err != nil {
logger.Fatal(err)
return err
}
logger := logruscomponent.MustReg(cReg).Logger()
authVerifier := endpointroles.NewVerifier(
endpointroles.WithLogrus(ilogger.Logrus()),
endpointroles.WithLogrus(logger),
)
authVerifier.AddRules(
endpointroles.RouterRule,
@ -281,25 +287,27 @@ func main() {
)
auth2ClientReg.Plugin().SetVerifier(authVerifier)
// Connect to the database
if err := ibun.Start(c); err != nil {
ilogger.Logrus().Fatal(err)
}
// Check if we got keys
if c.String("auth2_jwt_pub_key") == "" || c.String("auth2_jwt_priv_key") == "" || c.String("auth2_jwt_refresh_pub_key") == "" || c.String("auth2_jwt_refresh_priv_key") == "" {
ilogger.Logrus().Fatal(ErrorNoKeys)
logger.Fatal(ErrorNoKeys)
return ErrorNoKeys
}
// Check the other handler cli arguments
if c.Int64("auth2_jwt_access_expiry") < 1 {
ilogger.Logrus().Fatal(errors.New("MICRO_AUTH2_JWT_ACCESS_EXPIRY must be great than 0"))
err := errors.New("MICRO_AUTH2_JWT_ACCESS_EXPIRY must be great than 0")
logger.Fatal(err)
return err
}
if c.Int64("auth2_jwt_refresh_expiry") < 1 {
ilogger.Logrus().Fatal(errors.New("MICRO_AUTH2_JWT_REFRESH_EXPIRY must be great than 0"))
err := errors.New("MICRO_AUTH2_JWT_REFRESH_EXPIRY must be great than 0")
logger.Fatal(err)
return err
}
if c.StringSlice("auth2_jwt_audience") == nil {
ilogger.Logrus().Fatal(errors.New("MICRO_AUTH2_JWT_AUDIENCES must be given"))
err := errors.New("MICRO_AUTH2_JWT_AUDIENCES must be given")
logger.Fatal(err)
return err
}
if err := authHandler.Init(handler.InitConfig{
@ -311,88 +319,81 @@ func main() {
RefreshTokenPubKey: c.String("auth2_jwt_refresh_pub_key"),
RefreshTokenPrivKey: c.String("auth2_jwt_refresh_priv_key"),
}); err != nil {
ilogger.Logrus().Fatal(err)
logger.Fatal(err)
return err
}
authpb.RegisterAuthServiceHandler(srv.Server(), authHandler)
authpb.RegisterAuthServiceHandler(service.Server(), authHandler)
// Register with https://jochum.dev/jo-micro/router
r := router.NewHandler(
c.String("auth2_sqld_router_basepath"),
router.NewRoute(
router.Method(router.MethodGet),
router.Path("/"),
router.Endpoint(authpb.AuthService.List),
router.Params("limit", "offset"),
router.AuthRequired(),
router.RatelimitUser("1-S", "10-M"),
),
router.NewRoute(
router.Method(router.MethodPost),
router.Path("/login"),
router.Endpoint(authpb.AuthService.Login),
router.RatelimitClientIP("1-S", "10-M", "30-H", "100-D"),
),
router.NewRoute(
router.Method(router.MethodPost),
router.Path("/register"),
router.Endpoint(authpb.AuthService.Register),
router.RatelimitClientIP("1-M", "10-H", "50-D"),
),
router.NewRoute(
router.Method(router.MethodPost),
router.Path("/refresh"),
router.Endpoint(authpb.AuthService.Refresh),
router.RatelimitClientIP("1-M", "10-H", "50-D"),
),
router.NewRoute(
router.Method(router.MethodDelete),
router.Path("/:userId"),
router.Endpoint(authpb.AuthService.Delete),
router.Params("userId"),
router.AuthRequired(),
router.RatelimitUser("1-S", "10-M"),
),
router.NewRoute(
router.Method(router.MethodGet),
router.Path("/:userId"),
router.Endpoint(authpb.AuthService.Detail),
router.Params("userId"),
router.AuthRequired(),
router.RatelimitUser("100-M"),
),
router.NewRoute(
router.Method(router.MethodPut),
router.Path("/:userId/roles"),
router.Endpoint(authpb.AuthService.UpdateRoles),
router.Params("userId"),
router.AuthRequired(),
router.RatelimitUser("1-M"),
),
)
r.RegisterWithServer(srv.Server())
// r := router.New()
// c.String("auth2_sqld_router_basepath"),
// router.NewRoute(
// router.Method(router.MethodGet),
// router.Path("/"),
// router.Endpoint(authpb.AuthService.List),
// router.Params("limit", "offset"),
// router.AuthRequired(),
// router.RatelimitUser("1-S", "10-M"),
// ),
// router.NewRoute(
// router.Method(router.MethodPost),
// router.Path("/login"),
// router.Endpoint(authpb.AuthService.Login),
// router.RatelimitClientIP("1-S", "10-M", "30-H", "100-D"),
// ),
// router.NewRoute(
// router.Method(router.MethodPost),
// router.Path("/register"),
// router.Endpoint(authpb.AuthService.Register),
// router.RatelimitClientIP("1-M", "10-H", "50-D"),
// ),
// router.NewRoute(
// router.Method(router.MethodPost),
// router.Path("/refresh"),
// router.Endpoint(authpb.AuthService.Refresh),
// router.RatelimitClientIP("1-M", "10-H", "50-D"),
// ),
// router.NewRoute(
// router.Method(router.MethodDelete),
// router.Path("/:userId"),
// router.Endpoint(authpb.AuthService.Delete),
// router.Params("userId"),
// router.AuthRequired(),
// router.RatelimitUser("1-S", "10-M"),
// ),
// router.NewRoute(
// router.Method(router.MethodGet),
// router.Path("/:userId"),
// router.Endpoint(authpb.AuthService.Detail),
// router.Params("userId"),
// router.AuthRequired(),
// router.RatelimitUser("100-M"),
// ),
// router.NewRoute(
// router.Method(router.MethodPut),
// router.Path("/:userId/roles"),
// router.Endpoint(authpb.AuthService.UpdateRoles),
// router.Params("userId"),
// router.AuthRequired(),
// router.RatelimitUser("1-M"),
// ),
// )
// r.RegisterWithServer(service.Server())
return nil
}),
}
srv.Init(opts...)
service.Init(opts...)
// Run server
if err := srv.Run(); err != nil {
ilogger.Logrus().Fatal(err)
}
// Disconnect from the database
if err := ibun.Stop(); err != nil {
ilogger.Logrus().Fatal(err)
if err := service.Run(); err != nil {
logruscomponent.MustReg(cReg).Logger().Fatal(err)
return
}
// Stop the auth Plugin
if err := auth2ClientReg.Stop(); err != nil {
ilogger.Logrus().Fatal(err)
}
// Stop the logger
if err := ilogger.Stop(); err != nil {
if err := cReg.Stop(); err != nil {
logger.Fatal(err)
return
}
}

@ -0,0 +1,158 @@
package auth2
import (
"context"
"fmt"
"strings"
"github.com/urfave/cli/v2"
"go-micro.dev/v4/errors"
"go-micro.dev/v4/server"
"jochum.dev/jo-micro/components"
)
const ClientAuthName = "clientauth"
const RouterAuthName = "routerauth"
func ClientAuthComponent() *AuthRegistry[ClientPlugin] {
c := &AuthRegistry[ClientPlugin]{initialized: false, kind: "client", name: ClientAuthName, plugins: make(map[string]ClientPlugin)}
c.Register(newNoopClientPlugin())
return c
}
func ClientAuthMust(ctx context.Context) *AuthRegistry[ClientPlugin] {
return components.Must(ctx).Must(ClientAuthName).(*AuthRegistry[ClientPlugin])
}
func ClientAuthMustReg(cReg *components.Registry) *AuthRegistry[ClientPlugin] {
return cReg.Must(ClientAuthName).(*AuthRegistry[ClientPlugin])
}
func RouterAuthComponent() *AuthRegistry[RouterPlugin] {
c := &AuthRegistry[RouterPlugin]{initialized: false, kind: "router", name: RouterAuthName, plugins: make(map[string]RouterPlugin)}
c.Register(newNoopRouterPlugin())
return c
}
func RouterAuthMust(ctx context.Context) *AuthRegistry[RouterPlugin] {
return components.Must(ctx).Must(RouterAuthName).(*AuthRegistry[RouterPlugin])
}
func RouterAuthMustReg(cReg *components.Registry) *AuthRegistry[RouterPlugin] {
return cReg.Must(RouterAuthName).(*AuthRegistry[RouterPlugin])
}
type AuthRegistry[T any] struct {
initialized bool
forcedPlugin string
kind string
name string
plugin T
pluginName string
plugins map[string]T
}
func (r *AuthRegistry[T]) ForcePlugin(pName string) error {
r.forcedPlugin = pName
m, ok := r.plugins[pName]
if !ok {
return fmt.Errorf("unknown plugin '%s'", pName)
}
r.pluginName = pName
r.plugin = m
return nil
}
// Register registers a plugin within AuthRegistry
func (r *AuthRegistry[T]) Register(plugin T) {
if s, ok := any(plugin).(registryFuncs); ok {
r.plugins[s.String()] = plugin
} else {
panic("Unknown plugin")
}
}
func (r *AuthRegistry[T]) Priority() int {
return 100
}
func (r *AuthRegistry[T]) Name() string {
return r.name
}
func (r *AuthRegistry[T]) Initialized() bool {
return r.initialized
}
// Flags returns a list of cli.Flag's for micro.Service
func (r *AuthRegistry[T]) Flags(c *components.Registry) []cli.Flag {
flags := []cli.Flag{}
if r.forcedPlugin == "" {
flags = []cli.Flag{
&cli.StringFlag{
Name: fmt.Sprintf("auth2_%s", r.kind),
Usage: fmt.Sprintf("Auth %s Plugin to use", r.kind),
EnvVars: []string{fmt.Sprintf("MICRO_AUTH2_%s", strings.ToUpper(r.kind))},
Value: "noop",
},
}
}
for _, p := range r.plugins {
if p2, ok := any(p).(registryFuncs); ok {
flags = append(flags, p2.Flags(c)...)
}
}
return flags
}
// Plugin returns the current active Plugin
func (r *AuthRegistry[T]) Plugin() T {
return r.plugin
}
// Init should be executed in micro.Init
func (r *AuthRegistry[T]) Init(c *components.Registry, cli *cli.Context) error {
if r.forcedPlugin == "" {
plugin := cli.String(fmt.Sprintf("auth2_%s", r.kind))
m, ok := r.plugins[plugin]
if !ok {
return fmt.Errorf("unknown MICRO_AUTH2_%s plugin '%s'", strings.ToUpper(r.kind), plugin)
}
r.plugin = m
r.pluginName = plugin
}
m2, _ := any(r.plugin).(registryFuncs)
return m2.Init(c, cli)
}
// Stop should be executed after service.Run()
func (r *AuthRegistry[T]) Stop() error {
m, _ := any(r.plugin).(registryFuncs)
return m.Stop()
}
// Health returns the health of the plugin
func (r *AuthRegistry[T]) Health(ctx context.Context) error {
m, _ := any(r.plugin).(registryFuncs)
return m.Health(ctx)
}
// WrapHandlerFunc returns a server.HandleWrapper, this works only for ClientPlugin
func (r *AuthRegistry[T]) WrapHandlerFunc(ctx context.Context, req server.Request, rsp interface{}) error {
m, ok := any(r.plugin).(ClientPlugin)
if !ok {
return errors.InternalServerError("NO_SUCH_AUTH_PLUGIN", fmt.Sprintf("No plugin '%s' found", r.pluginName))
}
return m.WrapHandlerFunc(ctx, req, rsp)
}

@ -13,7 +13,7 @@ require (
github.com/golang-migrate/migrate/v4 v4.15.2
github.com/google/uuid v1.3.0
github.com/jackc/pgx-logrus v0.0.0-20220919124836-b099d8ce75da
github.com/jackc/pgx/v5 v5.0.0
github.com/jackc/pgx/v5 v5.0.1
github.com/sirupsen/logrus v1.9.0
github.com/uptrace/bun v1.1.8
github.com/uptrace/bun/dialect/pgdialect v1.1.8
@ -22,7 +22,10 @@ require (
go-micro.dev/v4 v4.8.1
golang.org/x/crypto v0.0.0-20220924013350-4ba4fb4dd9e7
google.golang.org/protobuf v1.28.1
jochum.dev/jo-micro/router v0.3.8
jochum.dev/jo-micro/buncomponent v0.0.1
jochum.dev/jo-micro/components v0.1.0
jochum.dev/jo-micro/logruscomponent v0.0.2
jochum.dev/jo-micro/router v0.4.0
)
require (
@ -69,7 +72,7 @@ require (
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rogpeppe/go-internal v1.8.0 // indirect
github.com/rogpeppe/go-internal v1.9.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sergi/go-diff v1.2.0 // indirect
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
@ -85,7 +88,7 @@ require (
golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 // indirect
golang.org/x/tools v0.1.12 // indirect
google.golang.org/genproto v0.0.0-20220921223823-23cae91e6737 // indirect
google.golang.org/genproto v0.0.0-20220923205249-dd2d53f1fffc // indirect
google.golang.org/grpc v1.49.0 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect

@ -763,6 +763,8 @@ github.com/jackc/pgx/v4 v4.6.1-0.20200606145419-4e5062306904/go.mod h1:ZDaNWkt9s
github.com/jackc/pgx/v4 v4.10.1/go.mod h1:QlrWebbs3kqEZPHCTGyxecvzG6tvIsYu+A5b1raylkA=
github.com/jackc/pgx/v5 v5.0.0 h1:3UdmB3yUeTnJtZ+nDv3Mxzd4GHHvHkl9XN3oboIbOrY=
github.com/jackc/pgx/v5 v5.0.0/go.mod h1:JBbvW3Hdw77jKl9uJrEDATUZIFM2VFPzRq4RWIhkF4o=
github.com/jackc/pgx/v5 v5.0.1 h1:JZu9othr7l8so2JMDAGeDUMXqERAuZpovyfl4H50tdg=
github.com/jackc/pgx/v5 v5.0.1/go.mod h1:JBbvW3Hdw77jKl9uJrEDATUZIFM2VFPzRq4RWIhkF4o=
github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/puddle v1.1.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
@ -1071,6 +1073,7 @@ github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
@ -1819,6 +1822,8 @@ google.golang.org/genproto v0.0.0-20220111164026-67b88f271998/go.mod h1:5CzLGKJ6
google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E=
google.golang.org/genproto v0.0.0-20220921223823-23cae91e6737 h1:K1zaaMdYBXRyX+cwFnxj7M6zwDyumLQMZ5xqwGvjreQ=
google.golang.org/genproto v0.0.0-20220921223823-23cae91e6737/go.mod h1:2r/26NEF3bFmT3eC3aZreahSal0C3Shl8Gi6vyDYqOQ=
google.golang.org/genproto v0.0.0-20220923205249-dd2d53f1fffc h1:saaNe2+SBQxandnzcD/qB1JEBQ2Pqew+KlFLLdA/XcM=
google.golang.org/genproto v0.0.0-20220923205249-dd2d53f1fffc/go.mod h1:yEEpwVWKMZZzo81NwRgyEJnA2fQvpXAYPVisv8EgDVs=
google.golang.org/grpc v0.0.0-20160317175043-d3ddb4469d5a/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
@ -1924,12 +1929,22 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
jochum.dev/jo-micro/buncomponent v0.0.1 h1:UHLODCgkv0x29jt46SPZ8h20WCT2B8ZNG9wW1OQwdVQ=
jochum.dev/jo-micro/buncomponent v0.0.1/go.mod h1:nQLcdOa3KMOZpm6SLmZK0ef18fX3V9L0BdABdedHiD4=
jochum.dev/jo-micro/components v0.0.11 h1:Rtm0J+MiMcyFVrweJ3r1eoxQY5qP59GzC1TPc7O9Ixs=
jochum.dev/jo-micro/components v0.0.11/go.mod h1:XzhOsv4pAOoRdnrgvYlZXwPzzBd9/8h2CzehB/Yf92w=
jochum.dev/jo-micro/components v0.1.0 h1:9QP79NK+lShksiswtqtxsW8kfd0aBtF87HuBZsu8yxE=
jochum.dev/jo-micro/components v0.1.0/go.mod h1:Yvn0Qz1zctUQUI6WIjq7PbfLY87Qvywpw+KxnVZeCvA=
jochum.dev/jo-micro/logruscomponent v0.0.2 h1:IPyQXOdC0t6Howf4ndykRzVYovrxP5OHM3ZbalRqjYk=
jochum.dev/jo-micro/logruscomponent v0.0.2/go.mod h1:WtSAK/M/zSKuawJhh+Ub+9pknbOKyUScK+qhEbCvFAU=
jochum.dev/jo-micro/router v0.3.6 h1:MgT8k7/Hrxpk+nfit3wg+X7oduo4DsM/uG6XT7Ca2ys=
jochum.dev/jo-micro/router v0.3.6/go.mod h1:5zHbSgMEUKmF8lodzyg4XXXRxFi8QtOM9Ci55dRXs2I=
jochum.dev/jo-micro/router v0.3.7 h1:4AE6PEp9gRMgGUAFkvJWDuT2Tk0cf/kbg12xBPC94OE=
jochum.dev/jo-micro/router v0.3.7/go.mod h1:13ONF6lTtaEm6GpEkEIf+8zY4jL26VhavoU5hQX4itw=
jochum.dev/jo-micro/router v0.3.8 h1:sBSuQ/VpFxMatRvow9gAlYLeE5la7Y0WB+Eh2MqP73Q=
jochum.dev/jo-micro/router v0.3.8/go.mod h1:C5YjdFEIZtObsgFymCyTWOI+rLrUZS1LL9K5oYX8DtE=
jochum.dev/jo-micro/router v0.4.0 h1:2IA/SzrhXGMv4I3Z0i7//U2bfgOE1cwv+r/Ey4FUSgw=
jochum.dev/jo-micro/router v0.4.0/go.mod h1:yPfhNJQ3D1TJ4+IEluT5W5D0ax8mFRZnJ3mcWnyaGvw=
k8s.io/api v0.20.1/go.mod h1:KqwcCVogGxQY3nBlRpwt+wpAMF/KjaCc7RpywacvqUo=
k8s.io/api v0.20.4/go.mod h1:++lNL1AJMkDymriNniQsWRkMDzRaX2Y/POTUi8yvqYQ=
k8s.io/api v0.20.6/go.mod h1:X9e8Qag6JV/bL5G6bU8sdVRltWKmdHsFUGS3eVndqE8=

@ -1,125 +0,0 @@
package ibun
import (
"database/sql"
"fmt"
"strings"
"github.com/golang-migrate/migrate/v4"
migratePostgres "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
pgxLogrus "github.com/jackc/pgx-logrus"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
"github.com/jackc/pgx/v5/tracelog"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/extra/bundebug"
"go-micro.dev/v4/errors"
"jochum.dev/jo-micro/auth2/internal/ilogger"
"jochum.dev/jo-micro/auth2/shared/sutil"
"github.com/urfave/cli/v2"
)
var initialized = false
var SQLDB *sql.DB
var Bun *bun.DB
func AppendFlags(flags []cli.Flag) []cli.Flag {
flags = sutil.MergeFlag(flags, &cli.StringFlag{
Name: "auth2_database_url",
Usage: "bun Database URL",
EnvVars: []string{"MICRO_AUTH2_DATABASE_URL"},
})
flags = sutil.MergeFlag(flags, &cli.BoolFlag{
Name: "auth2_database_debug",
Usage: "Set it to the debug the database queries",
EnvVars: []string{"MICRO_AUTH2_DATABASE_DEBUG"},
DefaultText: "false",
Value: false,
})
flags = sutil.MergeFlag(flags, &cli.StringFlag{
Name: "auth2_migrations_table",
Value: "schema_migrations",
Usage: "Table to store migrations info",
EnvVars: []string{"MICRO_AUTH2_MIGRATIONS_TABLE"},
})
flags = sutil.MergeFlag(flags, &cli.StringFlag{
Name: "auth2_migrations_dir",
Value: "/migrations",
Usage: "Folder which contains migrations",
EnvVars: []string{"MICRO_AUTH2_MIGRATIONS_DIR"},
})
return flags
}
func Intialized() bool {
return initialized
}
func Start(cli *cli.Context) error {
if initialized {
return nil
}
if cli.String("auth2_database_url") == "" {
return errors.InternalServerError("internal/ibun.Start|sqltype.empty", "MICRO_AUTH2_DATABASE_URL is required")
} else if strings.HasPrefix(cli.String("auth2_database_url"), "postgres://") {
config, err := pgx.ParseConfig(cli.String("auth2_database_url"))
if err != nil {
return err
}
if ilogger.Intialized() {
config.Tracer = &tracelog.TraceLog{Logger: pgxLogrus.NewLogger(ilogger.Logrus()), LogLevel: tracelog.LogLevelInfo}
}
connStr := stdlib.RegisterConnConfig(config)
SQLDB, _ := sql.Open("pgx", connStr)
driver, err := migratePostgres.WithInstance(SQLDB, &migratePostgres.Config{MigrationsTable: cli.String("auth2_migrations_table")})
if err != nil {
return err
}
m, err := migrate.NewWithDatabaseInstance(
fmt.Sprintf("file://%s/postgres", cli.String("auth2_migrations_dir")),
"postgres", driver)
if err != nil {
return errors.InternalServerError("internal/ibun.Start|migrate.NewWithDatabaseInstance", fmt.Sprintf("%s", err))
}
if err := m.Up(); err != migrate.ErrNoChange && err != nil {
return errors.InternalServerError("internal/ibun.Start|migrate.Up", fmt.Sprintf("%s", err))
}
Bun = bun.NewDB(SQLDB, pgdialect.New())
if Bun == nil {
return errors.InternalServerError("internal/ibun.Start|bun.NewDB", "failed to create bun")
}
if cli.Bool("auth2_database_debug") {
// Print all queries to stdout.
Bun.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))
}
} else {
return errors.InternalServerError("internal/ibun.Start|sqltype", "unknown MICRO_AUTH2_DATABASE_URL type")
}
initialized = true
return nil
}
func Stop() error {
if err := SQLDB.Close(); err != nil {
return err
}
if err := Bun.Close(); err != nil {
return err
}
return nil
}

@ -1,78 +0,0 @@
package ilogger
import (
"fmt"
"os"
"runtime"
microLogrus "github.com/go-micro/plugins/v4/logger/logrus"
microLogger "go-micro.dev/v4/logger"
"jochum.dev/jo-micro/auth2/shared/sutil"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
var myLogger *logrus.Logger = nil
var initialized = false
func AppendFlags(flags []cli.Flag) []cli.Flag {
return sutil.MergeFlag(flags, &cli.StringFlag{
Name: "auth2_loglevel",
Value: "info",
Usage: "Logrus log level default 'info', {panic,fatal,error,warn,info,debug,trace} available",
EnvVars: []string{"MICRO_AUTH2_LOG_LEVEL"},
})
}
func Intialized() bool {
return initialized
}
// caller returns string presentation of log caller which is formatted as
// `/path/to/file.go:line_number`. e.g. `/internal/app/api.go:25`
func caller() func(*runtime.Frame) (function string, file string) {
return func(f *runtime.Frame) (function string, file string) {
return "", fmt.Sprintf("%s:%d", f.File, f.Line)
}
}
func Start(cli *cli.Context) error {
if initialized {
return nil
}
lvl, err := logrus.ParseLevel(cli.String("auth2_loglevel"))
if err != nil {
return err
}
myLogger = logrus.New()
myLogger.Out = os.Stdout
myLogger.Level = lvl
myLogger.SetReportCaller(true)
myLogger.SetFormatter(&logrus.JSONFormatter{
CallerPrettyfier: caller(),
FieldMap: logrus.FieldMap{
logrus.FieldKeyFile: "caller",
},
})
microLogger.DefaultLogger = microLogrus.NewLogger(microLogrus.WithLogger(myLogger))
initialized = true
return nil
}
func Stop() error {
initialized = false
myLogger = nil
return nil
}
func Logrus() *logrus.Logger {
return myLogger
}

@ -6,14 +6,11 @@ import (
"github.com/google/uuid"
"github.com/urfave/cli/v2"
"go-micro.dev/v4/errors"
"go-micro.dev/v4/server"
"jochum.dev/jo-micro/components"
)
func init() {
ClientAuthRegistry().Register(newNoopClientPlugin())
RouterAuthRegistry().Register(newNoopRouterPlugin())
}
func newNoopClientPlugin() ClientPlugin {
return new(noopClientPlugin)
}
@ -24,11 +21,11 @@ func (p *noopClientPlugin) String() string {
return "noop"
}
func (p *noopClientPlugin) MergeFlags(flags []cli.Flag) []cli.Flag {
return flags
func (p *noopClientPlugin) Flags(r *components.Registry) []cli.Flag {
return []cli.Flag{}
}
func (p *noopClientPlugin) Init(opts ...InitOption) error {
func (p *noopClientPlugin) Init(r *components.Registry, cli *cli.Context) error {
return nil
}
@ -36,8 +33,8 @@ func (p *noopClientPlugin) Stop() error {
return nil
}
func (p *noopClientPlugin) Health(ctx context.Context) (string, error) {
return "All fine", nil
func (p *noopClientPlugin) Health(ctx context.Context) error {
return nil
}
func (p *noopClientPlugin) SetVerifier(v VerifierPlugin) {
@ -51,8 +48,8 @@ func (p *noopClientPlugin) Inspect(ctx context.Context) (*User, error) {
return &User{Id: uuid.New().String(), Issuer: p.String()}, nil
}
func (p *noopClientPlugin) WrapperFunc(h server.HandlerFunc, ctx context.Context, req server.Request, rsp interface{}) error {
return h(ctx, req, rsp)
func (p *noopClientPlugin) WrapHandlerFunc(ctx context.Context, req server.Request, rsp interface{}) error {
return errors.MethodNotAllowed("NO_AUTH_METHOD", "no auth method - noop plugin")
}
func newNoopRouterPlugin() RouterPlugin {
@ -65,11 +62,11 @@ func (p *noopRouterPlugin) String() string {
return "noop"
}
func (p *noopRouterPlugin) MergeFlags(flags []cli.Flag) []cli.Flag {
return flags
func (p *noopRouterPlugin) Flags(r *components.Registry) []cli.Flag {
return []cli.Flag{}
}
func (p *noopRouterPlugin) Init(opts ...InitOption) error {
func (p *noopRouterPlugin) Init(r *components.Registry, cli *cli.Context) error {
return nil
}
@ -77,8 +74,8 @@ func (p *noopRouterPlugin) Stop() error {
return nil
}
func (p *noopRouterPlugin) Health(ctx context.Context) (string, error) {
return "All fine", nil
func (p *noopRouterPlugin) Health(ctx context.Context) error {
return nil
}
func (p *noopRouterPlugin) Inspect(r *http.Request) (*User, error) {

@ -1,48 +0,0 @@
package auth2
import (
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"go-micro.dev/v4"
"go-micro.dev/v4/errors"
)
type InitOptions struct {
CliContext *cli.Context
Service micro.Service
Logrus *logrus.Logger
}
type InitOption func(o *InitOptions)
func CliContext(n *cli.Context) InitOption {
return func(o *InitOptions) {
o.CliContext = n
}
}
func Service(n micro.Service) InitOption {
return func(o *InitOptions) {
o.Service = n
}
}
func Logrus(n *logrus.Logger) InitOption {
return func(o *InitOptions) {
o.Logrus = n
}
}
func NewInitOptions(opts ...InitOption) (InitOptions, error) {
options := InitOptions{}
for _, o := range opts {
o(&options)
}
// Make CliContext() required
if options.CliContext == nil {
return options, errors.InternalServerError("auth2.NewInitOptions:no cli.Context", "no cli.Context hase been given")
}
return options, nil
}

@ -6,6 +6,7 @@ import (
"github.com/urfave/cli/v2"
"go-micro.dev/v4/server"
"jochum.dev/jo-micro/components"
)
type registryFuncs interface {
@ -13,16 +14,16 @@ type registryFuncs interface {
String() string
// MergeFlags merges a list of cli.Flag's for micro.Service
MergeFlags(flags []cli.Flag) []cli.Flag
Flags(r *components.Registry) []cli.Flag
// Init should be executed in micro.Init
Init(opts ...InitOption) error
Init(r *components.Registry, cli *cli.Context) error
// Stop should be executed after service.Run()
Stop() error
// Health returns the health of the plugin
Health(ctx context.Context) (string, error)
Health(ctx context.Context) error
}
type VerifierPlugin interface {
@ -43,8 +44,8 @@ type ClientPlugin interface {
// Inspect a context
Inspect(ctx context.Context) (*User, error)
// Wrapper returns the Auth Wrapper for your service
WrapperFunc(h server.HandlerFunc, ctx context.Context, req server.Request, rsp interface{}) error
// WrapHandlerFunc runs the authentication
WrapHandlerFunc(ctx context.Context, req server.Request, rsp interface{}) error
}
// RouterPlugin is for routers that forward the token or do other stuff required by ClientPlugin

@ -17,13 +17,10 @@ import (
"jochum.dev/jo-micro/auth2/plugins/verifier/endpointroles"
"jochum.dev/jo-micro/auth2/shared/sjwt"
"jochum.dev/jo-micro/auth2/shared/sutil"
"jochum.dev/jo-micro/components"
)
func init() {
auth2.ClientAuthRegistry().Register(newJWTPlugin())
}
func newJWTPlugin() auth2.ClientPlugin {
func New() auth2.ClientPlugin {
return &jwtPlugin{
verifier: endpointroles.NewVerifier(
endpointroles.NoDefaultDeny(),
@ -42,8 +39,8 @@ func (p *jwtPlugin) String() string {
return "jwt"
}
func (p *jwtPlugin) MergeFlags(flags []cli.Flag) []cli.Flag {
return sutil.MergeFlags(flags,
func (p *jwtPlugin) Flags(r *components.Registry) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "auth2_jwt_pub_key",
Usage: "Public key PEM base64 encoded for access keys",
@ -57,29 +54,24 @@ func (p *jwtPlugin) MergeFlags(flags []cli.Flag) []cli.Flag {
Usage: "Add and expect this JWT audience",
EnvVars: []string{"MICRO_AUTH2_JWT_AUDIENCES"},
},
)
}
func (p *jwtPlugin) Init(opts ...auth2.InitOption) error {
options, err := auth2.NewInitOptions(opts...)
if err != nil {
return err
}
}
if len(options.CliContext.String("auth2_jwt_pub_key")) < 1 || len(options.CliContext.String("auth2_jwt_priv_key")) < 1 {
func (p *jwtPlugin) Init(r *components.Registry, cli *cli.Context) error {
if len(cli.String("auth2_jwt_pub_key")) < 1 || len(cli.String("auth2_jwt_priv_key")) < 1 {
return errors.New("you must provide auth2_jwt_(priv|pub)_key")
}
if options.CliContext.StringSlice("auth2_jwt_audience") == nil {
if cli.StringSlice("auth2_jwt_audience") == nil {
return errors.New("MICRO_AUTH2_JWT_AUDIENCES must be given")
}
pub, priv, err := sjwt.DecodeKeyPair(options.CliContext.String("auth2_jwt_pub_key"), options.CliContext.String("auth2_jwt_priv_key"))
pub, priv, err := sjwt.DecodeKeyPair(cli.String("auth2_jwt_pub_key"), cli.String("auth2_jwt_priv_key"))
if err != nil {
return err
}
p.audiences = options.CliContext.StringSlice("auth2_jwt_audience")
p.audiences = cli.StringSlice("auth2_jwt_audience")
p.pubKey = pub
p.privKey = priv
@ -90,8 +82,8 @@ func (p *jwtPlugin) Stop() error {
return nil
}
func (p *jwtPlugin) Health(ctx context.Context) (string, error) {
return "All fine", nil
func (p *jwtPlugin) Health(ctx context.Context) error {
return nil
}
func (p *jwtPlugin) SetVerifier(v auth2.VerifierPlugin) {
@ -173,7 +165,7 @@ func (p *jwtPlugin) Inspect(ctx context.Context) (*auth2.User, error) {
return &auth2.User{Id: claims.ID, Type: claims.Type, Issuer: claims.Issuer, Metadata: cMD, Scopes: claims.Scopes, Roles: claims.Roles}, nil
}
func (p *jwtPlugin) WrapperFunc(h server.HandlerFunc, ctx context.Context, req server.Request, rsp interface{}) error {
func (p *jwtPlugin) WrapHandlerFunc(ctx context.Context, req server.Request, rsp interface{}) error {
u, err := p.Inspect(ctx)
if err != nil {
u = auth2.AnonUser
@ -184,5 +176,5 @@ func (p *jwtPlugin) WrapperFunc(h server.HandlerFunc, ctx context.Context, req s
return err
}
return h(ctx, req, rsp)
return nil
}

@ -10,59 +10,46 @@ import (
"strings"
"github.com/golang-jwt/jwt/v4"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"go-micro.dev/v4/errors"
"go-micro.dev/v4/metadata"
"jochum.dev/jo-micro/auth2"
auth "jochum.dev/jo-micro/auth2"
"jochum.dev/jo-micro/auth2/shared/sjwt"
"jochum.dev/jo-micro/auth2/shared/sutil"
"jochum.dev/jo-micro/components"
"jochum.dev/jo-micro/logruscomponent"
)
func init() {
auth.RouterAuthRegistry().Register(newJWTPlugin())
}
func newJWTPlugin() auth.RouterPlugin {
func New() auth2.RouterPlugin {
return new(jwtPlugin)
}
type jwtPlugin struct {
pubKey any
options auth2.InitOptions
}
func (p *jwtPlugin) logrus() *logrus.Logger {
if p.options.Logrus == nil {
return logrus.StandardLogger()
}
return p.options.Logrus
cReg *components.Registry
pubKey any
}
func (p *jwtPlugin) String() string {
return "jwt"
}
func (p *jwtPlugin) MergeFlags(flags []cli.Flag) []cli.Flag {
return sutil.MergeFlag(flags, &cli.StringFlag{
Name: "auth2_jwt_pub_key",
Usage: "Public key PEM base64 encoded",
EnvVars: []string{"MICRO_AUTH2_JWT_PUB_KEY"},
})
func (p *jwtPlugin) Flags(r *components.Registry) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "auth2_jwt_pub_key",
Usage: "Public key PEM base64 encoded",
EnvVars: []string{"MICRO_AUTH2_JWT_PUB_KEY"},
},
}
}
func (p *jwtPlugin) Init(opts ...auth2.InitOption) error {
options, err := auth2.NewInitOptions(opts...)
if err != nil {
return err
}
func (p *jwtPlugin) Init(r *components.Registry, cli *cli.Context) error {
p.cReg = r
if len(options.CliContext.String("auth2_jwt_pub_key")) < 1 {
if len(cli.String("auth2_jwt_pub_key")) < 1 {
return errors.InternalServerError("auth2/plugins/router/jwt.Init:No auth2_jwt_pub_key", "you must provide auth2_jwt_pub_key")
}
aPub, err := base64.StdEncoding.DecodeString(options.CliContext.String("auth2_jwt_pub_key"))
aPub, err := base64.StdEncoding.DecodeString(cli.String("auth2_jwt_pub_key"))
if err != nil {
return err
}
@ -86,13 +73,13 @@ func (p *jwtPlugin) Stop() error {
return nil
}
func (p *jwtPlugin) Health(ctx context.Context) (string, error) {
return "All fine", nil
func (p *jwtPlugin) Health(ctx context.Context) error {
return nil
}
func (p *jwtPlugin) Inspect(r *http.Request) (*auth.User, error) {
func (p *jwtPlugin) Inspect(r *http.Request) (*auth2.User, error) {
if _, ok := r.Header["Authorization"]; !ok {
p.logrus().WithField("headers", r.Header).Debug("empty or no Authorization header in request")
logruscomponent.MustReg(p.cReg).Logger().WithField("headers", r.Header).Debug("empty or no Authorization header in request")
return nil, errors.InternalServerError("auth2/plugins/router/jwt.Inspect", "empty or no Authorization header in request")
}
@ -117,7 +104,7 @@ func (p *jwtPlugin) Inspect(r *http.Request) (*auth.User, error) {
"Subject": claims.Subject,
}
return &auth.User{Id: claims.ID, Type: claims.Type, Issuer: claims.Issuer, Metadata: cMD, Scopes: claims.Scopes, Roles: claims.Roles}, nil
return &auth2.User{Id: claims.ID, Type: claims.Type, Issuer: claims.Issuer, Metadata: cMD, Scopes: claims.Scopes, Roles: claims.Roles}, nil
}
func (p *jwtPlugin) ForwardContext(u *auth2.User, r *http.Request, ctx context.Context) (context.Context, error) {
@ -129,7 +116,7 @@ func (p *jwtPlugin) ForwardContext(u *auth2.User, r *http.Request, ctx context.C
md["X-Fowarded-For"] = v
}
p.logrus().WithField("username", u.Metadata["Subject"]).Trace("Forwarding user")
logruscomponent.MustReg(p.cReg).Logger().WithField("username", u.Metadata["Subject"]).Trace("Forwarding user")
return metadata.MergeContext(ctx, md, true), nil
}

@ -1,122 +0,0 @@
package auth2
import (
"context"
"fmt"
"strings"
"github.com/urfave/cli/v2"
"go-micro.dev/v4/errors"
"go-micro.dev/v4/server"
"jochum.dev/jo-micro/auth2/shared/sutil"
)
var car = &AuthRegistry[ClientPlugin]{kind: "client", plugins: make(map[string]ClientPlugin)}
var rar = &AuthRegistry[RouterPlugin]{kind: "router", plugins: make(map[string]RouterPlugin)}
func ClientAuthRegistry() *AuthRegistry[ClientPlugin] {
return car
}
func RouterAuthRegistry() *AuthRegistry[RouterPlugin] {
return rar
}
type AuthRegistry[T any] struct {
forcedPlugin string
kind string
plugin T
plugins map[string]T
}
func (r *AuthRegistry[T]) ForcePlugin(pName string) error {
r.forcedPlugin = pName
m, ok := r.plugins[pName]
if !ok {
return fmt.Errorf("unknown plugin '%s'", pName)
}
r.plugin = m
return nil
}
// Register registers a plugin within AuthRegistry
func (r *AuthRegistry[T]) Register(plugin T) {
if s, ok := any(plugin).(registryFuncs); ok {
r.plugins[s.String()] = plugin
}
}
// Flags returns a list of cli.Flag's for micro.Service
func (r *AuthRegistry[T]) MergeFlags(flags []cli.Flag) []cli.Flag {
if r.forcedPlugin == "" {
flags = sutil.MergeFlag(flags, &cli.StringFlag{
Name: fmt.Sprintf("auth2_%s", r.kind),
Usage: fmt.Sprintf("Auth %s Plugin to use", r.kind),
EnvVars: []string{fmt.Sprintf("MICRO_AUTH2_%s", strings.ToUpper(r.kind))},
Value: "noop",
})
}
for _, p := range r.plugins {
if p2, ok := any(p).(registryFuncs); ok {
flags = p2.MergeFlags(flags)
}
}
return flags
}
// Plugin returns the current active Plugin
func (r *AuthRegistry[T]) Plugin() T {
return r.plugin
}
// Init should be executed in micro.Init
func (r *AuthRegistry[T]) Init(opts ...InitOption) error {
options, err := NewInitOptions(opts...)
if err != nil {
return err
}