Refactor: Implement user removal in Python

This commit is contained in:
Whispering Wind
2025-05-02 11:40:57 +03:30
committed by GitHub
parent 8d9fda0c09
commit 7e71b1c33b
3 changed files with 59 additions and 30 deletions

View File

@ -26,7 +26,7 @@ class Command(Enum):
ADD_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'add_user.sh')
EDIT_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'edit_user.sh')
RESET_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'reset_user.sh')
REMOVE_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'remove_user.sh')
REMOVE_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'remove_user.py')
SHOW_USER_URI = os.path.join(SCRIPT_DIR, 'hysteria2', 'show_user_uri.py')
WRAPPER_URI = os.path.join(SCRIPT_DIR, 'hysteria2', 'wrapper_uri.py')
IP_ADD = os.path.join(SCRIPT_DIR, 'hysteria2', 'ip.sh')
@ -303,7 +303,7 @@ def remove_user(username: str):
'''
Removes a user by username.
'''
run_cmd(['bash', Command.REMOVE_USER.value, username])
run_cmd(['python3', Command.REMOVE_USER.value, username])
def kick_user_by_name(username: str):
'''Kicks a specific user by username.'''

View File

@ -0,0 +1,57 @@
#!/usr/bin/env python3
import json
import sys
import os
import asyncio
from init_paths import *
from paths import *
async def remove_user(username):
"""
Remove a user from the USERS_FILE asynchronously.
Args:
username (str): The username to remove
Returns:
int: 0 on success, 1 on failure
"""
if not os.path.isfile(USERS_FILE):
print(f"Error: Config file {USERS_FILE} not found.")
return 1
try:
async with asyncio.to_thread(open, USERS_FILE, 'r') as f:
try:
users_data = json.load(f)
except json.JSONDecodeError:
print(f"Error: {USERS_FILE} contains invalid JSON.")
return 1
if username in users_data:
del users_data[username]
async with asyncio.to_thread(open, USERS_FILE, 'w') as f:
json.dump(users_data, f, indent=4)
print(f"User {username} removed successfully.")
else:
print(f"Error: User {username} not found.")
return 1
except Exception as e:
print(f"Error: {str(e)}")
return 1
return 0
async def main():
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <username>")
sys.exit(1)
username = sys.argv[1]
exit_code = await remove_user(username)
sys.exit(exit_code)
if __name__ == "__main__":
asyncio.run(main())

View File

@ -1,28 +0,0 @@
#!/bin/bash
source /etc/hysteria/core/scripts/path.sh
source /etc/hysteria/core/scripts/utils.sh
define_colors
remove_user() {
if [ $# -ne 1 ]; then
echo "Usage: $0 <username>"
exit 1
fi
local username=$1
if [ -f "$USERS_FILE" ]; then
if jq -e "has(\"$username\")" "$USERS_FILE" > /dev/null; then
jq --arg username "$username" 'del(.[$username])' "$USERS_FILE" > "${USERS_FILE}.temp" && mv "${USERS_FILE}.temp" "$USERS_FILE"
echo "User $username removed successfully."
else
echo -e "${red}Error:${NC} User $username not found."
fi
else
echo -e "${red}Error:${NC} Config file $USERS_FILE not found."
fi
}
# python3 "$CLI_PATH" restart-hysteria2 > /dev/null 2>&1
remove_user "$1"