-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
81 lines (71 loc) · 2.34 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
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
// func OptionsMiddleWare(c *gin.Context) {
// if c.Request.Method != "OPTIONS" {
// c.Next()
// } else {
// c.Header("Access-Control-Allow-Origin", "*")
// c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
// c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept, X-API-KEY, x-api-key")
// c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
// c.Header("Content-Type", "application/json")
// c.AbortWithStatus(http.StatusOK)
// }
// }
func requireAuth(c *gin.Context) {
tokenString := c.Request.Header.Get("X-API-KEY")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
c.AbortWithStatus(http.StatusUnauthorized)
}
return []byte(secretKEY), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
if float64(time.Now().Unix()) > claims["expiry"].(float64) {
c.AbortWithStatus(http.StatusUnauthorized)
}
//db := openDB()
c.Set("userID", uint(claims["sub"].(float64)))
} else {
fmt.Println(err)
}
c.Next()
}
func googleAuth(c *gin.Context) {
tokenString := c.Query("state")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
c.AbortWithStatus(http.StatusUnauthorized)
}
return []byte(secretKEY), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
if float64(time.Now().Unix()) > claims["expiry"].(float64) {
c.AbortWithStatus(http.StatusUnauthorized)
}
//db := openDB()
c.Set("userID", uint(claims["sub"].(float64)))
} else {
fmt.Println(err)
}
c.Next()
}
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
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, x-api-key")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}