-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddleware.go
More file actions
123 lines (113 loc) · 3.38 KB
/
middleware.go
File metadata and controls
123 lines (113 loc) · 3.38 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package router
import (
"net/http"
"strconv"
"time"
"github.com/google/uuid"
"github.com/labstack/echo/v5"
"github.com/traPtitech/Jomon/internal/logging"
"github.com/traPtitech/Jomon/internal/router/wrapsession"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
loginUserKey = "login_user"
)
func (h Handlers) setLoggerMiddleware(logger *zap.Logger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
req := c.Request()
ctx := req.Context()
reqID := req.Header.Get(echo.HeaderXRequestID)
l := logger.With(zap.String("requestID", reqID))
ctx = logging.SetLogger(ctx, l)
c.SetRequest(req.WithContext(ctx))
return next(c)
}
}
}
// AccessLoggingMiddleware ですべてのエラーを出力する
func (h Handlers) AccessLoggingMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// TODO(logging): https://echo.labstack.com/docs/middleware/logger を使う
return func(c *echo.Context) error {
start := time.Now()
err := next(c)
if err != nil {
defaultHTTPErrorHandler(c, HTTPErrorHandlerInner(err))
}
stop := time.Now()
req := c.Request()
latency := strconv.FormatFloat(stop.Sub(start).Seconds(), 'f', 9, 64) + "s"
fields := []zapcore.Field{
zap.String("requestMethod", req.Method),
zap.String("userAgent", req.UserAgent()),
zap.String("remoteIp", c.RealIP()),
zap.String("referer", req.Referer()),
zap.String("protocol", req.Proto),
zap.String("requestUrl", req.URL.String()),
zap.String("requestSize", req.Header.Get(echo.HeaderContentLength)),
zap.String("latency", latency),
}
rw, uErr := echo.UnwrapResponse(c.Response())
if uErr != nil {
logger := logging.GetLogger(req.Context())
fields = append(
fields,
zap.Error(uErr),
zap.String("status", "unknown"),
zap.String("responseSize", "unknown"))
logger.Error("failed to unwrap response for access logging", fields...)
return nil
}
fields = append(fields,
zap.Int("status", rw.Status),
zap.String("responseSize", strconv.FormatInt(rw.Size, 10)))
logger := logging.GetLogger(req.Context())
httpCode := rw.Status
switch {
case httpCode >= 500:
fields = append(fields, zap.Error(err))
logger.Error("server error", fields...)
case httpCode >= 400:
fields = append(fields, zap.Error(err))
logger.Warn("client error", fields...)
case httpCode >= 300:
logger.Info("redirect", fields...)
default:
logger.Info("success", fields...)
}
return nil
}
}
func (h Handlers) CheckLoginMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
ctx := c.Request().Context()
id, err := wrapsession.WithSession(
c, h.SessionName, func(w *wrapsession.W) (uuid.UUID, error) {
v, ok := w.GetUserID()
if !ok {
err := echo.NewHTTPError(http.StatusUnauthorized, "you are not logged in")
return uuid.Nil, err
}
return v, nil
})
if err != nil {
return err
}
user, err := h.Repository.GetUserByID(ctx, id)
if err != nil {
return err
}
c.Set(loginUserKey, userFromModelUser(*user))
return next(c)
}
}
func (h Handlers) CheckAccountManagerMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
loginUser, _ := c.Get(loginUserKey).(User)
if !loginUser.AccountManager {
return echo.NewHTTPError(http.StatusForbidden, "you are not accountManager")
}
return next(c)
}
}