|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "durable_php/appcontext" |
| 6 | + "durable_php/config" |
| 7 | + "encoding/base64" |
| 8 | + "fmt" |
| 9 | + "github.com/golang-jwt/jwt/v4" |
| 10 | + "net/http" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +func getActiveKey(config *config.Config) []byte { |
| 16 | + key := config.Extensions.Authz.Secrets[len(config.Extensions.Authz.Secrets)-1] |
| 17 | + decoded, err := base64.StdEncoding.DecodeString(key) |
| 18 | + if err != nil { |
| 19 | + panic(err) |
| 20 | + } |
| 21 | + return decoded |
| 22 | +} |
| 23 | + |
| 24 | +func DecorateContextWithUser(ctx context.Context, user *User) context.Context { |
| 25 | + return context.WithValue(ctx, appcontext.CurrentUserKey, user) |
| 26 | +} |
| 27 | + |
| 28 | +func ExtractUser(r *http.Request, config *config.Config) (user *User, ok bool) { |
| 29 | + tokenString := r.Header.Get("Authorization") |
| 30 | + if tokenString == "" { |
| 31 | + return nil, false |
| 32 | + } |
| 33 | + |
| 34 | + tokenParts := strings.SplitN(tokenString, " ", 2) |
| 35 | + if tokenParts[0] != "Bearer" { |
| 36 | + return nil, false |
| 37 | + } |
| 38 | + |
| 39 | + token, err := jwt.Parse(tokenParts[1], func(token *jwt.Token) (interface{}, error) { |
| 40 | + if token.Method.Alg() != jwt.SigningMethodHS256.Alg() { |
| 41 | + return nil, fmt.Errorf("unexpected signing method") |
| 42 | + } |
| 43 | + |
| 44 | + return getActiveKey(config), nil |
| 45 | + }, jwt.WithValidMethods([]string{"HS256"})) |
| 46 | + if err != nil { |
| 47 | + return nil, false |
| 48 | + } |
| 49 | + |
| 50 | + getRoles := func(roles []interface{}) []Role { |
| 51 | + rolesSlice := make([]Role, len(roles)) |
| 52 | + for i, r := range roles { |
| 53 | + rolesSlice[i] = Role(r.(string)) |
| 54 | + } |
| 55 | + return rolesSlice |
| 56 | + } |
| 57 | + |
| 58 | + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { |
| 59 | + userId := claims["sub"].(string) |
| 60 | + rol := claims["roles"].([]interface{}) |
| 61 | + return &User{ |
| 62 | + UserId: UserId(userId), |
| 63 | + Roles: getRoles(rol), |
| 64 | + }, true |
| 65 | + } |
| 66 | + |
| 67 | + return nil, false |
| 68 | +} |
| 69 | + |
| 70 | +func CreateUser(userId UserId, role []Role, config *config.Config) (string, error) { |
| 71 | + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ |
| 72 | + "sub": userId, |
| 73 | + "exp": time.Now().Add(72 * time.Hour).Unix(), |
| 74 | + "iat": time.Now().Add(-5 * time.Minute).Unix(), |
| 75 | + "roles": role, |
| 76 | + }) |
| 77 | + |
| 78 | + signedString, err := token.SignedString(getActiveKey(config)) |
| 79 | + if err != nil { |
| 80 | + return "", err |
| 81 | + } |
| 82 | + |
| 83 | + return signedString, nil |
| 84 | +} |
0 commit comments