auth.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package headutil
  2. import (
  3. "Cold_Logistic/internal/pkg/common/constant"
  4. "encoding/base64"
  5. "strings"
  6. "gogs.baozhida.cn/Cold_Logistic_libs/pkg/contrib/util/sliceutil"
  7. "github.com/gin-gonic/gin"
  8. "gogs.baozhida.cn/Cold_Logistic_libs/pkg/contrib/errors"
  9. )
  10. // ParseAuthHead 解析请求头中Authorization,返回tokenType, Token
  11. func ParseAuthHead(c *gin.Context) (tokenType, token string, e error) {
  12. authHeader := strings.SplitN(c.Request.Header.Get(constant.Authorization), " ", 2)
  13. if len(authHeader) != 2 || authHeader[1] == "" || !sliceutil.ContainStr([]string{constant.AuthTokenTypeBasic, constant.AuthTokenTypeBearer}, authHeader[0]) {
  14. return "", "", errors.New("Authorization header format is wrong")
  15. }
  16. return authHeader[0], authHeader[1], nil
  17. }
  18. // ParseBasicToken 解析BasicToken,返回账号, 密码
  19. func ParseBasicToken(token string) (username, password string, err error) {
  20. payload, err := base64.StdEncoding.DecodeString(token)
  21. if err != nil {
  22. return "", "", err
  23. }
  24. pair := strings.SplitN(string(payload), ":", 2)
  25. if len(pair) != 2 {
  26. return "", "", errors.New("Parse Basic Payload Error")
  27. }
  28. return pair[0], pair[1], nil
  29. }