diff --git a/amanuensis/cli.py b/amanuensis/cli.py index 69f0a74..0b40807 100644 --- a/amanuensis/cli.py +++ b/amanuensis/cli.py @@ -154,12 +154,32 @@ def command_user_list(args): user_dirs = os.listdir(config.prepend('user')) users = [] for uid in user_dirs: + if uid == "index.json": continue with config.json_ro('user', uid, 'config.json') as user: users.append(user) users.sort(key=lambda u: u['username']) for user in users: print("{0} {1} ({2})".format(user['uid'], user['displayname'], user['username'])) +@add_argument("--username", help="The user to change password for") +def command_user_passwd(args): + """Set a user's password""" + import getpass + import os + + import config + from user import User, get_user_by_username + + if not args.username: + args.username = input("Username: ") + uid = get_user_by_username(args.username) + if uid is None: + print("No user with username '{}'".format(args.username)) + return -1 + user = User(uid) + pw = getpass.getpass("Password: ") + user.set_password(pw) + @add_argument("--foo", action="store_true") def command_dump(args): """Dumps the global config or the config for the given lexicon""" diff --git a/amanuensis/config/__init__.py b/amanuensis/config/__init__.py index 72a2a18..e48d15c 100644 --- a/amanuensis/config/__init__.py +++ b/amanuensis/config/__init__.py @@ -57,6 +57,14 @@ def json_rw(*path): def new_user(user_json): user_dir = prepend("user", user_json['uid']) + # Create user dir and put config in it os.mkdir(user_dir) with config.loader.open_ex(os.path.join(user_dir, "config.json"), 'w') as f: json.dump(user_json, f, allow_nan=False, indent='\t') + # Ensure index exists + if not os.path.isdir(prepend('user', 'index.json')): + with open_ex(prepend('user', 'index.json'), 'w') as f: + json.dump({}, f) + # Update index + with json_rw('user', 'index.json') as j: + j[user_json['username']] = user_json['uid'] diff --git a/amanuensis/user.py b/amanuensis/user.py index 3e88df5..117aa1e 100644 --- a/amanuensis/user.py +++ b/amanuensis/user.py @@ -9,9 +9,20 @@ import config class User(): def __init__(self, uid): + if not os.path.isdir(config.prepend('user', uid)): + raise ValueError("No user with uid {}".format(uid)) self.uid = uid self.config = os.path.join('user', uid, 'config.json') + def set_password(self, pw): + h = generate_password_hash(pw) + with config.json_rw(self.config) as j: + j['password'] = h + + def check_password(self, pw): + with config.json_ro(self.config) as j: + return check_password_hash(j['password'], pw) + def valid_username(username): return re.match(r"^[A-Za-z0-9-_]{3,}$", username) is not None @@ -35,3 +46,7 @@ def create_user(username, displayname, email): } config.new_user(user_json) return User(uid) + +def get_user_by_username(username): + with config.json_ro('user', 'index.json') as index: + return index.get(username)