· 6 years ago · Oct 07, 2019, 12:28 AM
1import hashlib
2import json
3import os
4import sqlite3
5from getpass import getpass
6
7path = "C:/Users/16102/Documents/Advanced Beginner Projects/login/Part 2_SQL"
8os.chdir(path)
9
10# connect to sqlite3
11conn = sqlite3.connect(os.path.join(path, "users_db.db"))
12c = conn.cursor()
13
14
15def setup_db():
16 # creates table in database
17 users_db = '''
18 CREATE TABLE IF NOT EXISTS users (
19 username TEXT PRIMARY KEY,
20 password TEXT
21 );
22 '''
23 c.execute(users_db)
24
25
26def ask_recreate():
27 # count users and ask to recreate db
28 count_users = '''SELECT * FROM users;'''
29 c.execute(count_users)
30 num_users = len(c.fetchall())
31
32 print("Your users table currently holds %d users." % num_users)
33
34 del_table = input("Would you like to delete the current table and start over? (y/n): ")
35 if del_table.lower().strip() in ['y', 'yes']:
36 del_stmt = '''DROP TABLE users;'''
37 c.execute(del_stmt)
38
39 setup_db()
40
41
42def show_db():
43 # displays all registered users
44 c.execute('''SELECT * FROM users;''')
45 rows = c.fetchall()
46
47 for row in rows:
48 print(row)
49
50
51def sha_encrypt(pw):
52 # sha256 hashing
53 encode_hash = hashlib.sha256(pw.encode())
54 hash_pw = encode_hash.hexdigest()
55
56 return hash_pw
57
58
59def register():
60 username = input("Please enter a username: ").lower()
61
62 # ensure passwords match
63 invalid = True
64 while invalid:
65 pw = getpass("Please enter a password: ")
66 pw2 = getpass("Please confirm your password: ")
67
68 if pw == pw2:
69 invalid = False
70 elif pw != pw2:
71 print("Passwords are not the same")
72
73 # hash password
74 hash_pw = sha_encrypt(pw)
75
76 # save to sqlite3 database. Return error if username taken
77 try:
78 insert_user = "INSERT INTO users VALUES (?, ?);"
79 c.execute(insert_user, (username, hash_pw))
80 except sqlite3.IntegrityError:
81 print("ERROR: Username already exists")
82 register()
83
84
85def is_valid_credentials():
86 # get username and password and check if they match db users
87 username = input("Please enter a username: ")
88 pw = getpass("Please enter a password: ")
89 hash_pw = sha_encrypt(pw)
90
91 # execute sqlite3 command. Returns None if doesn't exist
92 select_users = '''SELECT * FROM users WHERE username=? AND password=?;'''
93 c.execute(select_users, (username, hash_pw))
94 if c.fetchone() is not None:
95 print("Welcome")
96 else:
97 print("Login failed. Username or password is incorrect.")
98
99
100def main():
101 setup_db()
102 ask_recreate()
103
104 # ask to register or login
105 undecided = True
106 while undecided:
107 log_type = input("Would you like to register or login? Type register or login: ")
108 if log_type.strip().lower() == "register":
109 register()
110 break
111 elif log_type.strip().lower() == "login":
112 is_valid_credentials()
113 break
114 else:
115 print("Please type a valid response")
116
117 # closing connection and commiting changes
118 conn.commit()
119 conn.close()
120
121
122if __name__ == "__main__":
123 main()