Skip to content

Commit 0ed23a4

Browse files
committed
Add a module to manage user credentials and access.
1 parent eb0238f commit 0ed23a4

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

manage_users.py

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import sys
2+
import string
3+
import subprocess
4+
import json
5+
from random import choice
6+
from os.path import isfile
7+
from time import time
8+
9+
DEFAULT_RAND_STR_SIZE = 10
10+
DEFAULT_RAND_STR_CHARS = string.lowercase + string.uppercase + string.digits
11+
12+
USER_PREFIX = "census_user_"
13+
USER_JSON = "census_data_users.json"
14+
HTPASSWDFILE = "../.htpasswd-data-release"
15+
MONTH_IN_S = 30*24*3600 # month as seconds
16+
17+
18+
def read_json(json_path):
19+
return json.load(open(json_path))
20+
21+
22+
def dump_as_json(obj, json_path):
23+
with open(json_path, 'w') as f:
24+
json.dump(obj, f)
25+
26+
27+
def rand_str(size=DEFAULT_RAND_STR_SIZE, chars=DEFAULT_RAND_STR_CHARS):
28+
"""Return random string given a size and character space."""
29+
return ''.join(choice(chars) for _ in range(size))
30+
31+
32+
def get_expiry():
33+
return int(time() + MONTH_IN_S)
34+
35+
36+
def generate_username():
37+
return USER_PREFIX + rand_str(6)
38+
39+
40+
def generate_password():
41+
return rand_str(16)
42+
43+
44+
def delete_from_htpasswd(username):
45+
print subprocess.call(["htpasswd", "-D", HTPASSWDFILE, username])
46+
47+
48+
def update_user_expiry_db(username):
49+
users = {}
50+
if isfile(USER_JSON):
51+
users = read_json(USER_JSON)
52+
users[username] = get_expiry()
53+
dump_as_json(users, USER_JSON)
54+
print "Added: " + username + " Current # users", len(users)
55+
56+
57+
def revoke_expired_accounts():
58+
expired_usernames = set()
59+
users = read_json(USER_JSON)
60+
now = time()
61+
for username, expiry_time in users.iteritems():
62+
if now > expiry_time:
63+
expired_usernames.add(username)
64+
for expired_username in expired_usernames:
65+
print "Revoking expired account", expired_username
66+
users.pop(expired_username)
67+
delete_from_htpasswd(expired_username)
68+
dump_as_json(users, USER_JSON)
69+
70+
71+
def add_new_user():
72+
username = generate_username()
73+
update_user_expiry_db(username)
74+
password = generate_password()
75+
print "Username: %s\nPassword: %s" % (username, password)
76+
subprocess.call(["htpasswd", "-b", HTPASSWDFILE, username, password])
77+
78+
79+
# USAGE
80+
# Add a new user:
81+
# python manage_users add
82+
83+
# Remove expired users
84+
# python manage_users revoke
85+
86+
87+
if __name__ == '__main__':
88+
command = sys.argv[1]
89+
if command == "revoke":
90+
revoke_expired_accounts()
91+
elif command == "add":
92+
add_new_user()
93+
else:
94+
print "Unknown command"

0 commit comments

Comments
 (0)