-
Notifications
You must be signed in to change notification settings - Fork 1
/
middlewares.go
108 lines (91 loc) · 2.32 KB
/
middlewares.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package common
import (
"github.com/goccy/go-json"
"runtime/debug"
"strconv"
"time"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"
)
func GetUserID(c *fiber.Ctx) (int, error) {
// get user id from header: X-Consumer-Username if through Kong
username := c.Get("X-Consumer-Username")
if username != "" {
id, err := strconv.Atoi(username)
if err == nil {
return id, nil
}
}
// get user id from jwt
// ID and UserID are both valid
var user struct {
ID int `json:"id"`
UserID int `json:"user_id"`
}
token := GetJWTToken(c)
if token == "" {
return 0, Unauthorized("Unauthorized")
}
err := ParseJWTToken(token, &user)
if err != nil {
return 0, Unauthorized("Unauthorized")
}
if user.ID != 0 {
return user.ID, nil
} else if user.UserID != 0 {
return user.UserID, nil
}
return 0, Unauthorized("Unauthorized")
}
func MiddlewareGetUserID(c *fiber.Ctx) error {
userID, err := GetUserID(c)
if err == nil {
c.Locals("user_id", userID)
}
return c.Next()
}
func MiddlewareCustomLogger(c *fiber.Ctx) error {
startTime := time.Now()
chainErr := c.Next()
if chainErr != nil {
if err := c.App().ErrorHandler(c, chainErr); err != nil {
_ = c.SendStatus(fiber.StatusInternalServerError)
}
}
latency := time.Since(startTime).Milliseconds()
userID, ok := c.Locals("user_id").(int)
contentType := string(c.Request().Header.ContentType())
output := log.Info().
Int("status_code", c.Response().StatusCode()).
Str("method", c.Method()).
Str("origin_url", c.OriginalURL()).
Str("remote_ip", c.Get("X-Real-IP")).
Str("user_agent", c.Get("User-Agent", "")).
Int64("latency", latency).
Str("content_type", contentType)
xForwardFor := c.Get("X-Forwarded-For")
if xForwardFor != "" {
output = output.Str("x_forwarded_for", xForwardFor)
}
if ok {
output = output.Int("user_id", userID)
}
if chainErr != nil {
output = output.Err(chainErr)
}
if c.Method() == "POST" || c.Method() == "PUT" {
var body = make(map[string]any)
err := json.Unmarshal(c.Body(), &body)
if err != nil {
output = output.Bytes("body", StripBytes(c.Body(), 32))
} else {
delete(body, "password")
output = output.Any("body", body)
}
}
output.Msg("http log")
return nil
}
func StackTraceHandler(_ *fiber.Ctx, e any) {
log.Error().Any("panic", e).Bytes("stack", debug.Stack()).Msg("stacktrace")
}