-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathexercise1.py
More file actions
94 lines (85 loc) · 2.62 KB
/
exercise1.py
File metadata and controls
94 lines (85 loc) · 2.62 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
import sqlite3
from werkzeug.security import generate_password_hash, check_password_hash
def create_user_table(conn):
"""Create table."""
cur = conn.cursor()
try:
sql = ("CREATE TABLE users ("
"userid INTEGER, "
"username VARCHAR(20) NOT NULL, "
"passwordhash VARCHAR(120) NOT NULL, "
"PRIMARY KEY(userid) "
"UNIQUE(username))")
cur.execute(sql)
conn.commit
except sqlite3.Error as err:
print("Error: {}".format(err))
else:
print("Table created.")
finally:
cur.close()
def add_user(conn, username, hash):
"""Add user. Returns the new user id"""
cur = conn.cursor()
try:
sql = ("INSERT INTO users (username, passwordhash) VALUES (?,?)")
cur.execute(sql, (username, hash))
conn.commit()
except sqlite3.Error as err:
print("Error: {}".format(err))
return -1
else:
print("User {} created with id {}.".format(username, cur.lastrowid))
return cur.lastrowid
finally:
cur.close()
def get_user_by_name(conn, username):
"""Get user details by name."""
cur = conn.cursor()
try:
sql = ("SELECT userid, username FROM users WHERE username = ?")
cur.execute(sql, (username,))
for row in cur:
(id,name,role) = row
return {
"username": name,
"userid": id
}
else:
#user does not exist
return {
"username": username,
"userid": None
}
except sqlite3.Error as err:
print("Error: {}".format(err))
finally:
cur.close()
def get_hash_for_login(conn, username):
"""Get user details from id."""
cur = conn.cursor()
try:
sql = ("SELECT passwordhash FROM users WHERE username=?")
cur.execute(sql, (username,))
for row in cur:
(passhash,) = row
return passhash
else:
return None
except sqlite3.Error as err:
print("Error: {}".format(err))
finally:
cur.close()
if __name__ == "__main__":
try:
conn = sqlite3.connect("database.db")
except sqlite3.Error as err:
print(err)
else:
#drop_table(conn)
create_user_table(conn)
add_user(conn,"johndoe", generate_password_hash("Joe123"))
add_user(conn,"maryjane", generate_password_hash("LoveDogs"))
hash = get_hash_for_login(conn, "maryjane")
print("Check password: {}".format(check_password_hash(hash,"LoveDogs")))
conn.close()