-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathusercrud.py
More file actions
216 lines (184 loc) · 5.78 KB
/
usercrud.py
File metadata and controls
216 lines (184 loc) · 5.78 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 5 11:39:27 2017
Modified May 31, 2018
Modified Apr 18, 2019
Modified Apr 2, 2020
Modified Apr 3, 2020
@author: Kirby Urner
usercrud.py is about doing basic...
Creating
Retrieving
Updating
Deleting
plus...
Authenticating
w/r to a Users table. Good review of DB API.
Designed for interactive use from the REPL.
We'll use connector.py for our db connection.
"""
from connector import DB
import hashlib
import os
# modify this to suit, like settings.py
PATH = "./data"
filepath = os.path.join(PATH, "users.db")
def check_tables():
with DB(filepath) as db:
db.curs.execute("SELECT * FROM sqlite_master where type='table'")
results = db.curs.fetchall()
if results and "Users" in results[0]:
return True
else:
print("No Users table")
return False
def fetch_all():
with DB(filepath) as db:
if check_tables():
db.curs.execute("SELECT * FROM Users")
results = db.curs.fetchall()
if results:
return tuple(results)
else:
print("Users table empty")
else:
print("No table")
def fetch_one(user_name):
with DB(filepath) as db:
if check_tables():
db.curs.execute("SELECT * FROM Users "
"WHERE username = ?",
(user_name,))
try:
results = db.curs.fetchone()
if results:
return tuple(results)
else:
print("Not found")
except TypeError:
return None
else:
print("No table")
def zap_table():
with DB(filepath) as db:
db.curs.execute("DROP TABLE IF EXISTS Users")
def create_table():
if check_tables():
return "Table already exists"
else:
with DB(filepath) as db:
db.curs.execute("CREATE TABLE Users "
"(username text, "
"password text)")
print("Table created")
def add_one(user_name, pw):
with DB(filepath) as db:
if check_tables():
if fetch_one(user_name):
print("User already exists")
return
hashpw = hashlib.sha256(bytes(pw, encoding='utf-8')).hexdigest()
db.curs.execute("INSERT INTO Users "
"(username, password) "
"VALUES (?, ?)",
(user_name, hashpw))
db.conn.commit()
print("User added")
else:
print("No tables")
def delete_one(user_name):
with DB(filepath) as db:
if not check_tables():
return
if not fetch_one(user_name):
print("User does not exists")
return
db.curs.execute("DELETE FROM Users "
"WHERE username = ? ",
(user_name,))
db.conn.commit()
print("User deleted")
def change_one(user_name, newpw):
# http://www.sqlitetutorial.net/sqlite-update/
with DB(filepath) as db:
if not check_tables():
return
if not fetch_one(user_name):
print("User does not exists")
return
# pass to placeholders in right order!
hashpw = hashlib.sha256(bytes(newpw, encoding='utf-8')).hexdigest()
db.curs.execute("UPDATE Users "
"SET password = ? "
"WHERE username = ? ",
(hashpw, user_name))
db.conn.commit()
print("Info changed")
def auth(user_name, pw=None):
if not pw:
pw = input("What is the password? : ")
if not pw:
return
hashpw = hashlib.sha256(bytes(pw, encoding='utf-8')).hexdigest()
got_one = fetch_one(user_name)
if got_one:
if got_one[1] == hashpw:
print("Access Allowed!")
else:
print("Access Denied")
# used when input prompts are needed
# This module was originally meant to be imported
# and used interactively after being imported.
# Later I decided to add this additional functions
# for operating usercrud.py from the command line
def fetch():
try:
who = input("User? > ")
result = fetch_one(who)
print("{}: {}".format(*result))
except TypeError:
print("build and addone before fetching")
def fetchall():
try:
for rec in fetch_all():
print("{}: {}".format(*rec))
except TypeError:
print("build and addone before fetching")
def authenticate():
who = input("User? > ")
pw = input("Password? > ")
auth(who, pw)
def addone():
who = input("User? > ")
pw = input("Password? > ")
add_one(who, pw)
def remone():
who = input("User? > ")
delete_one(who)
def the_help():
print("$ python -m usercrud name\n"
"where name is:\n",
" ".join(menu_options.keys()) + "\n",
"If you zap, you need to build before you addone\n")
menu_options = {
"fetchone": fetch,
"fetchall": fetchall,
"addone": addone,
"remove": remone,
"auth": authenticate,
"build": create_table,
"zap": zap_table,
"--help": the_help,
"-h": the_help}
if __name__ == "__main__":
import sys
if len(sys.argv)>1:
requested_op = sys.argv[1]
# print sys.argv
if requested_op in menu_options:
# don't just eval() whatever is passed in!
# print("Selected: ", requested_op)
menu_options[requested_op]()
else:
the_help()