|
12345678910111213141516171819202122232425262728293031323334353637383940 |
- package auth
-
- import (
- "fmt"
- "net/http"
- "strings"
-
- "github.com/golang-jwt/jwt/v4"
- "github.com/spf13/viper"
- )
-
- type Claims struct {
- ID uint `json:"id"`
- Username string `json:"username"`
- Privileges uint `json:"privileges"`
- jwt.RegisteredClaims
- }
-
- func GetUserClaims(r *http.Request) (rights *Claims, err error) {
- var token *jwt.Token
- authHeader := r.Header.Get("Authorization")
- if authHeader == "" {
- return nil, nil
- }
-
- claims := &Claims{}
-
- _, t, _ := strings.Cut(r.Header.Get("Authorization"), "Bearer ")
- token, _ = jwt.ParseWithClaims(t, claims, func(token *jwt.Token) (interface{}, error) {
- if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
- return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
- }
-
- return []byte(viper.GetString("app.secretKey")), nil
- })
- if !token.Valid {
- return nil, nil
- }
- return claims, nil
- }
|