+
+
nest
choo
+
dynamo
+
+
+
+
@
asm
+
dask
next
alpine
dynamo
+
+
+
+
junit
+
mocha
json
sqlite
+
+
+
https
+
f#
+
argocd
∩
pycharm
+
erlang
+
~
+
...
+
+
+
+
+
+
meteor
+
+
+
+
+
+
php
+
cdn
+
+
+
+
+
+
+
+
%
<-
+
+
kali
cassandra
+
+
+
+
swc
vue
+
+
cdn
+
git
+
!==
+
jwt
+
+
riot
Back to Blog
Medical Record Management on Alpine Linux πŸ₯
Alpine Linux Healthcare Database

Medical Record Management on Alpine Linux πŸ₯

Published Jun 13, 2025

Learn how to build a secure medical record management system on Alpine Linux. We will implement HIPAA compliance, patient data security, and healthcare workflows! πŸ’Š

24 min read
0 views
Table of Contents

Managing medical records digitally is like being a guardian of health information! πŸ›‘οΈ Alpine Linux provides a secure and reliable platform for handling sensitive patient data while ensuring compliance with healthcare regulations. Let’s build a comprehensive medical record management system! πŸš€

Understanding Medical Record Management πŸ€”

Medical record systems handle:

  • Patient demographics - Personal and contact information
  • Medical history - Past conditions and treatments
  • Clinical data - Test results and diagnoses
  • Prescriptions - Medication management
  • Compliance - HIPAA and privacy regulations

Think of it as a digital filing cabinet with super security! πŸ—„οΈ

Setting Up Secure Infrastructure πŸ“¦

Install essential components with security in mind:

# Update package list
sudo apk update

# Install secure web server
sudo apk add nginx nginx-mod-http-headers-more
sudo apk add certbot certbot-nginx

# Install PHP with security modules
sudo apk add php82 php82-fpm php82-opcache
sudo apk add php82-openssl php82-sodium php82-session
sudo apk add php82-pdo php82-pdo_pgsql php82-json

# Install PostgreSQL (HIPAA compliant)
sudo apk add postgresql14 postgresql14-client
sudo apk add postgresql14-contrib

# Security tools
sudo apk add fail2ban aide

Database Security Setup πŸ”’

Create a secure database environment:

# Initialize PostgreSQL with encryption
sudo /etc/init.d/postgresql setup
sudo rc-service postgresql start
sudo rc-update add postgresql

# Configure PostgreSQL for encryption
sudo -u postgres psql << 'EOF'
-- Create encrypted database
CREATE DATABASE medical_records WITH ENCODING 'UTF8';

-- Create roles with limited permissions
CREATE ROLE medical_admin WITH LOGIN PASSWORD 'SecurePass123!';
CREATE ROLE medical_user WITH LOGIN PASSWORD 'UserPass456!';
CREATE ROLE medical_readonly WITH LOGIN PASSWORD 'ReadOnly789!';

-- Grant appropriate permissions
GRANT ALL PRIVILEGES ON DATABASE medical_records TO medical_admin;
GRANT CONNECT ON DATABASE medical_records TO medical_user;
GRANT CONNECT ON DATABASE medical_records TO medical_readonly;

\c medical_records

-- Enable row-level security
ALTER DATABASE medical_records SET row_security = on;
EOF

# Configure SSL for database connections
sudo cat >> /var/lib/postgresql/14/data/postgresql.conf << 'EOF'
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL'
EOF

HIPAA-Compliant Schema πŸ“‹

Create database tables with audit trails:

# Medical records schema
cat > medical_schema.sql << 'EOF'
-- Enable extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

