Skip to content

Commit

Permalink
feat: rename list_users to list_privileged_users, add auth_type in au…
Browse files Browse the repository at this point in the history
…th.py and improve list user command in cli

rename list_users to list_privileged_users to match the function effective behavior (that list only users from privileged_users table
add auth_type function to check the kind of autentication selected (it returns a string)
the function list_users_guests_and_privileges now join with credential table only if basic authentication is active (since credential table has a real effect only for basic authentication)
improve cli 'users list' command
  • Loading branch information
Michele-Alberti committed Jan 2, 2025
1 parent 1ed93f5 commit d4b6a19
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 22 deletions.
45 changes: 35 additions & 10 deletions dlunch/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ def pn_user(config: DictConfig) -> str:


def is_basic_auth_active(config: DictConfig) -> bool:
"""Check config object and return `True` if basic authentication is active.
"""Check configuration object and return `True` if basic authentication is active.
Return `False` otherwise.
Args:
Expand All @@ -440,7 +440,7 @@ def is_basic_auth_active(config: DictConfig) -> bool:


def is_auth_active(config: DictConfig) -> bool:
"""Check configuration dictionary and return `True` if basic authentication or OAuth is active.
"""Check configuration object and return `True` if basic authentication or OAuth is active.
Return `False` otherwise.
Args:
Expand All @@ -452,11 +452,32 @@ def is_auth_active(config: DictConfig) -> bool:

# Check if a valid auth key exists
auth_provider = is_basic_auth_active(config=config)
oauth_provider = config.server.get("oauth_provider", None)
oauth_provider = config.server.get("oauth_provider", None) is not None

return auth_provider or oauth_provider


def auth_type(config: DictConfig) -> str | None:
"""Check configuration object and return authentication type.
Args:
config (DictConfig): Hydra configuration dictionary.
Returns:
str | None: authentication type. None if no authentication is active.
"""

# Check if a valid auth key exists
if is_basic_auth_active(config=config):
auth_type = "basic"
elif config.server.get("oauth_provider", None) is not None:
auth_type = config.server.oauth_provider
else:
auth_type = None

return auth_type


def authorize(
config: DictConfig,
user_info: dict,
Expand Down Expand Up @@ -486,7 +507,7 @@ def authorize(

# Set current user from panel state
current_user = pn_user(config)
privileged_users = list_users(config=config)
privileged_users = list_privileged_users(config=config)
log.debug(f"target path: {target_path}")
# If user is not authenticated block it
if not current_user:
Expand Down Expand Up @@ -660,7 +681,7 @@ def remove_user(user: str, config: DictConfig) -> dict:
}


def list_users(config: DictConfig) -> list[str]:
def list_privileged_users(config: DictConfig) -> list[str]:
"""List only privileged users (from `privileged_users` table).
Args:
Expand Down Expand Up @@ -706,10 +727,14 @@ def list_users_guests_and_privileges(config: DictConfig) -> pd.DataFrame:
config=config,
index_col="user",
)
df_credentials = models.Credentials.read_as_df(
config=config,
index_col="user",
)
# Leave credentials table empty if basic auth is not active
if is_basic_auth_active(config=config):
df_credentials = models.Credentials.read_as_df(
config=config,
index_col="user",
)
else:
df_credentials = pd.DataFrame()
# Change admin column to privileges (used after join)
df_privileged_users["group"] = df_privileged_users.admin.map(
{True: "admin", False: "user"}
Expand Down Expand Up @@ -759,7 +784,7 @@ def is_guest(
return True

# Otherwise check if user is not included in privileged users
privileged_users = list_users(config)
privileged_users = list_privileged_users(config)

is_guest = user not in privileged_users

Expand Down
47 changes: 37 additions & 10 deletions dlunch/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,46 @@ def cli(ctx, hydra_overrides: tuple | None):
@cli.group()
@click.pass_obj
def users(obj):
"""Manage privileged users and admin privileges."""
"""Manage privileged users and their group."""


@users.command("list")
@click.option(
"--privileged-only",
"list_only_privileged_users",
is_flag=True,
help="list only privileged users (without group)",
)
@click.pass_obj
def list_users_name(obj):
"""List users."""
def list_users(obj, list_only_privileged_users):
"""List users and privileges."""

# Define padding function
def _left_justify(df):
df = df.astype(str).str.strip()
return df.str.ljust(df.str.len().max())

# Auth settings
auth_type = auth.auth_type(config=obj["config"]) or "not active"
click.secho("AUTH SETTINGS", fg="yellow", bold=True)
click.secho(f"authentication: {auth_type}\n")

# List user
click.secho("USERS", fg="yellow", bold=True)
if list_only_privileged_users:
users = auth.list_privileged_users(config=obj["config"])
click.secho("user", fg="cyan")
click.secho("\n".join(users))
else:
df_users = auth.list_users_guests_and_privileges(config=obj["config"])
df_users = (
df_users.reset_index()
.apply(_left_justify)
.to_string(index=False, justify="left")
)
click.secho(df_users.split("\n")[0], fg="cyan")
click.secho("\n".join(df_users.split("\n")[1:]))

# Clear action
usernames = auth.list_users(config=obj["config"])
click.secho("USERS:")
click.secho("\n".join(usernames), fg="yellow")
click.secho("\nDone", fg="green")


Expand Down Expand Up @@ -373,13 +401,12 @@ def generate_secrets(obj):
"""Generate secrets for DATA_LUNCH_COOKIE_SECRET and DATA_LUNCH_OAUTH_ENC_KEY env variables."""

try:
click.secho("Print secrets\n", fg="yellow")
result_secret = subprocess.run(
["panel", "secret"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
click.secho("COOKIE SECRET:", fg="yellow")
click.secho("\nCOOKIE SECRET:", fg="yellow", bold=True)
click.secho(
f"{result_secret.stdout.decode('utf-8')}",
fg="cyan",
Expand All @@ -389,7 +416,7 @@ def generate_secrets(obj):
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
click.secho("ENCRIPTION KEY:", fg="yellow")
click.secho("ENCRIPTION KEY:", fg="yellow", bold=True)
click.secho(
f"{result_encription.stdout.decode('utf-8')}",
fg="cyan",
Expand Down
6 changes: 4 additions & 2 deletions dlunch/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,9 @@ def send_order(
username_key_press
not in (
name
for name in auth.list_users(config=self.config)
for name in auth.list_privileged_users(
config=self.config
)
if name != "guest"
)
)
Expand Down Expand Up @@ -849,7 +851,7 @@ def delete_order(
)
and (
username_key_press
in auth.list_users(config=self.config)
in auth.list_privileged_users(config=self.config)
)
and (auth.is_auth_active(config=self.config))
):
Expand Down

0 comments on commit d4b6a19

Please sign in to comment.