The backend for the project formerly known as signet, now known as beignet.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package auth
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/golang-jwt/jwt/v4"
  7. "github.com/spf13/viper"
  8. )
  9. type Claims struct {
  10. ID uint `json:"id"`
  11. Username string `json:"username"`
  12. Privileges uint `json:"privileges"`
  13. jwt.RegisteredClaims
  14. }
  15. func GetUserClaims(r *http.Request) (rights *Claims, err error) {
  16. var token *jwt.Token
  17. authHeader := r.Header.Get("Authorization")
  18. if authHeader == "" {
  19. return nil, nil
  20. }
  21. claims := &Claims{}
  22. _, t, _ := strings.Cut(r.Header.Get("Authorization"), "Bearer ")
  23. token, _ = jwt.ParseWithClaims(t, claims, func(token *jwt.Token) (interface{}, error) {
  24. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  25. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  26. }
  27. return []byte(viper.GetString("app.secretKey")), nil
  28. })
  29. if !token.Valid {
  30. return nil, nil
  31. }
  32. return claims, nil
  33. }