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

auth.go 1.7KB

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