« Back to History
company_setup.php
|
20260723_000646.php
Initial Domain Snapshot
Copy Code
<?php // ============================================================================ // Developer Console (ERP Setup) // Purpose: Developer-only console to create companies and assign owner users. // Compatible with your existing users table (name, username, password_hash, etc.) // ============================================================================ // ERP Session Compatibility $erp_sess_dir = dirname(__DIR__) . '/erp/tmp_sessions'; if (!is_dir($erp_sess_dir)) { @mkdir($erp_sess_dir, 0775, true); } @ini_set('session.save_path', $erp_sess_dir); if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); } ini_set('display_errors', 1); error_reporting(E_ALL); // --------------------------------------------------------------- // Locate and include ERP DB connection (core/db.php) // --------------------------------------------------------------- $included = false; $try_paths = [ __DIR__ . '/../erp/core/db.php', __DIR__ . '/../../erp/core/db.php', __DIR__ . '/erp/core/db.php', __DIR__ . '/../../core/db.php', ]; foreach ($try_paths as $p) { if (file_exists($p)) { require_once $p; $included = true; break; } } if (!$included) { echo "<h2>Developer Console Error:</h2>"; echo "<p>Cannot locate core/db.php. Ensure proper path as per ERP structure.</p>"; exit; } if (!isset($pdo) || !$pdo instanceof PDO) { echo "<h2>Developer Console Error:</h2>"; echo "<p>\$pdo not found. Check core/db.php configuration.</p>"; exit; } // --------------------------------------------------------------- // CSRF + Utility functions // --------------------------------------------------------------- function csrf_token() { if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(24)); } return $_SESSION['csrf_token']; } function csrf_check($t) { return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], (string)$t); } function flash($msg, $type='info') { $_SESSION['flash'][] = ['msg'=>$msg, 'type'=>$type]; } function show_flashes() { if(empty($_SESSION['flash'])) return; foreach($_SESSION['flash'] as $f) { $bg = $f['type']=='error' ? '#f8d7da' : ($f['type']=='success' ? '#d4edda' : '#fff3cd'); echo "<div style='background:$bg;padding:8px;border-radius:5px;margin-bottom:8px'>{$f['msg']}</div>"; } unset($_SESSION['flash']); } function h($s){return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8');} function find_developer_account(PDO $pdo, string $username): ?array { $st = $pdo->prepare("SELECT id, username, password_hash FROM developers WHERE username=? LIMIT 1"); $st->execute([$username]); $row = $st->fetch(PDO::FETCH_ASSOC); if ($row) { $row['auth_source'] = 'developers'; return $row; } $st = $pdo->prepare("SELECT id, username, password_hash, role, is_active FROM users WHERE username=? LIMIT 1"); $st->execute([$username]); $row = $st->fetch(PDO::FETCH_ASSOC); if (!$row) { return null; } if (strtolower((string)($row['role'] ?? '')) !== 'developer') { return null; } if (isset($row['is_active']) && (int)$row['is_active'] !== 1) { return null; } $row['auth_source'] = 'users'; return $row; } // --------------------------------------------------------------- // Ensure developer & audit tables exist // --------------------------------------------------------------- $pdo->exec(" CREATE TABLE IF NOT EXISTS developers ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(100) UNIQUE, password_hash VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; "); $pdo->exec(" CREATE TABLE IF NOT EXISTS developer_audit ( id INT AUTO_INCREMENT PRIMARY KEY, developer_id INT NULL, action VARCHAR(255), payload TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; "); // --------------------------------------------------------------- // Seed default developer (first-time use) // --------------------------------------------------------------- try { $c = (int)$pdo->query("SELECT COUNT(*) FROM developers")->fetchColumn(); if ($c === 0) { $u = 'dev'; $p = 'dev123!Change'; $h = password_hash($p, PASSWORD_DEFAULT); $pdo->prepare("INSERT INTO developers (username, password_hash) VALUES (?,?)")->execute([$u,$h]); $_SESSION['dev_seed_notice'] = "Seeded developer user <b>$u</b> / <b>$p</b>. Change password immediately."; } } catch (Exception $e) {} // --------------------------------------------------------------- // Auth handling // --------------------------------------------------------------- $logged_in = false; $developer = null; if (!empty($_SESSION['developer_id'])) { $auth_source = $_SESSION['developer_auth_source'] ?? 'developers'; if ($auth_source === 'users') { $st = $pdo->prepare("SELECT id, username, name, role, is_active FROM users WHERE id=? LIMIT 1"); $st->execute([$_SESSION['developer_id']]); $developer = $st->fetch(PDO::FETCH_ASSOC); if ($developer && strtolower((string)($developer['role'] ?? '')) === 'developer' && (int)($developer['is_active'] ?? 0) === 1) { $logged_in = true; } } else { $st = $pdo->prepare("SELECT id, username FROM developers WHERE id=? LIMIT 1"); $st->execute([$_SESSION['developer_id']]); $developer = $st->fetch(PDO::FETCH_ASSOC); if ($developer) { $logged_in = true; } } } if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='login') { if (!csrf_check($_POST['csrf'] ?? '')) { flash('Invalid CSRF token','error'); header("Location: ".$_SERVER['PHP_SELF']); exit; } $user = trim($_POST['username']??''); $pass = $_POST['password']??''; $r = find_developer_account($pdo, $user); if ($r && password_verify($pass,$r['password_hash'])) { $_SESSION['developer_id'] = $r['id']; $_SESSION['developer_auth_source'] = $r['auth_source'] ?? 'developers'; flash('Login successful','success'); } else { flash('Invalid credentials','error'); } header("Location: ".$_SERVER['PHP_SELF']); exit; } if (isset($_GET['action']) && $_GET['action']==='logout') { unset($_SESSION['developer_id']); unset($_SESSION['developer_auth_source']); flash('Logged out','info'); header("Location: ".$_SERVER['PHP_SELF']); exit; } // --------------------------------------------------------------- // Developer actions (create company / owner) // --------------------------------------------------------------- if ($logged_in && $_SERVER['REQUEST_METHOD']==='POST') { $act = $_POST['action']??''; if (!csrf_check($_POST['csrf']??'')) { flash('Invalid CSRF token','error'); header("Location: ".$_SERVER['PHP_SELF']); exit; } if ($act==='create_company') { $name = trim($_POST['company_name']??''); $short = trim($_POST['company_short']??''); if ($name==='') flash('Company name required','error'); else { $st=$pdo->prepare("INSERT INTO companies (name, short_name) VALUES (?,?)"); $st->execute([$name, $short?:null]); $cid=$pdo->lastInsertId(); $pdo->prepare("INSERT INTO developer_audit (developer_id,action,payload) VALUES (?,?,?)") ->execute([$_SESSION['developer_id'],'create_company',json_encode(['company_id'=>$cid,'name'=>$name])]); flash("Company created (ID: $cid)",'success'); } header("Location: ".$_SERVER['PHP_SELF']); exit; } if ($act==='create_owner') { $cid = (int)($_POST['company_id']??0); $username = trim($_POST['owner_username']??''); $pass = $_POST['owner_password']??''; $name = trim($_POST['owner_fullname']??''); $email = trim($_POST['owner_email']??''); $mobile = trim($_POST['owner_mobile']??''); if ($cid<=0 || $username==='' || $pass==='') { flash('Company, username & password required','error'); } else { try { $pdo->beginTransaction(); $check = $pdo->prepare("SELECT id FROM companies WHERE id=?"); $check->execute([$cid]); if(!$check->fetchColumn()) throw new Exception("Invalid company ID"); $hash = password_hash($pass, PASSWORD_DEFAULT); $ins = $pdo->prepare(" INSERT INTO users (company_id, name, username, email, mobile, password_hash, role, is_active, created_at) VALUES (:cid,:n,:u,:e,:m,:p,:r,1,NOW()) "); $ins->execute([ ':cid'=>$cid, ':n'=>$name ?: $username, ':u'=>$username, ':e'=>$email ?: null, ':m'=>$mobile ?: null, ':p'=>$hash, ':r'=>'owner' ]); $uid=$pdo->lastInsertId(); $pdo->prepare("INSERT INTO developer_audit (developer_id,action,payload) VALUES (?,?,?)") ->execute([$_SESSION['developer_id'],'create_owner',json_encode(['user_id'=>$uid,'company_id'=>$cid,'username'=>$username])]); $pdo->commit(); flash("Owner created successfully (User ID: $uid)",'success'); } catch(Exception $e){ $pdo->rollBack(); flash('Error creating owner: '.$e->getMessage(),'error'); } } header("Location: ".$_SERVER['PHP_SELF']); exit; } } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Developer Console</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body{font-family:Inter,Arial,sans-serif;background:#f4f6f8;margin:0;padding:20px;} .card{background:#fff;padding:18px;border-radius:10px;max-width:900px;margin:20px auto;box-shadow:0 2px 5px rgba(0,0,0,0.05);} .btn{background:#0b5fff;color:#fff;padding:8px 14px;border:none;border-radius:6px;cursor:pointer;text-decoration:none;display:inline-block;} .btn:hover{opacity:.9;} .topbar{display:flex;justify-content:space-between;align-items:center;max-width:900px;margin:0 auto;} .topbar-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;justify-content:flex-end;} input,select{width:100%;padding:8px;margin-bottom:10px;border:1px solid #ccc;border-radius:4px;} label{font-weight:600;margin-top:6px;display:block;} table{width:100%;border-collapse:collapse;} th,td{padding:6px;border-top:1px solid #eee;text-align:left;} .note{background:#e7f1ff;padding:10px;border-radius:6px;margin-bottom:12px;} </style> </head> <body> <div class="topbar"> <div><h2>Developer Console</h2><small>For internal ERP setup: create company & owner</small></div> <div class="topbar-actions"> <a href="dashboard.php" class="btn">Back to Dashboard</a> <?php if($logged_in): ?> <span>Signed in as <b><?=h($developer['username'])?></b></span> <a href="?action=logout" class="btn">Logout</a> <?php endif; ?> </div> </div> <div class="card"> <?php show_flashes(); ?> <?php if(!empty($_SESSION['dev_seed_notice'])): ?> <div class="note"><?=$_SESSION['dev_seed_notice']?></div> <?php unset($_SESSION['dev_seed_notice']); ?> <?php endif; ?> <?php if(!$logged_in): ?> <h3>Login</h3> <form method="post"> <input type="hidden" name="action" value="login"> <input type="hidden" name="csrf" value="<?=h(csrf_token())?>"> <label>Username</label> <input name="username" required> <label>Password</label> <input type="password" name="password" required> <button class="btn">Login</button> </form> <?php else: ?> <h3>Create Company</h3> <form method="post"> <input type="hidden" name="action" value="create_company"> <input type="hidden" name="csrf" value="<?=h(csrf_token())?>"> <label>Company Name</label> <input name="company_name" required> <label>Short Name</label> <input name="company_short"> <button class="btn">Create Company</button> </form> <hr> <h3>Create Company Owner</h3> <form method="post"> <input type="hidden" name="action" value="create_owner"> <input type="hidden" name="csrf" value="<?=h(csrf_token())?>"> <label>Company</label> <select name="company_id" required> <option value="">-- select company --</option> <?php $st=$pdo->query("SELECT id,name FROM companies ORDER BY id DESC"); while($r=$st->fetch(PDO::FETCH_ASSOC)){ echo "<option value='{$r['id']}'>".h($r['id'].' — '.$r['name'])."</option>"; } ?> </select> <label>Username</label> <input name="owner_username" required> <label>Password</label> <input type="password" name="owner_password" required> <label>Full Name</label> <input name="owner_fullname"> <label>Email</label> <input name="owner_email" type="email"> <label>Mobile</label> <input name="owner_mobile" type="text"> <button class="btn">Create Owner</button> </form> <hr> <h4>Recent Developer Actions</h4> <table> <tr><th>When</th><th>Action</th><th>Payload</th></tr> <?php $q=$pdo->query("SELECT da.*,d.username AS dev FROM developer_audit da LEFT JOIN developers d ON d.id=da.developer_id ORDER BY da.id DESC LIMIT 25"); while($r=$q->fetch(PDO::FETCH_ASSOC)){ echo "<tr><td>".h($r['created_at'])." by ".h($r['dev'])."</td><td>".h($r['action'])."</td><td><pre style='white-space:pre-wrap;margin:0'>".h($r['payload'])."</pre></td></tr>"; } ?> </table> <?php endif; ?> </div> </body> </html>