You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.5 KiB
Python

import secrets
import sqlite3
conn = sqlite3.connect("database.db")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS users (
telegram_id INTEGER PRIMARY KEY,
oauth_id TEXT,
UNIQUE (telegram_id, oauth_id)
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS tokens (
telegram_id INTEGER,
token TEXT,
FOREIGN KEY (telegram_id) REFERENCES users (telegram_id),
UNIQUE (telegram_id, token)
)
"""
)
conn.commit()
def create_user(telegram_id, oauth_id):
# insert the user into the database
conn.execute(
"""
INSERT INTO users (telegram_id, oauth_id) VALUES (?, ?)
""",
(telegram_id, oauth_id),
)
conn.commit()
def create_token(telegram_id):
# delete any existing tokens for this user
conn.execute(
"""
DELETE FROM tokens WHERE telegram_id = ?
""",
(telegram_id,),
)
# generate a new random token using crypt
token = secrets.token_hex(16)
# insert the token into the database
conn.execute(
"""
INSERT INTO tokens (telegram_id, token) VALUES (?, ?)
""",
(telegram_id, token),
)
conn.commit()
return token
def get_telegram_id(token):
# get the telegram id from the database
cursor = conn.execute(
"""
SELECT telegram_id FROM tokens WHERE token = ?
""",
(token,),
)
# fetch the result
result = cursor.fetchone()
# return the telegram id
return result[0] if result else None