-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
44 lines (35 loc) · 993 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
package auth
import (
"net/http"
"os"
"github.com/dgrijalva/jwt-go"
"github.com/ericktm/olivsoft-golang-api/common"
"github.com/gin-gonic/gin"
)
// Middleware to validate Authorization Headers
// TODO: Use JWT
func Middleware() gin.HandlerFunc {
envToken := os.Getenv("APP_TOKEN")
return func(c *gin.Context) {
cookie, err := c.Cookie(common.AuthCookie)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, common.ErrorMessage{Message: "auth cookie missing"})
return
}
claims := &Jwt{}
tkn, err := jwt.ParseWithClaims(cookie, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(envToken), nil
})
if err != nil {
println(err.Error())
c.AbortWithStatusJSON(http.StatusUnauthorized, common.ErrorMessage{Message: err.Error()})
return
}
if !tkn.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, common.ErrorMessage{Message: "invalid token"})
return
}
c.Set(common.LoggedUser, claims.User)
c.Next()
}
}