/
middlewares.go
99 lines (78 loc) · 2.36 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
package serve
import (
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/YuukanOO/seelf/internal/auth/domain"
httputils "github.com/YuukanOO/seelf/pkg/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
const (
userSessionKey = "seelf-session"
apiAuthHeader = "Authorization"
apiAuthPrefix = "Bearer "
apiAuthPrefixLength = len(apiAuthPrefix)
)
var errUnauthorized = errors.New("unauthorized")
func (s *server) authenticate(withApiAccess bool) gin.HandlerFunc {
return func(ctx *gin.Context) {
// First, try to find a user id in the encrypted session cookie
sess := sessions.Default(ctx)
uid, ok := sess.Get(userSessionKey).(string)
failed := !ok || uid == ""
// If it failed and api access is not allowed, return early
if failed && !withApiAccess {
ctx.AbortWithError(http.StatusUnauthorized, errUnauthorized)
return
}
// Else, if we do not fail, the user id has been found, go on
if !failed {
ctx.Request = ctx.Request.WithContext(domain.WithUserID(ctx.Request.Context(), domain.UserID(uid)))
ctx.Next()
return
}
// If we are here, look in the request header to check if an api key is present and check if it corresponds to an existing user
authHeader := ctx.GetHeader(apiAuthHeader)
if !strings.HasPrefix(authHeader, apiAuthPrefix) {
ctx.AbortWithError(http.StatusUnauthorized, errUnauthorized)
return
}
id, err := s.usersReader.GetIDFromAPIKey(ctx.Request.Context(), domain.APIKey(authHeader[apiAuthPrefixLength:]))
if err != nil {
ctx.AbortWithError(http.StatusUnauthorized, errUnauthorized)
return
}
// Attach the user id to the context passed down in every usecases.
ctx.Request = ctx.Request.WithContext(domain.WithUserID(ctx.Request.Context(), id))
ctx.Next()
}
}
func (s *server) requestLogger(ctx *gin.Context) {
defer func(start time.Time, c *gin.Context) {
path := ctx.Request.URL.Path
raw := ctx.Request.URL.RawQuery
if raw != "" {
path = path + "?" + raw
}
s.logger.Debugw(path,
"status", c.Writer.Status(),
"method", c.Request.Method,
"elapsed", time.Since(start))
}(time.Now(), ctx)
ctx.Next()
}
func (s *server) recoverer(ctx *gin.Context) {
defer func() {
if err := recover(); err != nil {
asErr, ok := err.(error)
if !ok {
asErr = fmt.Errorf("%v", err)
}
httputils.HandleError(s, ctx, asErr)
}
}()
ctx.Next()
}