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

auth.go 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package auth
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/dgrijalva/jwt-go"
  6. "github.com/gin-gonic/gin"
  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 == http.ErrNoCookie {
  19. tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
  20. }
  21. if tokenFromHeader == "" {
  22. tokenFromHeader = "Bearer " + tokenFromCookie
  23. }
  24. if len(tokenFromHeader) < 8 {
  25. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  26. return
  27. }
  28. token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
  29. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  30. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  31. }
  32. return []byte(authKey), nil
  33. })
  34. if err != nil || !token.Valid {
  35. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
  36. return
  37. }
  38. if !session.IsExistsJwtToken(token.Raw) {
  39. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token expired by server"})
  40. return
  41. }
  42. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  43. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  44. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  45. } else {
  46. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderUserId].(float64) error"})
  47. return
  48. }
  49. } else {
  50. ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token.Claims.(jwt.MapClaims) error"})
  51. return
  52. }
  53. }
  54. }