-- Audit log table
CREATE TABLE audit_log (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    user_id UUID NOT NULL,
    action VARCHAR(50) NOT NULL,
    table_name VARCHAR(50),
    record_id UUID,
    old_values JSONB,
    new_values JSONB,
    ip_address INET,
    user_agent TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Users table with role-based access
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    username VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    role VARCHAR(50) NOT NULL CHECK (role IN ('admin', 'doctor', 'nurse', 'staff', 'patient')),
    full_name VARCHAR(255) NOT NULL,
    email VARCHAR(255),
    active BOOLEAN DEFAULT true,
    last_login TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Patients table with encrypted sensitive data
CREATE TABLE patients (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    medical_record_number VARCHAR(50) UNIQUE NOT NULL,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) NOT NULL,
    date_of_birth DATE NOT NULL,
    ssn_encrypted BYTEA, -- Encrypted SSN
    gender VARCHAR(20),
    blood_type VARCHAR(5),
    phone VARCHAR(20),
    email VARCHAR(255),
    address JSONB,
    emergency_contact JSONB,
    insurance_info JSONB,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Medical encounters
CREATE TABLE encounters (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    patient_id UUID REFERENCES patients(id),
    provider_id UUID REFERENCES users(id),
    encounter_date TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    encounter_type VARCHAR(50),
    chief_complaint TEXT,
    notes TEXT,
    diagnosis JSONB,
    treatment_plan TEXT,
    follow_up_date DATE,
    status VARCHAR(50) DEFAULT 'active'
);

-- Prescriptions with drug interaction checks
CREATE TABLE prescriptions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    patient_id UUID REFERENCES patients(id),
    provider_id UUID REFERENCES users(id),
    encounter_id UUID REFERENCES encounters(id),
    medication_name VARCHAR(255) NOT NULL,
    dosage VARCHAR(100),
    frequency VARCHAR(100),
    duration VARCHAR(100),
    refills INTEGER DEFAULT 0,
    pharmacy_notes TEXT,
    prescribed_date TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    status VARCHAR(50) DEFAULT 'active'
);

-- Lab results
CREATE TABLE lab_results (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    patient_id UUID REFERENCES patients(id),
    encounter_id UUID REFERENCES encounters(id),
    test_name VARCHAR(255) NOT NULL,
    test_code VARCHAR(50),
    result_value VARCHAR(255),
    result_unit VARCHAR(50),
    reference_range VARCHAR(100),
    abnormal_flag BOOLEAN DEFAULT false,
    test_date TIMESTAMP WITH TIME ZONE,
    resulted_date TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    notes TEXT
);

-- Access control policies
CREATE TABLE access_policies (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    role VARCHAR(50) NOT NULL,
    resource VARCHAR(100) NOT NULL,
    action VARCHAR(50) NOT NULL,
    conditions JSONB,
    UNIQUE(role, resource, action)
);

-- Create audit trigger function
CREATE OR REPLACE FUNCTION audit_trigger_function()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO audit_log (
        user_id,
        action,
        table_name,
        record_id,
        old_values,
        new_values,
        ip_address,
        user_agent
    ) VALUES (
        current_setting('app.current_user_id')::UUID,
        TG_OP,
        TG_TABLE_NAME,
        COALESCE(NEW.id, OLD.id),
        CASE WHEN TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN to_jsonb(OLD) ELSE NULL END,
        CASE WHEN TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN to_jsonb(NEW) ELSE NULL END,
        inet_client_addr(),
        current_setting('app.user_agent', true)
    );
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Apply audit triggers to all tables
CREATE TRIGGER audit_patients AFTER INSERT OR UPDATE OR DELETE ON patients
    FOR EACH ROW EXECUTE FUNCTION audit_trigger_function();
    
CREATE TRIGGER audit_encounters AFTER INSERT OR UPDATE OR DELETE ON encounters
    FOR EACH ROW EXECUTE FUNCTION audit_trigger_function();
    
CREATE TRIGGER audit_prescriptions AFTER INSERT OR UPDATE OR DELETE ON prescriptions
    FOR EACH ROW EXECUTE FUNCTION audit_trigger_function();
EOF

sudo -u postgres psql medical_records < medical_schema.sql

Secure API Backend πŸ›‘οΈ

