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

optional_auth.go 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package auth
  2. import (
  3. "net/http"
  4. "fmt"
  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 tokenFromCookie, tokenFromHeader string
  11. tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
  12. if err == http.ErrNoCookie {
  13. tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
  14. }
  15. if tokenFromHeader == "" {
  16. tokenFromHeader = "Bearer " + tokenFromCookie
  17. }
  18. if len(tokenFromHeader) > 7 {
  19. token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
  20. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  21. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  22. }
  23. return []byte(authKey), nil
  24. })
  25. if err != nil || !token.Valid {
  26. return
  27. }
  28. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  29. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  30. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  31. }
  32. }
  33. }
  34. }
  35. }
  36. func OptionalCloudTeamAuth(authKey string) gin.HandlerFunc {
  37. return func(ctx *gin.Context) {
  38. var tokenFromCookie, tokenFromHeader string
  39. tokenFromCookie, err := ctx.Cookie(ctxRequestCookieAuthorization)
  40. if err == http.ErrNoCookie {
  41. tokenFromHeader = ctx.Request.Header.Get(ctxRequestHeaderAuthorization)
  42. }
  43. if tokenFromHeader == "" {
  44. tokenFromHeader = "Bearer " + tokenFromCookie
  45. }
  46. if len(tokenFromHeader) > 7 {
  47. token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
  48. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  49. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  50. }
  51. return []byte(authKey), nil
  52. })
  53. if err != nil || !token.Valid {
  54. return
  55. }
  56. if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
  57. if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
  58. ctx.Set(CtxRequestHeaderUserId, int64(uid))
  59. }
  60. if tid, ok := mapClaims[CtxRequestHeaderTeamId].(float64); ok {
  61. ctx.Set(CtxRequestHeaderTeamId, int64(tid))
  62. }
  63. if rid, ok := mapClaims[CtxRequestHeaderRoleId].(float64); ok {
  64. ctx.Set(CtxRequestHeaderRoleId, int64(rid))
  65. }
  66. }
  67. }
  68. }
  69. }