diff options
| author | zberwaldt <17715430+zberwaldt@users.noreply.github.com> | 2024-03-15 22:03:11 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-03-15 22:03:11 -0400 |
| commit | 6f8cfbd6cc3d5adbda38e74013c68e3d4745766d (patch) | |
| tree | b3f045cd06d6622e23441b442e8f3861050ed444 /api/internal/middleware | |
| parent | fac21fa0a72d4a7f1a01ccd44e3acf9c90fd95bd (diff) | |
| parent | fd1332a3df191577e91c6d846a8b5db1747099fd (diff) | |
Merge pull request #1 from zberwaldt/staging
Staging to Prod
Diffstat (limited to 'api/internal/middleware')
| -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 | } | ||
