-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.py
More file actions
executable file
·79 lines (67 loc) · 2.12 KB
/
users.py
File metadata and controls
executable file
·79 lines (67 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
import glob
from getpass import getpass
from pathlib import Path
from flask_login import UserMixin
from werkzeug.security import generate_password_hash
USERS_DIR = "./users/"
PASSWD_MIN_LEN = 6
class User(UserMixin):
def __init__(self, id, username=None, hash=None):
self.id = id
self.name = username
self.hash = hash
@classmethod
def get_users(cls):
return [{"username": Path(file).stem,
"hash": open(file).read()
} for file in glob.glob(f"{USERS_DIR}/*.hash")]
@classmethod
def get(cls, user_id):
users = cls.get_users()
try:
index = int(user_id)
except ValueError:
return
if index < len(users):
return User(user_id, **users[index])
def create_user():
Path(USERS_DIR).mkdir(exist_ok=True)
users = [Path(file).stem for file in glob.glob(f"{USERS_DIR}/*.hash")]
while True:
username = input("Username: ")
if not username.isalnum():
print("Please use alphanumeric characters only")
continue
if username in users:
if input("This user already exists. Overwrite? (Y/n): ")\
.casefold() in ["", "y"]:
break
continue
break
while True:
password = getpass("Password (Won't be displayed): ")
if len(password) < PASSWD_MIN_LEN:
print(f"\nPassword must at least {PASSWD_MIN_LEN} characters long")
continue
password2 = getpass("Confirm Password: ")
if password != password2:
print("\nPasswords don't match. Try again")
continue
break
password_hash = generate_password_hash(password)
return [username, password_hash]
def save_user(user):
with open(f"{USERS_DIR}/{user[0]}.hash", "w") as f:
f.write(user[1])
def main():
print("ADDING NEW USER")
try:
user = create_user()
if user is None:
return
save_user(user)
except KeyboardInterrupt:
print("\nCancelling...")
if __name__ == "__main__":
main()