use zitadel/logging

This commit is contained in:
Tim Möhlmann 2023-08-24 19:08:14 +03:00
parent f30f0d3ead
commit 6f8f5226d7
7 changed files with 48 additions and 138 deletions

View file

@ -4,13 +4,15 @@ import (
"crypto/sha256"
"log"
"net/http"
"os"
"strconv"
"sync/atomic"
"time"
"github.com/go-chi/chi"
"golang.org/x/exp/slog"
"golang.org/x/text/language"
"github.com/zitadel/logging"
"github.com/zitadel/oidc/v3/example/server/storage"
"github.com/zitadel/oidc/v3/pkg/op"
)
@ -33,15 +35,25 @@ type Storage interface {
deviceAuthenticate
}
// simple request id counter
var requestID atomic.Uint64
// SetupServer creates an OIDC server with Issuer=http://localhost:<port>
//
// Use one of the pre-made clients in storage/clients.go or register a new one.
func SetupServer(issuer string, storage Storage) chi.Router {
func SetupServer(issuer string, storage Storage, logger *slog.Logger) chi.Router {
// the OpenID Provider requires a 32-byte key for (token) encryption
// be sure to create a proper crypto random key and manage it securely!
key := sha256.Sum256([]byte("test"))
router := chi.NewRouter()
// Enable request logging on INFO level
router.Use(logging.Middleware(
logging.MiddlewareWithLoggerOption(logger),
logging.MiddlewareWithIDOption(func() string {
return strconv.FormatUint(requestID.Add(1), 10)
}),
))
// for simplicity, we provide a very small default page for users who have signed out
router.HandleFunc(pathLoggedOut, func(w http.ResponseWriter, req *http.Request) {
@ -50,7 +62,7 @@ func SetupServer(issuer string, storage Storage) chi.Router {
})
// creation of the OpenIDProvider with the just created in-memory Storage
provider, err := newOP(storage, issuer, key)
provider, err := newOP(storage, issuer, key, logger)
if err != nil {
log.Fatal(err)
}
@ -80,7 +92,7 @@ func SetupServer(issuer string, storage Storage) chi.Router {
// newOP will create an OpenID Provider for localhost on a specified port with a given encryption key
// and a predefined default logout uri
// it will enable all options (see descriptions)
func newOP(storage op.Storage, issuer string, key [32]byte) (op.OpenIDProvider, error) {
func newOP(storage op.Storage, issuer string, key [32]byte, logger *slog.Logger) (op.OpenIDProvider, error) {
config := &op.Config{
CryptoKey: key,
@ -117,12 +129,8 @@ func newOP(storage op.Storage, issuer string, key [32]byte) (op.OpenIDProvider,
op.WithAllowInsecure(),
// as an example on how to customize an endpoint this will change the authorization_endpoint from /authorize to /auth
op.WithCustomAuthEndpoint(op.NewEndpoint("auth")),
op.WithLogger(slog.New(
slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelDebug,
}),
)),
// Pass our logger to the OP
op.WithLogger(logger.WithGroup("op")),
)
if err != nil {
return nil, err