81 lines
1.9 KiB
Python
81 lines
1.9 KiB
Python
import sqlite3
|
|
from sqlite3 import Error
|
|
|
|
database = r"db/cgi-example.sqlite3"
|
|
|
|
def create_connection():
|
|
""" create a database connection to the SQLite database
|
|
specified by db_file
|
|
:param db_file: database file
|
|
:return: Connection object or None
|
|
"""
|
|
conn = None
|
|
try:
|
|
conn = sqlite3.connect(database)
|
|
except Error as e:
|
|
print(e)
|
|
return conn
|
|
|
|
def add_user(conn):
|
|
"""
|
|
Create a new user record
|
|
:param conn:
|
|
:return: user id
|
|
"""
|
|
sql = ''' INSERT INTO users DEFAULT VALUES '''
|
|
cur = conn.cursor()
|
|
try:
|
|
cur.execute(sql)
|
|
conn.commit()
|
|
except:
|
|
return 'error in insert'
|
|
return cur.lastrowid
|
|
|
|
def add_hash(conn, cert_user):
|
|
"""
|
|
Create a new record for cert_user
|
|
:param conn:
|
|
:param cert_user:
|
|
:return: id
|
|
"""
|
|
sql = ''' INSERT INTO certs(hash,user_id) VALUES(?,?) '''
|
|
cur = conn.cursor()
|
|
cur.execute(sql, cert_user)
|
|
conn.commit()
|
|
return cur.lastrowid
|
|
|
|
def get_user(conn, tls_client_hash):
|
|
"""
|
|
Get user id of tls_client_hash if it exists
|
|
:param conn:
|
|
:param tls_client_hash:
|
|
:return: user id
|
|
"""
|
|
cur = conn.cursor()
|
|
cur.execute("SELECT user_id FROM certs WHERE hash=?", (tls_client_hash,))
|
|
rows = cur.fetchall()
|
|
|
|
if len(rows) > 0:
|
|
row = rows[0]
|
|
return row[0] # user_id
|
|
else:
|
|
return None
|
|
|
|
def check_hash(tls_client_hash):
|
|
"""
|
|
Check for existing user with hash or add a new one
|
|
:param conn:
|
|
:param tls_client_hash:
|
|
:return: user id
|
|
"""
|
|
conn = create_connection()
|
|
with conn:
|
|
user_id = get_user(conn, tls_client_hash)
|
|
if (user_id is None):
|
|
user_id = add_user(conn)
|
|
cert_user = (tls_client_hash, user_id)
|
|
add_hash(conn, cert_user)
|
|
return user_id
|
|
|
|
#vim:fenc=utf-8:ts=4:sw=4:sta:noet:sts=4:fdm=marker:ai
|