diff --git a/cgi-example/db.py b/cgi-example/db.py new file mode 100644 index 0000000..36ff611 --- /dev/null +++ b/cgi-example/db.py @@ -0,0 +1,84 @@ +import sqlite3 +from sqlite3 import Error + +database = r"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 user() + DEFAULT VALUES ''' + cur = conn.cursor() + cur.execute(sql) + conn.commit() + + 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_hash = (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 diff --git a/cgi-example/index.gmi b/cgi-example/index.gmi index 5b4c625..4607799 100755 --- a/cgi-example/index.gmi +++ b/cgi-example/index.gmi @@ -1,8 +1,13 @@ #!/bin/python from helpers import get_client_cert +from db import check_hash TLS_CLIENT_HASH = get_client_cert() print("TLS_CLIENT_HASH:") print(TLS_CLIENT_HASH) +user_id = check_hash(TLS_CLIENT_HASH) +print("USER ID:") +print(user_id) + #vim:fenc=utf-8:ts=4:sw=4:sta:noet:sts=4:fdm=marker:ai