Add `authtype` to logging middleware (#3310)

* Add authtype to logging middleware

This is useful for determining the authentication method that is being used for server traffic.

* use if statement
pull/3313/head
Colin Hoglund 2023-04-18 02:40:07 -07:00 committed by GitHub
parent eadb4638b4
commit d08aabb3ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 6 deletions

View File

@ -36,11 +36,20 @@ func Middleware(next http.Handler) http.Handler {
next.ServeHTTP(w, r.WithContext(ctx))
end := time.Now()
log.WithFields(logrus.Fields{
"method": r.Method,
"request": r.RequestURI,
"remote": r.RemoteAddr,
"latency": end.Sub(start),
"time": end.Format(time.RFC3339),
"method": r.Method,
"request": r.RequestURI,
"remote": r.RemoteAddr,
"latency": end.Sub(start),
"time": end.Format(time.RFC3339),
"authtype": authType(r),
}).Debug()
})
}
func authType(r *http.Request) string {
if r.Header.Get("Authorization") != "" || r.FormValue("access_token") != "" {
return "token"
}
return "cookie"
}

View File

@ -6,7 +6,10 @@
package logger
import "testing"
import (
"net/http/httptest"
"testing"
)
func TestMiddleware(t *testing.T) {
t.Skip()
@ -15,3 +18,21 @@ func TestMiddleware(t *testing.T) {
func TestMiddleware_GenerateRequestID(t *testing.T) {
t.Skip()
}
func TestAuthType(t *testing.T) {
cookieRequest := httptest.NewRequest("GET", "/", nil)
if authType(cookieRequest) != "cookie" {
t.Error("authtype is not cookie")
}
headerRequest := httptest.NewRequest("GET", "/", nil)
headerRequest.Header.Add("Authorization", "test")
if authType(headerRequest) != "token" {
t.Error("authtype is not token")
}
formRequest := httptest.NewRequest("GET", "/?access_token=test", nil)
if authType(formRequest) != "token" {
t.Error("authtype is not token")
}
}