我写了一个Python脚本,将用户输入与数据库查询进行比较,然后允许登录或不允许登录。我将分解问题,以便于理解:
说明:
我的程序已经对用户的密码和唯一ID进行加密和解密,从而具有双重安全性。
我希望一切都尽可能安全。我不久前就开始使用面向对象的Python,因此请尽可能地严格一点。
我不专业地制作了这个作品,但是它将投入生产!
信息
我将MySQL用于数据库,将Python 3.7用于脚本,将Flask用于会话。
# Imports
from passlib.context import CryptContext
import mysql.connector
import json
from pprint import pprint
# Config file loaded as a json
with open("database_connect.json") as config:
config = json.load(config)
config = config[0]
try:
# Json is argued as a kwarg
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
# Query is made
cursor.execute("SELECT first,id,pwd,uid FROM user")
args = cursor.fetchone()
# Any integer queries have the string function mapped to them
args = tuple(map(lambda i: str(i), args))
except:
print("Connection error!")
finally:
cnx.close()
# Passlib encryption method
passlib_context = CryptContext(
schemes=["pbkdf2_sha256"],
default="pbkdf2_sha256",
pbkdf2_sha256__default_rounds=300000)
# Base class for all users
class default:
priviliges = {
"Ban": False,
"Kick": False,
"Broadcast": False,
"Iplookup": False }
# Instantiating the default class
def __init__(self, name, uniqueid, pwd, usernameid):
self.name = name
self.__pwd = passlib_context.hash(pwd)
self.__uniqueid = passlib_context.hash(uniqueid)
self.usernameid = usernameid
# Encryption method for users
def encrypt_method(self):
encrypt_data = [self.__pwd, self.__uniqueid]
return encrypt_data
class decrypt():
# Instantiating the decryption class
def __init__(self, attempted_pwd, hashpwd):
self.__attempted_pwd = attempted_pwd
self.__hashpwd = hashpwd
# Decryption method for decryption class
def decrypt_method(self):
decrypt_data = passlib_context.verify(self.__attempted_pwd, self.__hashpwd)
if decrypt_data is False:
allow_login = False
elif decrypt_data is True:
allow_login = True
return allow_login
# Information fetched from the database in tuple form, used as an arguement
user = default(*args)
# Attempt corresponds to user input. The first arguement is the attempted password.
attempt = decrypt("",user.encrypt_method()[0])
print(attempt.decrypt_method())