nethttpoidc/README.md
2022-12-19 22:49:59 +01:00

2.2 KiB

nethttpoidc

oidc middleware for net/http


package cmd

import (
	"context"
	"log"
	"net/http"

	"code.icod.de/dalu/exyuql/config"
	"code.icod.de/dalu/exyuql/graph"
	"code.icod.de/dalu/nethttpoidc"
	"code.icod.de/dalu/oidc/options"
	"entgo.io/contrib/entgql"
	"github.com/99designs/gqlgen/graphql/handler"
	"github.com/99designs/gqlgen/graphql/playground"
	"github.com/MadAppGang/httplog"
	"github.com/rs/cors"
	"github.com/spf13/cobra"
)

var (
	graphqlDebug = false
	graphqlAddr  = "unix:/tmp/exyu.eu-graphql.sock"
)

// graphqlCmd represents the graphql command
var graphqlCmd = &cobra.Command{
	Use:   "graphql",
	Short: "A brief description of your command",
	RunE: func(cmd *cobra.Command, args []string) error {
		client := openDB(config.DatabaseUrlDev)
		if e := client.Schema.Create(
			context.Background(),
		); e != nil {
			log.Fatal("opening ent client", e)
		}
		srv := handler.NewDefaultServer(graph.NewSchema(client))
		srv.Use(entgql.Transactioner{TxOpener: client})

		cfg := config.OidcConfigDev

		oidcHandler := nethttpoidc.New(srv,
			options.WithIssuer(cfg.Issuer),
			options.WithRequiredTokenType("JWT"),
			options.WithRequiredAudience(cfg.Audience),
			options.IsPermissive(),
		)

		corsHandler := cors.AllowAll()
		http.Handle("/", playground.Handler("exyu.eu", "/query"))
		http.Handle("/query", corsHandler.Handler(httplog.LoggerWithFormatter(httplog.DefaultLogFormatterWithRequestHeader, oidcHandler)))

		return http.ListenAndServe(":8081", nil)
	},
}

func init() {
	rootCmd.AddCommand(graphqlCmd)

	graphqlCmd.Flags().BoolVar(
		&graphqlDebug,
		"debug",
		false,
		"debug enabled?",
	)
	graphqlCmd.Flags().StringVar(
		&graphqlAddr,
		"addr",
		"unix:/tmp/exyu.eu-graphql.sock",
		"either tcp: or unix: e.g. tcp:localhost:3030 unix:/tmp/listen.sock",
	)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// graphqlCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// graphqlCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}