Spaces:
Paused

File size: 12,067 Bytes
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
"""
YAZ Care Platform - PostgreSQL Setup Script
Production database initialization with multi-tenant support
"""

import asyncio
import os
import sys
import logging
from pathlib import Path

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

try:
    import asyncpg
    import psycopg2
    from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
except ImportError:
    print("❌ PostgreSQL dependencies not installed")
    print("Run: pip install asyncpg psycopg2-binary")
    sys.exit(1)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def create_database():
    """Create PostgreSQL database and user"""
    
    # Database configuration
    config = {
        'host': os.getenv('POSTGRES_HOST', 'localhost'),
        'port': int(os.getenv('POSTGRES_PORT', '5432')),
        'user': os.getenv('POSTGRES_ADMIN_USER', 'postgres'),
        'password': os.getenv('POSTGRES_ADMIN_PASSWORD', ''),
        'target_db': os.getenv('POSTGRES_DB', 'yazcare_prod'),
        'target_user': os.getenv('POSTGRES_USER', 'yazcare_user'),
        'target_password': os.getenv('POSTGRES_PASSWORD', 'yazcare_secure_2025')
    }
    
    try:
        # Connect as admin user
        logger.info("🔗 Connecting to PostgreSQL as admin...")
        conn = psycopg2.connect(
            host=config['host'],
            port=config['port'], 
            user=config['user'],
            password=config['password'],
            database='postgres'
        )
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cursor = conn.cursor()
        
        # Create user if not exists
        logger.info(f"👤 Creating user: {config['target_user']}")
        cursor.execute(f"""
            DO $$
            BEGIN
                IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{config['target_user']}') THEN
                    CREATE USER {config['target_user']} WITH PASSWORD '{config['target_password']}';
                END IF;
            END
            $$;
        """)
        
        # Create database if not exists
        logger.info(f"🗄️  Creating database: {config['target_db']}")
        cursor.execute(f"""
            SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{config['target_db']}'
        """)
        
        if not cursor.fetchone():
            cursor.execute(f"""
                CREATE DATABASE {config['target_db']} 
                OWNER {config['target_user']} 
                ENCODING 'UTF8'
            """)
        
        # Grant permissions
        logger.info("🔐 Granting permissions...")
        cursor.execute(f"GRANT ALL PRIVILEGES ON DATABASE {config['target_db']} TO {config['target_user']}")
        cursor.execute(f"ALTER USER {config['target_user']} CREATEDB")
        
        cursor.close()
        conn.close()
        
        # Connect to target database and setup extensions
        logger.info("📦 Setting up database extensions...")
        conn = psycopg2.connect(
            host=config['host'],
            port=config['port'],
            user=config['target_user'], 
            password=config['target_password'],
            database=config['target_db']
        )
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cursor = conn.cursor()
        
        # Create extensions
        extensions = [
            'uuid-ossp',  # UUID generation
            'pgcrypto',   # Cryptographic functions
            'pg_stat_statements'  # Query statistics
        ]
        
        for ext in extensions:
            try:
                cursor.execute(f"CREATE EXTENSION IF NOT EXISTS \"{ext}\"")
                logger.info(f"✅ Extension created: {ext}")
            except Exception as e:
                logger.warning(f"⚠️  Extension {ext} not available: {e}")
        
        cursor.close()
        conn.close()
        
        logger.info("✅ PostgreSQL setup completed successfully!")
        return True
        
    except Exception as e:
        logger.error(f"❌ PostgreSQL setup failed: {e}")
        return False

