-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
89 lines (66 loc) · 1.72 KB
/
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
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
package utils
import (
"net/http"
"os"
"strconv"
"github.com/go-playground/validator/v10"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/jwt"
)
func UserIDMiddleware(ctx iris.Context) {
params := ctx.Params()
id := params.Get("id")
claims := jwt.Get(ctx).(*AccessToken)
userID := strconv.FormatUint(uint64(claims.ID), 10)
if userID != id {
ctx.StatusCode(iris.StatusForbidden)
return
}
ctx.Next()
}
func AccessTokenVerifierMiddleware(ctx iris.Context) {
auth := ctx.GetHeader("Authorization")
if auth == "" {
ctx.StatusCode(http.StatusUnauthorized)
ctx.JSON(iris.Map{"error": "No authorization header"})
return
}
token := auth[7:] // Remove "Bearer " prefix
verifier := jwt.NewVerifier(jwt.HS256, []byte(os.Getenv("ACCESS_TOKEN_SECRET")))
verifier.WithDefaultBlocklist()
verifiedToken, err := verifier.VerifyToken([]byte(token))
if err != nil {
ctx.StatusCode(http.StatusUnauthorized)
ctx.JSON(iris.Map{"error": "Invalid token"})
return
}
var customClaims AccessToken
if err := verifiedToken.Claims(&customClaims); err != nil {
ctx.StatusCode(http.StatusUnauthorized)
ctx.JSON(iris.Map{"error": "Invalid token claims"})
return
}
// Set user ID in context
ctx.Values().Set("userID", customClaims.ID)
ctx.Next()
}
func GetUserFromToken(ctx iris.Context) *AccessToken {
token := jwt.Get(ctx)
if token == nil {
return nil
}
claims, ok := token.(*AccessToken)
if !ok {
return nil
}
return claims
}
// TokenPair represents both access and refresh tokens
type TokenPair struct {
AccessToken []byte
RefreshToken []byte
}
func AddCustomValidation(tag string, fn validator.Func) {
validate := validator.New()
validate.RegisterValidation(tag, fn)
}