update logic and logging

This commit is contained in:
Mohamad Tahir 2023-10-30 16:53:34 +03:00
parent 4f258ba7f3
commit cabcbbb166
Signed by: MohamadTahir
GPG Key ID: 116FAB02D35512FA
2 changed files with 14 additions and 18 deletions

View File

@ -11,6 +11,6 @@ testData:
- userId1 - userId1
- userId2 - userId2
paths: paths:
- prefix: /v1/users - base: /v1/users
mustContain: testValue path: /testValue
- prefix: /v1/organizations - base: /v1/organizations

26
main.go
View File

@ -9,8 +9,8 @@ import (
) )
type Path struct { type Path struct {
Prefix string `json:"prefix,omitempty"` Base string `json:"base,omitempty"`
MustContain string `json:"mustContain,omitempty"` Path string `json:"path,omitempty"`
} }
type Config struct { type Config struct {
@ -38,8 +38,8 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
} }
for _, path := range config.Paths { for _, path := range config.Paths {
if path.Prefix == "" { if path.Base == "" {
return nil, fmt.Errorf("Paths.Prefix cannot be empty") return nil, fmt.Errorf("Paths.Base cannot be empty")
} }
} }
@ -54,11 +54,8 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
func (a *UsersBlocker) ServeHTTP(rw http.ResponseWriter, req *http.Request) { func (a *UsersBlocker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
userId := req.Header["X-Auth-User-Id"][0] userId := req.Header["X-Auth-User-Id"][0]
os.Stdout.WriteString("\n request Path ->") message := fmt.Sprintf("{requestPath: %s, userId: %s}\n", req.URL.Path, userId)
os.Stdout.WriteString(req.URL.Path + "\n") os.Stdout.WriteString(message)
os.Stdout.WriteString("\n userId ->")
os.Stdout.WriteString(userId + "\n")
var isUserBlocked bool var isUserBlocked bool
@ -74,14 +71,13 @@ func (a *UsersBlocker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
} }
for _, path := range a.paths { for _, path := range a.paths {
isPathBlocked := strings.HasPrefix(req.URL.Path, path.Prefix) blockedPath := path.Base + path.Path
isPathBlocked := strings.HasPrefix(req.URL.Path, blockedPath)
if isPathBlocked && path.MustContain != "" {
isPathBlocked = !strings.Contains(req.URL.Path, path.MustContain)
}
if isPathBlocked { if isPathBlocked {
http.Error(rw, "Forbidden", http.StatusForbidden) message := fmt.Sprintf("blocked path %s (matched with %s) for user %s", req.URL.Path, blockedPath, userId)
os.Stdout.WriteString(message)
http.Error(rw, message, http.StatusForbidden)
return return
} }
} }