Build a secure API for medical records:

# Create API directory
mkdir -p ~/medical-api/{src,config,middleware}
cd ~/medical-api

# Main application file
cat > src/app.js << 'EOF'
const express = require('express');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { Pool } = require('pg');
const crypto = require('crypto');

const app = express();

// Security middleware
app.use(helmet());
app.use(express.json());

// Rate limiting
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100 // limit each IP to 100 requests per windowMs
});
app.use('/api/', limiter);

// Database connection with SSL
const pool = new Pool({
    host: 'localhost',
    database: 'medical_records',
    user: 'medical_admin',
    password: process.env.DB_PASSWORD,
    ssl: {
        rejectUnauthorized: false
    }
});

// Encryption functions
const algorithm = 'aes-256-gcm';
const secretKey = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');

function encrypt(text) {
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
    
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    
    const authTag = cipher.getAuthTag();
    
    return {
        encrypted,
        authTag: authTag.toString('hex'),
        iv: iv.toString('hex')
    };
}

function decrypt(encryptedData) {
    const decipher = crypto.createDecipheriv(
        algorithm, 
        secretKey, 
        Buffer.from(encryptedData.iv, 'hex')
    );
    
    decipher.setAuthTag(Buffer.from(encryptedData.authTag, 'hex'));
    
    let decrypted = decipher.update(encryptedData.encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    
    return decrypted;
}

// Authentication middleware
async function authenticate(req, res, next) {
    const token = req.headers.authorization?.split(' ')[1];
    
    if (!token) {
        return res.status(401).json({ error: 'No token provided' });
    }
    
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        
        // Set user context for audit logging
        await pool.query('SET LOCAL app.current_user_id = $1', [decoded.id]);
        await pool.query('SET LOCAL app.user_agent = $1', [req.headers['user-agent']]);
        
        next();
    } catch (error) {
        res.status(401).json({ error: 'Invalid token' });
    }
}

// Authorization middleware
function authorize(...roles) {
    return (req, res, next) => {
        if (!roles.includes(req.user.role)) {
            return res.status(403).json({ error: 'Insufficient permissions' });
        }
        next();
    };
}

// Login endpoint
app.post('/api/login', async (req, res) => {
    const { username, password } = req.body;
    
    try {
        const result = await pool.query(
            'SELECT id, username, password_hash, role, full_name FROM users WHERE username = $1 AND active = true',
            [username]
        );
        
        if (result.rows.length === 0) {
            return res.status(401).json({ error: 'Invalid credentials' });
        }
        
        const user = result.rows[0];
        const validPassword = await bcrypt.compare(password, user.password_hash);
        
        if (!validPassword) {
            return res.status(401).json({ error: 'Invalid credentials' });
        }
        
        // Update last login
        await pool.query(
            'UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = $1',
            [user.id]
        );
        
        // Generate JWT
        const token = jwt.sign(
            { 
                id: user.id, 
                username: user.username, 
                role: user.role,
                name: user.full_name
            },
            process.env.JWT_SECRET,
            { expiresIn: '8h' }
        );
        
        res.json({ 
            token, 
            user: {
                id: user.id,
                username: user.username,
                role: user.role,
                name: user.full_name
            }
        });
    } catch (error) {
        console.error('Login error:', error);
        res.status(500).json({ error: 'Server error' });
    }
});

// Patient endpoints
app.get('/api/patients', authenticate, authorize('doctor', 'nurse', 'admin'), async (req, res) => {
    try {
        const result = await pool.query(`
            SELECT id, medical_record_number, first_name, last_name, 
                   date_of_birth, gender, blood_type, phone, email
            FROM patients
            ORDER BY last_name, first_name
        `);
        
        res.json(result.rows);
    } catch (error) {
        console.error('Error fetching patients:', error);
        res.status(500).json({ error: 'Server error' });
    }
});

