import sqlite3
from hashlib import sha256
# ایجاد و اتصال به دیتابیس
def create_database():
conn = sqlite3.connect("user_database.db")
cursor = conn.cursor()
# ایجاد جدول کاربران (اگر وجود ندارد)
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
""")
conn.commit()
conn.close()
# ثبتنام کاربر
def register_user(username, password):
conn = sqlite3.connect("user_database.db")
cursor = conn.cursor()
try:
hashed_password = sha256(password.encode()).hexdigest() # هش کردن رمز عبور
cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hashed_password))
conn.commit()
print("User registered successfully!")
except sqlite3.IntegrityError:
print("Error: Username already exists.")
finally:
conn.close()
# بررسی اطلاعات ورود کاربر
def login_user(username, password):
conn = sqlite3.connect("user_database.db")
cursor = conn.cursor()
hashed_password = sha256(password.encode()).hexdigest() # هش کردن رمز عبور
cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, hashed_password))
user = cursor.fetchone()
conn.close()
if user:
print(f"Welcome, {username}!")
else:
print("Invalid username or password.")
# منوی اصلی
def main():
create_database()
while True:
print("\n1. Register")
print("2. Login")
print("3. Exit")
choice = input("Choose an option: ")
if choice == "1":
username = input("Enter username: ")
password = input("Enter password: ")
register_user(username, password)
elif choice == "2":
username = input("Enter username: ")
password = input("Enter password: ")
login_user(username, password)
elif choice == "3":
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
# اجرای برنامه
if __name__ == "__main__":
main()
#---