async def create_route(name: str) -> None: """Create an API route entry for authorization.""" try: await ApiRoute.create(name=name) except IntegrityError: raise StatsError(f"Route '{name}' already exists") from None log.success("Added route {}", name)
async def _remote_call(method: str, job_id: int, job_name: str, *args, **kwargs): log.info("Job {}: Starting {}", job_id, job_name) result = None try: connection: Connection = rpyc.connect( params.policy_server.host, params.policy_server.port, ipv6=True, ) call = getattr(connection.root, method) result = call(*args, **kwargs) if isinstance(result, str): message = result elif isinstance(result, (Sequence, Generator)): message = ", ".join(result) else: message = "" await update_job(job_id, detail=message) except (ConnectionRefusedError, gaierror) as err: log.error(str(err)) await update_job(job_id, in_progress=False, detail=str(err)) raise StatsError(str(err)) except TimeoutError as err: await update_job(job_id, in_progress=False, detail=str(err)) log.error(str(err)) pass await complete_job(job_id) log.success("Job: {}: Completed {}", job_id, job_name)
async def create_user(username: str, password: str) -> None: """Create an API user.""" hashed_password = argon2.hash(password) try: await ApiUser.create(username=username, password=hashed_password) except IntegrityError: raise AuthError("User '{u}' already exists.", u=username, status_code=409) from None log.success("Added user {}", username)
async def _change_route(username: str, routes: Union[str, List[str]], action: str) -> None: """Associate or disassociate a route from a user.""" user = await get_user(username) if isinstance(routes, str): routes = [routes] if action == "add": coro = user.routes.add msg = "Added route {} to user {}" elif action == "remove": coro = user.routes.remove msg = "Removed route {} from user {}" else: raise StatsError(f"Action {action} is not supported") for route in routes: matched = await get_route(route) await coro(matched) log.success(msg, route, user.username)
async def delete_route(route) -> None: """Delete an API route.""" _route = await get_route(route) await _route.delete() log.success("Deleted route {}", route)
async def delete_user(username) -> None: """Delete an API user.""" user = await get_user(username) await user.delete() log.success("Deleted user {}", username)