| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 | 
							- package auth
 - 
 - import (
 - 	"fmt"
 - 	"github.com/dgrijalva/jwt-go"
 - 	"github.com/gin-gonic/gin"
 - 	"net/http"
 - )
 - 
 - func OptionalAuth(authKey string) gin.HandlerFunc {
 - 	return func(ctx *gin.Context) {
 - 		var tokenFromCookie, tokenFromHeader string
 - 
 - 		tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
 - 		if err != nil {
 - 			if err == http.ErrNoCookie {
 - 				tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
 - 			}
 - 		}
 - 
 - 		if tokenFromHeader == "" {
 - 			tokenFromHeader = "Bearer " + tokenFromCookie
 - 		}
 - 
 - 		if len(tokenFromHeader) < 8 {
 - 			ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
 - 			return
 - 		}
 - 
 - 		token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
 - 			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
 - 				return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
 - 			}
 - 
 - 			return []byte(authKey), nil
 - 		})
 - 
 - 		if err != nil || !token.Valid {
 - 			return
 - 		}
 - 
 - 		if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
 - 			if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
 - 				ctx.Set(CtxRequestHeaderUserId, int64(uid))
 - 			}
 - 		}
 - 	}
 - }
 
 
  |