123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- package auth
-
- import (
- "net/http"
-
- "fmt"
- "github.com/dgrijalva/jwt-go"
- "github.com/gin-gonic/gin"
- )
-
- func OptionalAuth(authKey string) gin.HandlerFunc {
- return func(ctx *gin.Context) {
- var tokenFromCookie, tokenFromHeader string
-
- tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
- if err == http.ErrNoCookie {
- tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
- }
-
- if tokenFromHeader == "" {
- tokenFromHeader = "Bearer " + tokenFromCookie
- }
-
- if len(tokenFromHeader) > 7 {
- 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))
- }
- }
- }
- }
- }
|