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

optional_auth.go 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  34. if expired, ok := mapClaims[ctxRequestTokenExpired].(float64); ok {
  35. if int64(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. }
  42. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  43. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  44. }
  45. }
  46. }
  47. }