|
| 1 | +package access |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rsa" |
| 5 | + "errors" |
| 6 | + "net/http" |
| 7 | +) |
| 8 | + |
| 9 | +var ( |
| 10 | + ErrEndpointNotRegistered = errors.New("endpoint not registered") |
| 11 | +) |
| 12 | + |
| 13 | +// Permissions = method + path (aka endpoint key) -> PermissionKey |
| 14 | +var Permissions = map[string]PermissionKey{} |
| 15 | + |
| 16 | +func Route(r *http.ServeMux, method, path string, permission PermissionKey, handler func(http.ResponseWriter, *http.Request)) { |
| 17 | + Permissions[method+path] = permission |
| 18 | + r.HandleFunc(method+" "+path, handler) |
| 19 | +} |
| 20 | + |
| 21 | +var HandlerGetUserPublicKey func(userID string) (*rsa.PublicKey, error) |
| 22 | +var HandlerGetPermissionsByUserID func(userID string) ([]Permission, error) |
| 23 | + |
| 24 | +// IsAuthorized returns error only if the process failed, not if it's not authorized. |
| 25 | +func IsAuthorized(w http.ResponseWriter, r *http.Request, metadata *string) (userID string, isAuthorized bool, err error) { |
| 26 | + endpointKey := r.Method + r.URL.Path |
| 27 | + |
| 28 | + permissionKey, ok := Permissions[endpointKey] |
| 29 | + if !ok { |
| 30 | + return "", false, ErrEndpointNotRegistered |
| 31 | + } |
| 32 | + |
| 33 | + userID, permissions, reject := AuthenticateAndAuthorize( |
| 34 | + w, |
| 35 | + r, |
| 36 | + permissionKey, |
| 37 | + metadata, |
| 38 | + HandlerGetUserPublicKey, |
| 39 | + HandlerGetPermissionsByUserID, |
| 40 | + ) |
| 41 | + |
| 42 | + _ = permissions |
| 43 | + |
| 44 | + if reject { |
| 45 | + return userID, false, nil |
| 46 | + } |
| 47 | + |
| 48 | + return userID, true, nil |
| 49 | +} |
0 commit comments