-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
47 lines (41 loc) · 1.07 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
package middleware
import (
"fmt"
"net/http"
"github.com/PauloPortugal/gin-gonic-rest-mongodb/model"
"github.com/dgrijalva/jwt-go"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
type Client struct {
}
func (c Client) AuthJWTMiddleware(cfg *viper.Viper) gin.HandlerFunc {
return func(ctx *gin.Context) {
auth := ctx.GetHeader("Authorization")
claims := &model.Claims{}
tkn, err := jwt.ParseWithClaims(auth, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(fmt.Sprint(cfg.Get("auth.secret"))), nil
})
if err != nil {
ctx.AbortWithStatus(http.StatusUnauthorized)
}
if tkn == nil || !tkn.Valid {
ctx.AbortWithStatus(http.StatusUnauthorized)
}
ctx.Next()
}
}
func (c Client) AuthCookieMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
session := sessions.Default(ctx)
username := session.Get("username")
fmt.Print(username)
sessionToken := session.Get("token")
if sessionToken == nil {
ctx.JSON(http.StatusForbidden, "Not authorized")
ctx.Abort()
}
ctx.Next()
}
}