forked from singhmayank980/Hactoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Login form.py
444 lines (220 loc) · 9.96 KB
/
Login form.py
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
"""
With this program one can login, create or remove an account or change its
password. It stores your data in its online database.
---------------| IMPORTANT |-----------------
Password encryption is not added yet but will surely add in upcoming versions. So for now everything is public, please do not include any personal information about yourself in
both username or password.
"""
CMD = """
Commands:-
➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖
c - Create account
l - Login account / Change password
r - Remove account
"""
INP_FORM = """
Input Format:-
➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Command, Username, Password, *New
^ ^ ^
*New Password is optional
"""
INP_EX = """
Input Examples:-
➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖
- To create account:
c, james, 1234
- To login:
l, james, 1234
- To remove account
r, james, 1234
- To change password
l, james, 1234, abc123
"""
"""
---------------------------------------------
Author : OR!ON
Date : 05/03/2019
Version: 1.6.1-20190313 © 2019 All Rights
Reserved
---------------------------------------------
Please Upvote if you like my code \(*.*)/
"""
import json
import string
import http.client as client
import sys
sys.stdout.reconfigure(encoding="utf-16")
class Database:
"""Contains methods to read and write from database"""
def __init__(self):
"""Initializes with name of the database"""
self.json_host = "www.jsonblob.com"
self.json_url = "/api/jsonBlob/a1388a24-43fb-11e9-a5d1-69a4efa84c0a"
def read_database(self) -> dict:
"""Reads data from database and returns all the data"""
https_connection = client.HTTPSConnection(self.json_host)
https_connection.request('GET', self.json_url)
return json.load(https_connection.getresponse())
def write_database(self, new_data: dict) -> None:
"""Writes new data to the database"""
# online
https_connection = client.HTTPSConnection(self.json_host)
https_connection.request('PUT', self.json_url,
json.dumps(new_data))
class Account:
"""Contains various methods to create, login or remove an account."""
def __init__(self):
"""Initializes class with methods of Database() and valid_commands."""
self.database = Database()
self.valid_commands = ["c", "l", "r"]
@staticmethod
def valid_username_length(username: str) -> bool:
"""Checks whether username length is >= 2 or not."""
if len(username) >= 2:
return True
return False
@staticmethod
def valid_password_length(password: str) -> bool:
"""Checks whether password length is >= 4 or not."""
if len(password) >= 4:
return True
return False
@staticmethod
def invalid_character(username: str) -> bool:
"""Checks whether username contains punctuations or not."""
invalid_chars = string.punctuation
if any(char in invalid_chars for char in username):
return True
return False
def username_taken(self, username: str) -> bool:
"""Checks whether username is already taken or not."""
if username in self.database.read_database():
return True
return False
def same_password_as_old(self, username: str, new_password: str) -> bool:
"""Checks whether the new password is same as old or not."""
return self.database.read_database()[username] == new_password
def username_password_match(self, username: str, password: str) -> bool:
"""Checks whether username and password match in database."""
if (self.username_taken(username) and
self.database.read_database()[username] == password):
return True
return False
def create_account(self, username: str, password: str) -> None:
"""Creates a new account."""
if (self.valid_username_length(username) and
self.valid_password_length(password)):
if not self.invalid_character(username):
if not self.username_taken(username):
old_data = self.database.read_database()
# adding username and password to the old data
old_data[username] = password
self.database.write_database(old_data)
print("✔️ Account Created!")
else:
print("❌ Account Creation Failed! "
f"Username '{username}' already taken.")
else:
print("❗ Character Type Error! "
"Punctuation marks are not allowed in the "
"Username.")
else:
print("❗ Character Length Error! "
"Username & Password must be at least 2 and 4 "
"characters long respectively.")
def login_account(self, username: str, password: str,
new_password: str = None) -> None:
"""Login to an already present account or change its password."""
if self.username_password_match(username, password):
if new_password is not None:
if not self.valid_password_length(password):
print("❗ Password Length Error! New password must be at "
"least 4 characters long.")
elif self.same_password_as_old(username, new_password):
print("❌ Password Change Failed! "
"New password can not be same as old one.")
else:
old_data = self.database.read_database()
# updating the password in the old_data
old_data[username] = new_password
self.database.write_database(old_data)
print("✔️ Success! Password changed.")
else:
print("✔️ Login Successful!")
else:
print("❌ Login Failed! Username or Password is incorrect.")
def remove_account(self, username, password) -> None:
"""Removes already present account."""
if self.username_password_match(username, password):
old_data = self.database.read_database()
old_data.pop(username)
self.database.write_database(old_data)
print("✔️ Account Removed!")
else:
print("❌ Account Removal Failed! Username or Password is incorrect.")
def account_process(self, command: str, username: str, password: str,
new_password: str = None) -> None:
"""Handles account creation, login and removal."""
if command.lower() == "c":
self.create_account(username, password)
elif command.lower() == "l":
self.login_account(username, password, new_password)
elif command.lower() == "r":
self.remove_account(username, password)
class App:
def __init__(self):
self.account = Account()
@staticmethod
def take_user_input() -> list:
"""Takes user input."""
# taking user data
global user_entry
user_entry = input()
return user_entry.split(",")
def parse_user_input(self) -> list:
"""Removes trailing whitespaces."""
return [item.strip() for item in self.take_user_input()]
def handle_commands(self) -> None:
"""Handles commands given by user."""
parsed_user_input = self.parse_user_input()
# if first item of parsed_user_input (lowercase),
# is in valid_commands and
# there are either 3 or 4 items in parsed_user_input
if (parsed_user_input[0].lower() in self.account.valid_commands and
len(parsed_user_input) in range(3, 5)):
# normal condition
if len(parsed_user_input) == 3:
command, username, password = parsed_user_input
print(f"Username: {username}\nPassword: {password}\n")
self.account.account_process(command, username, password)
# in-case user wants to change its password
else:
command, username, password, new_password = parsed_user_input
# if user does not enter l command
if parsed_user_input[0].lower() != "l":
print(f"Username: {username}\nPassword: {password}\n")
print("❕ Warning! "
f"Command '{parsed_user_input[0]}' only requires "
f"2 entries, found (3).")
else:
print(f"Username : {username}\nPassword : {password}\nNew Password: {new_password}\n")
self.account.account_process(command, username, password,
new_password)
# if user does not enters any of command, username, password
elif len(parsed_user_input) not in range(3, 5):
if parsed_user_input != ['']:
val_len = len(parsed_user_input)
# if user forgets to put commas in the user_entry
print("❗ Comma Error! Separate you entry with either two or three "
"commas, "
f"found ({user_entry.count(',')}).\n", INP_FORM)
else:
val_len = len(parsed_user_input) - 1
print(f"❗ Value Error! Not enough values to proceed, "
f"required (3 or 4) found ({val_len}).\n", INP_EX)
# if command entered by user is not valid
elif parsed_user_input[0] not in self.account.valid_commands:
print("❗ Command Error! Valid commands are (l/c/r) found "
f"({parsed_user_input[0]}).\n", CMD)
App().handle_commands()