async def setup_row_level_security():
    """Setup Row Level Security for multi-tenant isolation"""
    
    config = {
        'host': os.getenv('POSTGRES_HOST', 'localhost'),
        'port': int(os.getenv('POSTGRES_PORT', '5432')),
        'user': os.getenv('POSTGRES_USER', 'yazcare_user'),
        'password': os.getenv('POSTGRES_PASSWORD', 'yazcare_secure_2025'),
        'database': os.getenv('POSTGRES_DB', 'yazcare_prod')
    }
    
    try:
        conn = psycopg2.connect(**config)
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cursor = conn.cursor()
        
        logger.info("🔒 Setting up Row Level Security...")
        
        # Create tenant-aware tables with RLS
        tables_sql = """
        -- Tenants table
        CREATE TABLE IF NOT EXISTS tenants (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            name VARCHAR(255) NOT NULL UNIQUE,
            subdomain VARCHAR(100) UNIQUE,
            settings JSONB DEFAULT '{}',
            created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
            updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
            active BOOLEAN DEFAULT TRUE
        );
        
        -- Users table with tenant isolation
        CREATE TABLE IF NOT EXISTS users (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
            email VARCHAR(255) NOT NULL,
            password_hash VARCHAR(255) NOT NULL,
            first_name VARCHAR(100),
            last_name VARCHAR(100),
            role VARCHAR(50) DEFAULT 'user',
            active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
            updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
            UNIQUE(tenant_id, email)
        );
        
        -- Medical records with tenant isolation  
        CREATE TABLE IF NOT EXISTS medical_records (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
            patient_id UUID NOT NULL,
            record_type VARCHAR(100) NOT NULL,
            content JSONB NOT NULL,
            created_by UUID REFERENCES users(id),
            created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
            updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
        );
        
        -- Audit logs for HIPAA compliance
        CREATE TABLE IF NOT EXISTS audit_logs (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            tenant_id UUID REFERENCES tenants(id),
            user_id UUID REFERENCES users(id),
            action VARCHAR(100) NOT NULL,
            resource_type VARCHAR(100),
            resource_id VARCHAR(255),
            old_values JSONB,
            new_values JSONB,
            ip_address INET,
            user_agent TEXT,
            session_id VARCHAR(255),
            created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
        );
        """
        
        cursor.execute(tables_sql)
        
        # Enable RLS on tenant-isolated tables
        rls_tables = ['users', 'medical_records', 'audit_logs']
        
        for table in rls_tables:
            cursor.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
            
            # Create RLS policies
            cursor.execute(f"""
                CREATE POLICY tenant_isolation ON {table}
                FOR ALL TO PUBLIC
                USING (tenant_id = current_setting('app.tenant_id', true)::UUID)
            """)
            
            logger.info(f"✅ RLS enabled for table: {table}")
        
        # Create helper functions
        cursor.execute("""
            CREATE OR REPLACE FUNCTION get_current_tenant_id() 
            RETURNS UUID AS $$
            BEGIN
                RETURN current_setting('app.tenant_id', true)::UUID;
            EXCEPTION 
                WHEN others THEN
                    RETURN NULL;
            END;
            $$ LANGUAGE plpgsql STABLE SECURITY DEFINER;
            
            CREATE OR REPLACE FUNCTION set_tenant_context(tenant_uuid UUID)
            RETURNS VOID AS $$
            BEGIN
                PERFORM set_config('app.tenant_id', tenant_uuid::TEXT, false);
            END;
            $$ LANGUAGE plpgsql SECURITY DEFINER;
        """)
        
        # Insert default tenant
        cursor.execute("""
            INSERT INTO tenants (name, subdomain, settings)
            VALUES (
                'Default Healthcare Organization',
                'default',
                '{"features": ["all"], "max_users": 1000, "storage_gb": 100}'
            )
            ON CONFLICT (name) DO NOTHING
        """)
        
        cursor.close()
        conn.close()
        
        logger.info("✅ Row Level Security setup completed!")
        return True
        
    except Exception as e:
        logger.error(f"❌ RLS setup failed: {e}")
        return False

async def create_indexes():
    """Create performance indexes"""
    
    config = {
        'host': os.getenv('POSTGRES_HOST', 'localhost'),
        'port': int(os.getenv('POSTGRES_PORT', '5432')),
        'user': os.getenv('POSTGRES_USER', 'yazcare_user'),
        'password': os.getenv('POSTGRES_PASSWORD', 'yazcare_secure_2025'),
        'database': os.getenv('POSTGRES_DB', 'yazcare_prod')
    }
    
    try:
        conn = psycopg2.connect(**config)
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cursor = conn.cursor()
        
        logger.info("📊 Creating performance indexes...")
        
        indexes = [
            "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_tenant_email ON users(tenant_id, email)",
            "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_medical_records_tenant_patient ON medical_records(tenant_id, patient_id)",
            "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_audit_logs_tenant_created ON audit_logs(tenant_id, created_at DESC)",
            "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_audit_logs_user_action ON audit_logs(user_id, action)",
            "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_medical_records_type_created ON medical_records(record_type, created_at DESC)"
        ]
        
        for index_sql in indexes:
            try:
                cursor.execute(index_sql)
                logger.info("✅ Index created successfully")
            except Exception as e:
                logger.warning(f"⚠️  Index creation failed: {e}")
        
        cursor.close()
        conn.close()
        
        logger.info("✅ Performance indexes created!")
        return True
        
    except Exception as e:
        logger.error(f"❌ Index creation failed: {e}")
        return False

async def main():
    """Main setup function"""
    logger.info("🏥 YAZ Care Platform - PostgreSQL Setup")
    logger.info("=" * 50)
    
    # Step 1: Create database and user
    if await create_database():
        logger.info("✅ Database creation completed")
    else:
        logger.error("❌ Database creation failed")
        return False
    
    # Step 2: Setup RLS and multi-tenancy
    if await setup_row_level_security():
        logger.info("✅ Multi-tenancy setup completed")
    else:
        logger.error("❌ Multi-tenancy setup failed") 
        return False
    
    # Step 3: Create performance indexes
    if await create_indexes():
        logger.info("✅ Performance optimization completed")
    else:
        logger.error("❌ Performance optimization failed")
        return False
    
    logger.info("🎉 PostgreSQL setup completed successfully!")
    logger.info("📋 Next steps:")
    logger.info("   1. Update .env file with PostgreSQL connection details")
    logger.info("   2. Run: python main.py migrate")
    logger.info("   3. Start the platform: python main.py serve")
    
    return True

if __name__ == "__main__":
    asyncio.run(main())