另客网go项目公用的代码库

optional_auth.go 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package auth
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/dgrijalva/jwt-go"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func OptionalAuth(authKey string) gin.HandlerFunc {
  9. return func(ctx *gin.Context) {
  10. var (
  11. err error
  12. tk = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
  13. )
  14. if tk == "" {
  15. tk, err = ctx.Cookie(ctxRequestCookieAuthorization)
  16. if err != nil {
  17. return
  18. }
  19. tk = "Bearer " + tk
  20. }
  21. if len(tk) < 8 {
  22. return
  23. }
  24. token, err := jwt.Parse(tk[7:], func(token *jwt.Token) (interface{}, error) {
  25. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  26. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  27. }
  28. return []byte(authKey), nil
  29. })
  30. if err != nil || !token.Valid {
  31. return
  32. }
  33. mapClaims := token.Claims.(jwt.MapClaims)
  34. expired := int64(mapClaims[ctxRequestTokenExpired].(float64))
  35. if expired < time.Now().Unix() {
  36. // Only cookie is blank value, check token expired
  37. if _, err := ctx.Cookie(ctxRequestCookieAuthorization); err != nil {
  38. return
  39. }
  40. }
  41. ctx.Set(CtxRequestHeaderUserId, int(mapClaims[CtxRequestHeaderUserId].(float64)))
  42. }
  43. }