/
middleware.go
48 lines (40 loc) · 930 Bytes
/
middleware.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
package handler
import (
"errors"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
const (
authorizationHeader = "Authorization"
userCtx = "userId"
)
func (h *Handler) userIdentity(c *gin.Context) {
header := c.GetHeader(authorizationHeader)
if header == "" {
newErrorResponse(c, http.StatusUnauthorized, "empty auth header")
return
}
headerParts := strings.Split(header, " ")
if len(headerParts) != 2 {
newErrorResponse(c, http.StatusUnauthorized, "invalid auth header")
return
}
userId, err := h.services.ParseToken(headerParts[1])
if err != nil {
newErrorResponse(c, http.StatusUnauthorized, err.Error())
return
}
c.Set(userCtx, userId)
}
func getUserId(c *gin.Context) (int, error) {
id, ok := c.Get(userCtx)
if !ok {
return 0, errors.New("user id not found")
}
idInt, ok := id.(int)
if !ok {
return 0, errors.New("user id is of invalid type")
}
return idInt, nil
}