AFAIRE
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.6 KiB

/*
------------------------------------------------------------------------------------------------------------------------
####### kong ####### Copyright (c) 2021-2022 losyme ################################################ MIT License #######
------------------------------------------------------------------------------------------------------------------------
*/
package middleware
import (
"net/http"
"forge.chapril.org/losyme/uuid"
"forge.chapril.org/losyme/kong/context"
"forge.chapril.org/losyme/kong/router"
)
const HeaderXRequestID = "X-Request-ID"
type Crypto interface {
DecryptString(text string) (string, error)
}
type Logger interface {
Debug(msg string, kv ...interface{})
Error(msg string, kv ...interface{})
}
func BasicAuth(crypto Crypto) router.Middleware {
return func(next router.HandlerFunc) router.HandlerFunc {
return func(c *context.Context) error {
username, password, ok := c.Request.BasicAuth()
if !ok {
c.SetHeaderWWWAuthenticate()
return c.NewError(http.StatusUnauthorized, "authorization Required") ///////////////////////////////////
}
value, err := crypto.DecryptString(password)
if err != nil || value != username {
c.SetHeaderWWWAuthenticate()
return c.NewError(http.StatusUnauthorized, "invalid username and/or password") /////////////////////////
}
return next(c)
}
}
}
func Log(logger Logger) router.Middleware {
return func(next router.HandlerFunc) router.HandlerFunc {
return func(c *context.Context) error {
req := c.Request
logger.Debug( //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
"Request",
"id", c.RequestID(),
"from", req.RemoteAddr,
"method", req.Method,
"uri", req.URL.RequestURI(),
)
if err := next(c); err != nil {
logger.Debug( //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
"Response",
"request", c.RequestID(),
nil, err,
)
return err
}
logger.Debug( //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
"Response",
"request", c.RequestID(),
"status", c.Status,
)
return nil
}
}
}
func RequestID() router.Middleware {
return func(next router.HandlerFunc) router.HandlerFunc {
return func(c *context.Context) error {
rID := c.Request.Header.Get(HeaderXRequestID)
if rID == "" {
rID = uuid.New()
}
c.SetRequestID(rID)
c.SetHeader(HeaderXRequestID, rID)
return next(c)
}
}
}
/*
######################################################################################################## @(°_°)@ #######
*/