app.post('/api/patients', authenticate, authorize('admin', 'staff'), async (req, res) => {
    const client = await pool.connect();
    
    try {
        await client.query('BEGIN');
        
        const { 
            medical_record_number, first_name, last_name, 
            date_of_birth, ssn, gender, blood_type, 
            phone, email, address, emergency_contact, insurance_info 
        } = req.body;
        
        // Encrypt SSN
        let ssn_encrypted = null;
        if (ssn) {
            const encryptedSSN = encrypt(ssn);
            ssn_encrypted = JSON.stringify(encryptedSSN);
        }
        
        const result = await client.query(`
            INSERT INTO patients (
                medical_record_number, first_name, last_name,
                date_of_birth, ssn_encrypted, gender, blood_type,
                phone, email, address, emergency_contact, insurance_info
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
            RETURNING id, medical_record_number, first_name, last_name
        `, [
            medical_record_number, first_name, last_name,
            date_of_birth, ssn_encrypted, gender, blood_type,
            phone, email, address, emergency_contact, insurance_info
        ]);
        
        await client.query('COMMIT');
        res.status(201).json(result.rows[0]);
    } catch (error) {
        await client.query('ROLLBACK');
        console.error('Error creating patient:', error);
        res.status(500).json({ error: 'Server error' });
    } finally {
        client.release();
    }
});

// Medical encounters
app.post('/api/encounters', authenticate, authorize('doctor', 'nurse'), async (req, res) => {
    const client = await pool.connect();
    
    try {
        await client.query('BEGIN');
        
        const {
            patient_id, encounter_type, chief_complaint,
            notes, diagnosis, treatment_plan, follow_up_date
        } = req.body;
        
        const result = await client.query(`
            INSERT INTO encounters (
                patient_id, provider_id, encounter_type,
                chief_complaint, notes, diagnosis, 
                treatment_plan, follow_up_date
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
            RETURNING id, encounter_date
        `, [
            patient_id, req.user.id, encounter_type,
            chief_complaint, notes, diagnosis,
            treatment_plan, follow_up_date
        ]);
        
        await client.query('COMMIT');
        res.status(201).json(result.rows[0]);
    } catch (error) {
        await client.query('ROLLBACK');
        console.error('Error creating encounter:', error);
        res.status(500).json({ error: 'Server error' });
    } finally {
        client.release();
    }
});

// Prescriptions with drug interaction check
app.post('/api/prescriptions', authenticate, authorize('doctor'), async (req, res) => {
    const client = await pool.connect();
    
    try {
        await client.query('BEGIN');
        
        const {
            patient_id, encounter_id, medication_name,
            dosage, frequency, duration, refills, pharmacy_notes
        } = req.body;
        
        // Check for existing medications (simplified)
        const existing = await client.query(`
            SELECT medication_name FROM prescriptions 
            WHERE patient_id = $1 AND status = 'active'
        `, [patient_id]);
        
        // In production, integrate with drug interaction API
        const warnings = [];
        if (existing.rows.length > 0) {
            warnings.push('Please review for potential drug interactions');
        }
        
        const result = await client.query(`
            INSERT INTO prescriptions (
                patient_id, provider_id, encounter_id,
                medication_name, dosage, frequency, 
                duration, refills, pharmacy_notes
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
            RETURNING id, prescribed_date
        `, [
            patient_id, req.user.id, encounter_id,
            medication_name, dosage, frequency,
            duration, refills, pharmacy_notes
        ]);
        
        await client.query('COMMIT');
        res.status(201).json({ 
            prescription: result.rows[0],
            warnings 
        });
    } catch (error) {
        await client.query('ROLLBACK');
        console.error('Error creating prescription:', error);
        res.status(500).json({ error: 'Server error' });
    } finally {
        client.release();
    }
});

