-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path25.DesignAMulti-FactorAuthentication(MFA)System.py
More file actions
58 lines (46 loc) · 2.11 KB
/
25.DesignAMulti-FactorAuthentication(MFA)System.py
File metadata and controls
58 lines (46 loc) · 2.11 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
# Design a simple Multi-Factor Authentication (MFA) System where a user first logs
# in with a password, then verifies a one-time password (OTP)
# generated by the system within a short time window —
# all implemented in-memory without any database.
import hashlib, random, time, threading
class AuthSystem:
def __init__(self):
self.users = {}
self.lock = threading.Lock()
def hash_password(self, password):
return hashlib.sha256(password.encode()).hexdigest()
def register_user(self, username, password):
with self.lock:
if username in self.users:
return "User already exists."
self.users[username] = {"password_hash": self.hash_password(password), "otp": None, "otp_expiry": 0}
return f" User '{username}' registered successfully."
def login(self, username, password):
with self.lock:
user = self.users.get(username)
if not user:
return "User not found"
if user["password_hash"] != self.hash_password(password):
return "Invalid Password."
otp = random.randint(100000, 999999)
expiry = time.time() + 10
user["otp"] = otp
user["otp_expiry"] = expiry
print(f"[SYSTEM] OTP for {username}: {otp} (valid 10s)")
return "Password verified. OTP sent"
def verify_otp(self, username, otp):
with self.lock:
user = self.users.get(username)
if not user or user["otp"] is None:
return "OTP not generated. Please login first."
if time.time() > user["otp_expiry"]:
return "OTP expired."
if user["otp"] != otp:
return "Invalid OTP."
return f"Access Granted to {username}!"
if __name__ == "__main__":
auth = AuthSystem()
print(auth.register_user("bharadwaj", "secure123"))
print(auth.login("bharadwaj", "secure123"))
otp_input = int(input("Enter received OTP: ")) # Simulate user entering OTP
print(auth.verify_otp("bharadwaj", otp_input))