openwebrx-clone/owrxadmin/commands.py

64 lines
2.3 KiB
Python
Raw Normal View History

2021-02-06 17:15:02 +00:00
from abc import ABC, ABCMeta, abstractmethod
2021-02-06 17:04:32 +00:00
from getpass import getpass
2021-02-06 17:22:13 +00:00
from owrx.users import UserList, User, DefaultPasswordClass
2021-02-06 17:04:32 +00:00
import sys
import random
import string
class Command(ABC):
@abstractmethod
def run(self, args):
pass
2021-02-06 17:15:02 +00:00
class UserCommand(Command, metaclass=ABCMeta):
def getUser(self, args):
2021-02-06 17:04:32 +00:00
if args.user:
2021-02-06 17:15:02 +00:00
return args.user
2021-02-06 17:04:32 +00:00
else:
if args.noninteractive:
print("ERROR: User name not specified")
sys.exit(1)
else:
2021-02-06 17:15:02 +00:00
return input("Please enter the user name: ")
class NewUser(UserCommand):
def run(self, args):
username = self.getUser(args)
2021-02-06 17:57:51 +00:00
userList = UserList()
# early test to bypass the password stuff if the user already exists
if username in userList:
raise KeyError("User {username} already exists".format(username=username))
2021-02-06 17:15:02 +00:00
2021-02-06 17:04:32 +00:00
if args.noninteractive:
print("Generating password for user {username}...".format(username=username))
password = self.getRandomPassword()
print('Password for {username} is "{password}".'.format(username=username, password=password))
# TODO implement this threat
print('This password is suitable for initial setup only, you will be asked to reset it on initial use.')
print('This password cannot be recovered from the system, please note it down now.')
else:
password = getpass("Please enter the password for {username}: ".format(username=username))
confirm = getpass("Please confirm password: ")
if password != confirm:
print("ERROR: Password mismatch.")
sys.exit(1)
print("Creating user {username}...".format(username=username))
2021-02-06 17:22:13 +00:00
user = User(name=username, enabled=True, password=DefaultPasswordClass(password))
2021-02-06 17:04:32 +00:00
userList.addUser(user)
def getRandomPassword(self, length=10):
printable = list(string.ascii_letters) + list(string.digits)
return ''.join(random.choices(printable, k=length))
2021-02-06 17:15:02 +00:00
class DeleteUser(UserCommand):
def run(self, args):
username = self.getUser(args)
print("Deleting user {username}...".format(username=username))
userList = UserList()
userList.deleteUser(username)