liuxiaolong
2019-06-15 1efc7ae174f57e6a0a96ccfe4efadc9390589b5a
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
package middlewares
 
import (
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "github.com/gin-gonic/gin"
    "strings"
)
 
func AuthHandler() gin.HandlerFunc {
    return func(c *gin.Context) {
        token := c.Request.Header.Get("Authorization")
        // Check if toke in correct format
        // ie Bearer: xx03xllasx
        b := "Bearer "
        if !strings.Contains(token, b) {
            c.JSON(403, gin.H{"message": "Your request is not authorized"})
            c.Abort()
            return
        }
        t := strings.Split(token, b)
        if len(t) < 2 {
            c.JSON(403, gin.H{"message": "An authorization token was not supplied"})
            c.Abort()
            return
        }
        // Validate token
        valid, err := ValidateToken(t[1], SigningKey)
        if err != nil {
            fmt.Println("enter error")
            c.JSON(403, gin.H{"message": "Invalid authorization token"})
            c.Abort()
            return
        }
 
        // set userId Variable
        c.Set("userId", valid.Claims.(jwt.MapClaims)["user_id"])
        c.Next()
    }
}