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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package auth
  2. import (
  3. "fmt"
  4. "github.com/dgrijalva/jwt-go"
  5. "github.com/gin-gonic/gin"
  6. "net/http"
  7. )
  8. const (
  9. CtxRequestHeaderUserId = "user_id"
  10. ctxRequestHeaderAuthorization = "Authorization"
  11. ctxRequestCookieAuthorization = "ak"
  12. ctxRequestTokenExpired = "expired"
  13. )
  14. func Auth(authKey string, session Session) gin.HandlerFunc {
  15. return func(ctx *gin.Context) {
  16. var tokenFromCookie, tokenFromHeader string
  17. tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
  18. if err != nil {
  19. if err == http.ErrNoCookie {
  20. tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
  21. }
  22. }
  23. if tokenFromHeader == "" {
  24. tokenFromHeader = "Bearer " + tokenFromCookie
  25. }
  26. if len(tokenFromHeader) < 8 {
  27. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  28. return
  29. }
  30. token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
  31. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  32. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  33. }
  34. return []byte(authKey), nil
  35. })
  36. if err != nil || !token.Valid {
  37. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  38. return
  39. }
  40. if !session.IsExistsJwtToken(token.Signature) {
  41. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token expired by server"})
  42. return
  43. }
  44. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  45. if expired, ok := mapClaims[ctxRequestTokenExpired].(float64); ok {
  46. if expired == 0 && tokenFromCookie == "" {
  47. if session.DeleteJwtToken(token.Raw) {
  48. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token expired"})
  49. } else {
  50. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, delete server token failed"})
  51. }
  52. return
  53. }
  54. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  55. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  56. } else {
  57. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderUserId].(float64) error"})
  58. return
  59. }
  60. } else {
  61. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[ctxRequestTokenExpired].(float64) error"})
  62. return
  63. }
  64. } else {
  65. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token.Claims.(jwt.MapClaims) error"})
  66. return
  67. }
  68. }
  69. }