diff options
Diffstat (limited to 'api/internal/middleware/middleware.go')
-rw-r--r-- | api/internal/middleware/middleware.go | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/api/internal/middleware/middleware.go b/api/internal/middleware/middleware.go new file mode 100644 index 0000000..aa27fb8 --- /dev/null +++ b/api/internal/middleware/middleware.go | |||
@@ -0,0 +1,56 @@ | |||
1 | package middleware | ||
2 | |||
3 | import ( | ||
4 | "errors" | ||
5 | "log" | ||
6 | "net/http" | ||
7 | "strings" | ||
8 | |||
9 | "github.com/gin-gonic/gin" | ||
10 | ) | ||
11 | |||
12 | func TokenRequired() gin.HandlerFunc { | ||
13 | return func(c *gin.Context) { | ||
14 | _, err := checkForTokenInContext(c) | ||
15 | |||
16 | if err != nil { | ||
17 | c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) | ||
18 | c.Abort() | ||
19 | return | ||
20 | } | ||
21 | |||
22 | c.Next() | ||
23 | } | ||
24 | } | ||
25 | |||
26 | func CORSMiddleware() gin.HandlerFunc { | ||
27 | return func(c *gin.Context) { | ||
28 | c.Writer.Header().Set("Access-Control-Allow-Origin", "*") | ||
29 | c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") | ||
30 | c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") | ||
31 | c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, PATCH") | ||
32 | |||
33 | if c.Request.Method == "OPTIONS" { | ||
34 | log.Println(c.Request.Header) | ||
35 | c.AbortWithStatus(http.StatusNoContent) | ||
36 | return | ||
37 | } | ||
38 | |||
39 | c.Next() | ||
40 | } | ||
41 | } | ||
42 | |||
43 | func checkForTokenInContext(c *gin.Context) (string, error) { | ||
44 | authorizationHeader := c.GetHeader("Authorization") | ||
45 | if authorizationHeader == "" { | ||
46 | return "", errors.New("authorization header is missing") | ||
47 | } | ||
48 | |||
49 | parts := strings.Split(authorizationHeader, " ") | ||
50 | |||
51 | if len(parts) != 2 || parts[0] != "Bearer" { | ||
52 | return "", errors.New("invalid Authorization header format") | ||
53 | } | ||
54 | |||
55 | return parts[1], nil | ||
56 | } | ||