Skip to content

Commit

Permalink
Add include_user_obj kwarg to protected_route, which can be called as…
Browse files Browse the repository at this point in the history
… a decorator factory
  • Loading branch information
ethho committed Apr 19, 2024
1 parent d2e3c27 commit 9113a8c
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions pharus/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,46 @@
)


def protected_route(function: Callable) -> Callable:
def doublewrap(f):
'''
A decorator decorator, allowing the decorator to be used as:
@decorator(with, arguments, and=kwargs)
or
@decorator
Adapted from https://stackoverflow.com/a/14412901
'''
@wraps(f)
def new_dec(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
# actual decorated function
return f(args[0])
else:
# decorator arguments
return lambda realf: f(realf, *args, **kwargs)

return new_dec


@doublewrap
def protected_route(function: Callable, include_user_obj: bool = False) -> Callable:
"""
Protected route function decorator which authenticates requests.
This function should be decorated with doublewrap, allowing the decorator
to be used as:
@protected_route
or equivalently
@protected_route(include_user_obj=False)
If include_user_obj is set to True, then the wrapped function should
accept a kwarg user_obj which will contain the decoded JWT token.
Args:
function: Function to decorate, typically routes
Returns:
Function's output if JWT authetication is successful, otherwise return error message
Wrapped function
"""

@wraps(function)
Expand Down Expand Up @@ -93,6 +124,8 @@ def wrapper(**kwargs):
user=connect_creds["username"],
password=connect_creds["password"],
)
if include_user_obj:
kwargs.update(user_obj=connect_creds)
return function(connection, **kwargs)
except Exception as e:
return str(e), 401
Expand Down

0 comments on commit 9113a8c

Please sign in to comment.