Added login

This commit is contained in:
2025-12-18 15:16:15 +00:00
parent 0c9c1d561f
commit 5fef4ac7c8
5 changed files with 924 additions and 184 deletions

149
initdb.py
View File

@@ -1,39 +1,26 @@
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from dotenv import load_dotenv
from os import getenv
load_dotenv()
# Database connection parameters
DB_HOST = getenv("DB_HOST")+":"+getenv("DB_PORT")
DB_USER = getenv("DB_USER")
DB_PASSWORD = getenv("DB_PASSWORD")
DB_NAME = "outpost"
def create_database():
"""Create the outpost database if it doesn't exist"""
def createDatabase(dbuser, dbpass, dbhost, dbname):
try:
# Connect to PostgreSQL server (default postgres database)
conn = psycopg2.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
host=dbhost,
user=dbuser,
password=dbpass,
database="postgres"
)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
# Check if database exists
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (DB_NAME,))
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (dbname,))
exists = cur.fetchone()
if not exists:
cur.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(DB_NAME)))
print(f"Database '{DB_NAME}' created successfully")
cur.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(dbname)))
print(f"Database '{dbname}' created successfully")
else:
print(f"Database '{DB_NAME}' already exists")
print(f"Database '{dbname}' already exists")
cur.close()
conn.close()
@@ -42,37 +29,85 @@ def create_database():
print(f"Error creating database: {e}")
raise
def create_tables():
def createTables(dbuser, dbpass, dbhost, dbname):
try:
conn = psycopg2.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME
host=dbhost,
user=dbuser,
password=dbpass,
database=dbname
)
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS groups (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) UNIQUE NOT NULL,
parent UUID REFERENCES groups(id),
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
print("Table 'groups' created or already exists")
cur.execute("""
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
username VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255),
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
password_hash VARCHAR(255) NOT NULL
password_hash VARCHAR(255) NOT NULL,
group_id UUID REFERENCES groups(id)
)
""")
print("Table 'users' created or already exists")
cur.execute("""
CREATE TABLE IF NOT EXISTS logging (
CREATE TABLE IF NOT EXISTS userData (
id SERIAL PRIMARY KEY,
time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
user_id INTEGER REFERENCES users(id),
action TEXT NOT NULL
user_id uuid REFERENCES users(id),
service_id VARCHAR(255) NOT NULL,
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
property VARCHAR(255) NOT NULL,
value VARCHAR(255) NOT NULL
)
""")
print("Table 'logging' created or already exists")
print("Table 'userData' created or already exists")
cur.execute("""
CREATE TABLE IF NOT EXISTS groupData (
id SERIAL PRIMARY KEY,
group_id uuid REFERENCES groups(id),
service_id VARCHAR(255) NOT NULL,
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
property VARCHAR(255) NOT NULL,
value VARCHAR(255) NOT NULL
)
""")
print("Table 'userData' created or already exists")
cur.execute("""
CREATE TABLE IF NOT EXISTS logs (
id SERIAL PRIMARY KEY,
user_id uuid REFERENCES users(id),
action VARCHAR(255),
details VARCHAR(255),
user_ip VARCHAR(255),
user_agent VARCHAR(255),
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
print("Table 'logs' created or already exists")
cur.execute("""
CREATE TABLE IF NOT EXISTS userTokens (
id VARCHAR(255) PRIMARY KEY,
owner_id uuid REFERENCES users(id),
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expiration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP + INTERVAL '30 days'
)
""")
print("Table 'userTokens' created or already exists")
conn.commit()
cur.close()
@@ -80,50 +115,4 @@ def create_tables():
except Exception as e:
print(f"Error creating tables: {e}")
raise
def create_user_table(id):
try:
conn = psycopg2.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME
)
cur = conn.cursor()
table_name = f"userpermissions.{id.lower().replace(' ', '_').replace('-', '_').replace('.', '_')}"
cur.execute(sql.SQL("""
CREATE TABLE IF NOT EXISTS {} (
key VARCHAR(255) PRIMARY KEY,
value TEXT
)
""").format(sql.Identifier(table_name)))
print(f"Table '{table_name}' created or already exists")
conn.commit()
cur.close()
conn.close()
except Exception as e:
print(f"Error creating user table: {e}")
raise
def main():
"""Main function to set up the database"""
print("Starting database setup...")
# Step 1: Create database
create_database()
# Step 2: Create tables
create_tables()
print("\nDatabase setup completed successfully!")
print("\nTo create a user-specific table, call:")
print("create_user_table('username')")
if __name__ == "__main__":
main()
raise