// Audit log access (restricted)
app.get('/api/audit-log', authenticate, authorize('admin'), async (req, res) => {
    try {
        const { start_date, end_date, user_id, action } = req.query;
        
        let query = 'SELECT * FROM audit_log WHERE 1=1';
        const params = [];
        
        if (start_date) {
            params.push(start_date);
            query += ` AND created_at >= $${params.length}`;
        }
        
        if (end_date) {
            params.push(end_date);
            query += ` AND created_at <= $${params.length}`;
        }
        
        if (user_id) {
            params.push(user_id);
            query += ` AND user_id = $${params.length}`;
        }
        
        if (action) {
            params.push(action);
            query += ` AND action = $${params.length}`;
        }
        
        query += ' ORDER BY created_at DESC LIMIT 1000';
        
        const result = await pool.query(query, params);
        res.json(result.rows);
    } catch (error) {
        console.error('Error fetching audit log:', error);
        res.status(500).json({ error: 'Server error' });
    }
});

// Start server with HTTPS in production
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Medical records API running on port ${PORT}`);
});

module.exports = app;
EOF

# Package.json
cat > package.json << 'EOF'
{
  "name": "medical-records-api",
  "version": "1.0.0",
  "description": "HIPAA-compliant medical records management API",
  "main": "src/app.js",
  "scripts": {
    "start": "node src/app.js",
    "dev": "nodemon src/app.js",
    "test": "jest --coverage"
  },
  "dependencies": {
    "express": "^4.18.2",
    "helmet": "^7.0.0",
    "express-rate-limit": "^6.7.0",
    "bcrypt": "^5.1.0",
    "jsonwebtoken": "^9.0.0",
    "pg": "^8.11.0",
    "dotenv": "^16.0.3"
  },
  "devDependencies": {
    "nodemon": "^2.0.22",
    "jest": "^29.5.0"
  }
}
EOF

npm install

Frontend Interface with Security πŸ–₯️

Create a secure web interface:

# Medical records frontend
cat > index.html << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self';">
    <title>Medical Records System</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        .header {
            background: #1e4d8b;
            color: white;
            padding: 1rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }
        .login-form {
            max-width: 400px;
            margin: 4rem auto;
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 1rem;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
        }
        .btn {
            background: #1e4d8b;
            color: white;
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            width: 100%;
        }
        .btn:hover {
            background: #164175;
        }
        .patient-list {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .patient-item {
            padding: 1rem;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .patient-item:hover {
            background: #f9f9f9;
        }
        .patient-info h3 {
            margin-bottom: 0.25rem;
            color: #1e4d8b;
        }
        .patient-details {
            color: #666;
            font-size: 0.9rem;
        }
        .security-notice {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 1rem;
            border-radius: 4px;
            margin-bottom: 1rem;
            color: #856404;
        }
        .audit-indicator {
            position: fixed;
            bottom: 1rem;
            right: 1rem;
            background: #28a745;
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            font-size: 0.85rem;
        }
    </style>
</head>
<body>
    <header class="header">
        <h1>Medical Records Management System</h1>
        <div id="user-info" style="display: none;">
            <span id="username"></span> | 
            <span id="role"></span> | 
            <button onclick="logout()">Logout</button>
        </div>
    </header>
    
    <div class="container">
        <!-- Login Form -->
        <div id="login-section">
            <form class="login-form" onsubmit="login(event)">
                <h2>Secure Login</h2>
                <div class="security-notice">
                    This is a HIPAA-compliant system. All access is logged and monitored.
                </div>
                <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" id="username" required autocomplete="username">
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" id="password" required autocomplete="current-password">
                </div>
                <button type="submit" class="btn">Login</button>
            </form>
        </div>
        
        <!-- Patient List (hidden until login) -->
        <div id="patient-section" style="display: none;">
            <h2>Patient Records</h2>
            <div class="patient-list" id="patient-list">
                <!-- Patients will be loaded here -->
            </div>
        </div>
    </div>
    
    <div class="audit-indicator">
        <span>πŸ”’ Secure Connection | All Actions Logged</span>
    </div>
    
    <script>
        let authToken = null;
        let currentUser = null;
        
        async function login(event) {
            event.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            try {
                const response = await fetch('/api/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });
                
                if (response.ok) {
                    const data = await response.json();
                    authToken = data.token;
                    currentUser = data.user;
                    
                    // Store token securely (in production, use httpOnly cookies)
                    sessionStorage.setItem('authToken', authToken);
                    
                    // Update UI
                    document.getElementById('login-section').style.display = 'none';
                    document.getElementById('patient-section').style.display = 'block';
                    document.getElementById('user-info').style.display = 'block';
                    document.getElementById('username').textContent = currentUser.name;
                    document.getElementById('role').textContent = currentUser.role.toUpperCase();
                    
                    // Load patient data
                    loadPatients();
                } else {
                    alert('Invalid credentials');
                }
            } catch (error) {
                console.error('Login error:', error);
                alert('Login failed. Please try again.');
            }
        }
        
        async function loadPatients() {
            try {
                const response = await fetch('/api/patients', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                if (response.ok) {
                    const patients = await response.json();
                    displayPatients(patients);
                } else if (response.status === 403) {
                    alert('You do not have permission to view patient records');
                }
            } catch (error) {
                console.error('Error loading patients:', error);
            }
        }
        
        function displayPatients(patients) {
            const container = document.getElementById('patient-list');
            container.innerHTML = '';
            
            patients.forEach(patient => {
                const item = document.createElement('div');
                item.className = 'patient-item';
                item.innerHTML = `
                    <div class="patient-info">
                        <h3>${patient.last_name}, ${patient.first_name}</h3>
                        <div class="patient-details">
                            MRN: ${patient.medical_record_number} | 
                            DOB: ${new Date(patient.date_of_birth).toLocaleDateString()} |
                            ${patient.gender || 'N/A'}
                        </div>
                    </div>
                    <button class="btn" onclick="viewPatient('${patient.id}')">View Record</button>
                `;
                container.appendChild(item);
            });
        }
        
        function viewPatient(patientId) {
            // In production, implement full patient record view
            console.log('Viewing patient:', patientId);
            alert('Patient record view coming soon');
        }
        
        function logout() {
            authToken = null;
            currentUser = null;
            sessionStorage.removeItem('authToken');
            
            document.getElementById('login-section').style.display = 'block';
            document.getElementById('patient-section').style.display = 'none';
            document.getElementById('user-info').style.display = 'none';
            
            // Clear form
            document.getElementById('username').value = '';
            document.getElementById('password').value = '';
        }
        
        // Check for existing session
        window.onload = function() {
            const token = sessionStorage.getItem('authToken');
            if (token) {
                authToken = token;
                // Validate token and load user data
                // For demo, we'll just show login
            }
        };
    </script>
</body>
</html>
EOF

Data Backup and Recovery πŸ’Ύ

Implement secure backup procedures:

# Backup script with encryption
cat > backup_medical_data.sh << 'EOF'
#!/bin/sh
# Medical Records Backup Script

BACKUP_DIR="/secure/backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="medical_backup_${DATE}"

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Dump database
echo "Starting database backup..."
pg_dump -U medical_admin -h localhost medical_records > "${BACKUP_DIR}/${BACKUP_FILE}.sql"

# Compress backup
gzip "${BACKUP_DIR}/${BACKUP_FILE}.sql"

# Encrypt backup with GPG
gpg --encrypt --recipient [email protected] "${BACKUP_DIR}/${BACKUP_FILE}.sql.gz"
rm "${BACKUP_DIR}/${BACKUP_FILE}.sql.gz"

# Create checksum
sha256sum "${BACKUP_DIR}/${BACKUP_FILE}.sql.gz.gpg" > "${BACKUP_DIR}/${BACKUP_FILE}.sha256"

# Copy to offsite storage (example with rclone)
# rclone copy "${BACKUP_DIR}/${BACKUP_FILE}.sql.gz.gpg" remote:medical-backups/

# Cleanup old backups (keep 90 days)
find "$BACKUP_DIR" -name "medical_backup_*.sql.gz.gpg" -mtime +90 -delete

echo "Backup completed: ${BACKUP_FILE}"

# Log backup completion
logger -t medical-backup "Backup completed successfully: ${BACKUP_FILE}"
EOF

chmod +x backup_medical_data.sh

# Add to crontab for daily backups
echo "0 2 * * * /home/medical/backup_medical_data.sh" | crontab -

Compliance Monitoring πŸ“Š

Track HIPAA compliance:

# Compliance monitoring script
cat > compliance_check.sh << 'EOF'
#!/bin/sh
# HIPAA Compliance Monitoring

echo "=== HIPAA Compliance Check ==="
echo "Date: $(date)"
echo

# Check SSL certificates
echo "SSL Certificate Status:"
openssl x509 -in /etc/nginx/ssl/cert.pem -noout -dates

# Check database encryption
echo -e "\nDatabase Encryption:"
sudo -u postgres psql -c "SHOW ssl;" medical_records

# Check user access logs
echo -e "\nRecent Access (Last 24 hours):"
sudo -u postgres psql medical_records -c "
SELECT u.username, u.role, COUNT(*) as actions
FROM audit_log a
JOIN users u ON a.user_id = u.id
WHERE a.created_at > NOW() - INTERVAL '24 hours'
GROUP BY u.username, u.role
ORDER BY actions DESC;"

# Check failed login attempts
echo -e "\nFailed Login Attempts:"
grep "Failed password" /var/log/auth.log | tail -10

# Check system patches
echo -e "\nSystem Update Status:"
apk version -l '<'

# Disk encryption status
echo -e "\nDisk Encryption:"
lsblk -o NAME,SIZE,TYPE,MOUNTPOINT,FSTYPE,CRYPT

# Generate compliance report
cat > compliance_report_$(date +%Y%m%d).txt << REPORT
HIPAA Compliance Report
Generated: $(date)

βœ“ SSL/TLS encryption enabled
βœ“ Database encryption active
βœ“ Audit logging functional
βœ“ Access controls in place
βœ“ Regular backups scheduled

Action Items:
- Review user access logs
- Update system patches
- Verify backup integrity

REPORT

echo -e "\nCompliance check completed. Report saved."
EOF

chmod +x compliance_check.sh

Best Practices πŸ“Œ

  1. Encryption everywhere - At rest and in transit
  2. Audit everything - Log all data access
  3. Principle of least privilege - Minimal access rights
  4. Regular security updates - Patch immediately
  5. Disaster recovery plan - Test restore procedures

Troubleshooting πŸ”§

Database Connection Issues

# Check PostgreSQL status
sudo rc-service postgresql status

# Verify SSL configuration
psql "sslmode=require host=localhost dbname=medical_records user=medical_admin"

# Check connection logs
tail -f /var/log/postgresql/postgresql-14-main.log

Performance Optimization

# Tune PostgreSQL for medical records
sudo -u postgres psql -c "
ALTER SYSTEM SET shared_buffers = '256MB';
ALTER SYSTEM SET effective_cache_size = '1GB';
ALTER SYSTEM SET maintenance_work_mem = '64MB';
"

sudo rc-service postgresql restart

Quick Reference πŸ“‹

# Start services
sudo rc-service postgresql start
sudo rc-service nginx start
sudo rc-service php-fpm82 start

# Check audit logs
sudo -u postgres psql medical_records -c "SELECT * FROM audit_log ORDER BY created_at DESC LIMIT 10;"

# Backup database
./backup_medical_data.sh

# Run compliance check
./compliance_check.sh

Conclusion 🎯

You’ve built a secure medical record management system on Alpine Linux! With HIPAA compliance, encryption, audit logging, and secure access controls, you’re ready to handle sensitive patient data responsibly. Remember to stay updated with healthcare regulations and security best practices. Stay secure! πŸ₯✨