Changeset 81bc7da


Ignore:
Timestamp:
07/13/26 07:55:05 (3 months ago)
Author:
Klimentina Efremova <klimentina08642@…>
Branches:
finki-main, main
Children:
62b2964
Parents:
79fff4f
Message:

Initial commit

Files:
1535 added
3 edited

Legend:

Unmodified
Added
Removed
  • README.md

    r79fff4f r81bc7da  
    1212Klimentina Efremova
    1313
    14 Aida Balikj
  • server.js

    r79fff4f r81bc7da  
    211211}
    212212
     213// ===== FIXED: requireAuth function to check both sessions and tempAdminSessions =====
    213214function requireAuth(req, res, callback) {
    214215    const cookies = parseCookies(req);
    215216    const sessionId = cookies.sessionId;
    216217
    217     if (!sessionId || !sessions.has(sessionId)) {
     218    console.log(`šŸ” requireAuth - Session ID from cookie: ${sessionId || 'none'}`);
     219    console.log(`šŸ” requireAuth - Sessions map size: ${sessions.size}`);
     220    console.log(`šŸ” requireAuth - TempAdminSessions map size: ${tempAdminSessions.size}`);
     221
     222    // Check both regular sessions and temp admin sessions
     223    if (!sessionId) {
     224        console.log(`āŒ requireAuth - No session cookie, redirecting to login`);
    218225        res.writeHead(302, { 'Location': '/login.html' });
    219226        res.end();
    … …  
    221228    }
    222229
    223     const userId = sessions.get(sessionId);
    224 
     230    // Check if session exists in regular sessions
     231    if (sessions.has(sessionId)) {
     232        const userId = sessions.get(sessionId);
     233        console.log(`āœ… requireAuth - Found in regular sessions, user: ${userId}`);
     234        callback(userId);
     235        return;
     236    }
     237
     238    // Check if session exists in temp admin sessions
    225239    if (tempAdminSessions.has(sessionId)) {
    226         if (!req.url.includes('/change-password') && !req.url.includes('/api/force-change-password')) {
     240        const userId = tempAdminSessions.get(sessionId);
     241        console.log(`āš ļø requireAuth - Found in temp admin sessions, user: ${userId}`);
     242
     243        // For temp sessions, we need to check if the request is for allowed pages
     244        // Allow access to change password page and API endpoints needed for password change
     245        const allowedPaths = [
     246            '/change-password.html',
     247            '/api/force-change-password',
     248            '/api/user',
     249            '/style.css',
     250            '/script.js',
     251            '/images/'
     252        ];
     253
     254        const isAllowed = allowedPaths.some(path => req.url.includes(path));
     255
     256        if (!isAllowed) {
     257            console.log(`šŸ”„ requireAuth - Redirecting to change password page`);
    227258            res.writeHead(302, { 'Location': '/change-password.html?forced=true' });
    228259            res.end();
    229260            return;
    230261        }
    231     }
    232 
    233     callback(userId);
     262
     263        callback(userId);
     264        return;
     265    }
     266
     267    // Session not found in either map
     268    console.log(`āŒ requireAuth - Session ID ${sessionId} not found in any session map`);
     269    res.writeHead(302, { 'Location': '/login.html' });
     270    res.end();
    234271}
    235272
    … …  
    11171154        const sessionId = cookies.sessionId;
    11181155
    1119         if (!sessionId || !sessions.has(sessionId)) {
     1156        if (!sessionId || (!sessions.has(sessionId) && !tempAdminSessions.has(sessionId))) {
    11201157            res.writeHead(302, { 'Location': '/login.html' });
    11211158            res.end();
    … …  
    11391176        const sessionId = cookies.sessionId;
    11401177
    1141         if (!sessionId || !sessions.has(sessionId)) {
     1178        if (!sessionId || (!sessions.has(sessionId) && !tempAdminSessions.has(sessionId))) {
    11421179            res.writeHead(302, { 'Location': '/login.html' });
     1180            res.end();
     1181            return;
     1182        }
     1183
     1184        if (tempAdminSessions.has(sessionId)) {
     1185            res.writeHead(302, { 'Location': '/change-password.html?forced=true' });
    11431186            res.end();
    11441187            return;
    … …  
    11791222        serveStaticFile(res, 'admin.html', 'text/html');
    11801223    } else if (pathname === '/store-owner.html') {
    1181         serveStaticFile(res, 'store-owner.html', 'text/html');
     1224        // Check if user is authenticated
     1225        const cookies = parseCookies(req);
     1226        const sessionId = cookies.sessionId;
     1227
     1228        console.log(`šŸ“„ Accessing store-owner.html - Session ID: ${sessionId || 'none'}`);
     1229
     1230        if (!sessionId || (!sessions.has(sessionId) && !tempAdminSessions.has(sessionId))) {
     1231            console.log(`āŒ store-owner.html - No valid session, redirecting to login`);
     1232            res.writeHead(302, { 'Location': '/login.html' });
     1233            res.end();
     1234            return;
     1235        }
     1236
     1237        if (tempAdminSessions.has(sessionId)) {
     1238            console.log(`āš ļø store-owner.html - Temporary session, redirecting to change password`);
     1239            res.writeHead(302, { 'Location': '/change-password.html?forced=true' });
     1240            res.end();
     1241            return;
     1242        }
     1243
     1244        // Get user from session
     1245        const userId = sessions.get(sessionId);
     1246        console.log(`šŸ“„ store-owner.html - User ID from session: ${userId}`);
     1247
     1248        // Check if this is a store owner
     1249        if (userId.startsWith('personal_')) {
     1250            const personalId = userId.replace('personal_', '');
     1251
     1252            database.database.get(
     1253                'SELECT boss_id FROM boss WHERE boss_id = ?',
     1254                [personalId],
     1255                (err, boss) => {
     1256                    if (boss) {
     1257                        // Is a store owner, serve the page
     1258                        console.log(`āœ… store-owner.html - User is a store owner, serving page`);
     1259                        serveStaticFile(res, 'store-owner.html', 'text/html');
     1260                    } else {
     1261                        // Not a store owner, redirect to appropriate page
     1262                        console.log(`āŒ store-owner.html - User is not a store owner, redirecting`);
     1263                        res.writeHead(302, { 'Location': '/dashboard.html' });
     1264                        res.end();
     1265                    }
     1266                }
     1267            );
     1268        } else if (userId === '000000') {
     1269            // Admin trying to access store owner page
     1270            console.log(`āŒ store-owner.html - Admin trying to access, redirecting to admin`);
     1271            res.writeHead(302, { 'Location': '/admin.html' });
     1272            res.end();
     1273        } else if (userId.startsWith('client_')) {
     1274            // Client trying to access store owner page
     1275            console.log(`āŒ store-owner.html - Client trying to access, redirecting to client`);
     1276            res.writeHead(302, { 'Location': '/client-dashboard.html' });
     1277            res.end();
     1278        } else {
     1279            res.writeHead(302, { 'Location': '/dashboard.html' });
     1280            res.end();
     1281        }
    11821282    } else if (pathname === '/store-employee.html') {
    1183         serveStaticFile(res, 'store-employee.html', 'text/html');
     1283        // Check if user is authenticated
     1284        const cookies = parseCookies(req);
     1285        const sessionId = cookies.sessionId;
     1286
     1287        console.log(`šŸ“„ Accessing store-employee.html - Session ID: ${sessionId || 'none'}`);
     1288
     1289        if (!sessionId || (!sessions.has(sessionId) && !tempAdminSessions.has(sessionId))) {
     1290            console.log(`āŒ store-employee.html - No valid session, redirecting to login`);
     1291            res.writeHead(302, { 'Location': '/login.html' });
     1292            res.end();
     1293            return;
     1294        }
     1295
     1296        if (tempAdminSessions.has(sessionId)) {
     1297            console.log(`āš ļø store-employee.html - Temporary session, redirecting to change password`);
     1298            res.writeHead(302, { 'Location': '/change-password.html?forced=true' });
     1299            res.end();
     1300            return;
     1301        }
     1302
     1303        // Get user from session
     1304        const userId = sessions.get(sessionId);
     1305        console.log(`šŸ“„ store-employee.html - User ID from session: ${userId}`);
     1306
     1307        // Check if this is a store employee
     1308        if (userId.startsWith('personal_')) {
     1309            const personalId = userId.replace('personal_', '');
     1310
     1311            database.database.get(
     1312                'SELECT employee_id FROM employees WHERE employee_id = ?',
     1313                [personalId],
     1314                (err, employee) => {
     1315                    if (employee) {
     1316                        // Is a store employee, serve the page
     1317                        console.log(`āœ… store-employee.html - User is a store employee, serving page`);
     1318                        serveStaticFile(res, 'store-employee.html', 'text/html');
     1319                    } else {
     1320                        // Check if they're a store owner (they can also access employee page)
     1321                        database.database.get(
     1322                            'SELECT boss_id FROM boss WHERE boss_id = ?',
     1323                            [personalId],
     1324                            (err, boss) => {
     1325                                if (boss) {
     1326                                    console.log(`āœ… store-employee.html - User is a store owner (can access), serving page`);
     1327                                    serveStaticFile(res, 'store-employee.html', 'text/html');
     1328                                } else {
     1329                                    // Not authorized
     1330                                    console.log(`āŒ store-employee.html - User is not authorized, redirecting`);
     1331                                    res.writeHead(302, { 'Location': '/dashboard.html' });
     1332                                    res.end();
     1333                                }
     1334                            }
     1335                        );
     1336                    }
     1337                }
     1338            );
     1339        } else if (userId === '000000') {
     1340            // Admin trying to access employee page
     1341            console.log(`āŒ store-employee.html - Admin trying to access, redirecting to admin`);
     1342            res.writeHead(302, { 'Location': '/admin.html' });
     1343            res.end();
     1344        } else if (userId.startsWith('client_')) {
     1345            // Client trying to access employee page
     1346            console.log(`āŒ store-employee.html - Client trying to access, redirecting to client`);
     1347            res.writeHead(302, { 'Location': '/client-dashboard.html' });
     1348            res.end();
     1349        } else {
     1350            res.writeHead(302, { 'Location': '/dashboard.html' });
     1351            res.end();
     1352        }
    11841353    } else if (pathname === '/client-dashboard.html') {
    1185         serveStaticFile(res, 'client-dashboard.html', 'text/html');
     1354        // Check if user is authenticated
     1355        const cookies = parseCookies(req);
     1356        const sessionId = cookies.sessionId;
     1357
     1358        console.log(`šŸ“„ Accessing client-dashboard.html - Session ID: ${sessionId || 'none'}`);
     1359
     1360        if (!sessionId || (!sessions.has(sessionId) && !tempAdminSessions.has(sessionId))) {
     1361            console.log(`āŒ client-dashboard.html - No valid session, redirecting to login`);
     1362            res.writeHead(302, { 'Location': '/login.html' });
     1363            res.end();
     1364            return;
     1365        }
     1366
     1367        if (tempAdminSessions.has(sessionId)) {
     1368            console.log(`āš ļø client-dashboard.html - Temporary session, redirecting to change password`);
     1369            res.writeHead(302, { 'Location': '/change-password.html?forced=true' });
     1370            res.end();
     1371            return;
     1372        }
     1373
     1374        // Get user from session
     1375        const userId = sessions.get(sessionId);
     1376        console.log(`šŸ“„ client-dashboard.html - User ID from session: ${userId}`);
     1377
     1378        // Check if this is a client
     1379        if (userId.startsWith('client_')) {
     1380            // Is a client, serve the page
     1381            console.log(`āœ… client-dashboard.html - User is a client, serving page`);
     1382            serveStaticFile(res, 'client-dashboard.html', 'text/html');
     1383        } else if (userId === '000000') {
     1384            // Admin trying to access client page
     1385            console.log(`āŒ client-dashboard.html - Admin trying to access, redirecting to admin`);
     1386            res.writeHead(302, { 'Location': '/admin.html' });
     1387            res.end();
     1388        } else if (userId.startsWith('personal_')) {
     1389            // Personal user trying to access client page
     1390            console.log(`āŒ client-dashboard.html - Personal user trying to access, redirecting to store`);
     1391            res.writeHead(302, { 'Location': '/store-owner.html' });
     1392            res.end();
     1393        } else {
     1394            res.writeHead(302, { 'Location': '/dashboard.html' });
     1395            res.end();
     1396        }
    11861397    } else if (pathname === '/products.html') {
    11871398        serveStaticFile(res, 'products.html', 'text/html');
    … …  
    21112322                        res.writeHead(200, {
    21122323                            'Content-Type': 'application/json',
    2113                             'Set-Cookie': `sessionId=${sessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
     2324                            'Set-Cookie': `sessionId=${sessionId}; HttpOnly; Path=/; Max-Age=86400; SameSite=Strict`
    21142325                        });
    21152326
    … …  
    25052716    }
    25062717
     2718    // ===== FIXED: /api/verify-2fa endpoint with proper redirect handling =====
    25072719    else if (pathname === '/api/verify-2fa' && req.method === 'POST') {
    25082720        let body = '';
    … …  
    25442756                verificationCodes.delete(email);
    25452757
    2546                 // Determine redirect based on user type
     2758                // Determine redirect based on user type - all go to change-password.html with appropriate query parameters
    25472759                let redirectTo = 'change-password.html?forced=true';
     2760
     2761                // Add redirect parameter to know where to go after password change
    25482762                if (verificationData.userType === 'store_owner') {
    25492763                    redirectTo = 'change-password.html?forced=true&redirect=store-owner.html';
    … …  
    25542768                } else if (verificationData.userType === 'client') {
    25552769                    redirectTo = 'change-password.html?forced=true&redirect=client-dashboard.html';
     2770                } else {
     2771                    redirectTo = 'change-password.html?forced=true&redirect=dashboard.html';
    25562772                }
     2773
     2774                console.log(`šŸ”„ Password change required for ${verificationData.userType}. Redirecting to: ${redirectTo}`);
     2775                console.log(`šŸ”„ Temp session created: ${tempSessionId} for user: ${verificationData.userId}`);
     2776                console.log(`šŸ” TempAdminSessions now has ${tempAdminSessions.size} entries`);
    25572777
    25582778                res.writeHead(200, {
    … …  
    26092829            }
    26102830
    2611             console.log(`āœ… ${verificationData.userType} login successful. Redirecting to: ${redirectTo}`);
     2831            console.log(`āœ… ${verificationData.userType} login successful. Session: ${sessionId}, User: ${sessions.get(sessionId)}, Redirecting to: ${redirectTo}`);
     2832            console.log(`šŸ“Š Current sessions: ${Array.from(sessions.entries()).map(([id, user]) => `${id.substring(0,8)}...:${user}`).join(', ')}`);
    26122833
    26132834            res.writeHead(200, {
    26142835                'Content-Type': 'application/json',
    2615                 'Set-Cookie': `sessionId=${sessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
     2836                'Set-Cookie': `sessionId=${sessionId}; HttpOnly; Path=/; Max-Age=86400; SameSite=Strict`
    26162837            });
    26172838
    … …  
    26302851
    26312852        if (sessionId) {
    2632             const userId = sessions.get(sessionId);
     2853            const userId = sessions.get(sessionId) || tempAdminSessions.get(sessionId);
    26332854            if (userId) {
    26342855                database.logAudit(userId, 'LOGOUT', 'auth', userId.toString(), 'User logged out', ipAddress);
    … …  
    26512872            const sessionId = cookies.sessionId;
    26522873
     2874            // Check if this is a temp session
    26532875            if (tempAdminSessions.has(sessionId)) {
    26542876                // This is a temporary session (password change required)
    … …  
    35503772                                }
    35513773
    3552                                 console.log(`Password changed successfully for user ${userId}, redirecting to ${finalRedirect}`);
     3774                                console.log(`āœ… Password changed successfully for user ${userId}, redirecting to ${finalRedirect}`);
     3775                                console.log(`New session created: ${newSessionId} -> ${sessionUserId}`);
    35533776
    35543777                                database.logAudit(userId, 'FORCED_PASSWORD_CHANGE', 'auth', userId.toString(),
    35553778                                    `${user.user_type || 'user'} forced password change completed`, ipAddress);
    35563779
    3557                                 // Set the cookie with proper options
     3780                                // Set the cookie with proper options - extended to 24 hours
    35583781                                res.writeHead(200, {
    35593782                                    'Content-Type': 'application/json',
    3560                                     'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=86400; SameSite=Strict` // Extended to 24 hours
     3783                                    'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=86400; SameSite=Strict`
    35613784                                });
    35623785
    … …  
    36263849                                                sessions.set(newSessionId, `personal_${userId}`);
    36273850
    3628                                                 console.log(`Password changed successfully for ${userType} ${userId}, redirecting to ${finalRedirect}`);
     3851                                                console.log(`āœ… Password changed successfully for ${userType} ${userId}, redirecting to ${finalRedirect}`);
     3852                                                console.log(`New session created: ${newSessionId} -> personal_${userId}`);
    36293853
    36303854                                                database.logAudit(userId, 'FORCED_PASSWORD_CHANGE', 'auth', userId.toString(),
  • view-database.js

    r79fff4f r81bc7da  
    33
    44const dbPath = path.join(__dirname, 'database', 'handcraft.db');
    5 const db = new sqlite3.Database(dbPath);
     5const db = new sqlite3.Database(dbPath, (err) => {
     6    if (err) {
     7        console.error('Error opening database:', err.message);
     8        process.exit(1);
     9    }
     10});
    611
    712console.log('\nšŸŽØ HANDCRAFT MARKETPLACE - DATABASE CONTENTS\n');
    … …  
    2530}
    2631
     32// Main execution chain
     33function executeChecks() {
     34    let currentCheck = 0;
     35
     36    const checks = [
     37        { name: 'clients', func: checkClients },
     38        { name: 'personal', func: checkPersonal },
     39        { name: 'store', func: checkStore },
     40        { name: 'product', func: checkProduct },
     41        { name: 'category', func: checkCategory },
     42        { name: 'works_in_store', func: checkWorksInStore },
     43        { name: 'permissions', func: checkPermissions },
     44        { name: 'employees', func: checkEmployees },
     45        { name: 'boss', func: checkBoss },
     46        { name: 'order', func: checkOrder },
     47        { name: 'report', func: checkReport },
     48        { name: 'refund', func: checkRefund },
     49        { name: 'image', func: checkImage },
     50        { name: 'color', func: checkColor }
     51    ];
     52
     53    function next() {
     54        currentCheck++;
     55        if (currentCheck < checks.length) {
     56            checks[currentCheck].func(next);
     57        } else {
     58            finish();
     59        }
     60    }
     61
     62    // Start with first check
     63    checks[0].func(next);
     64}
     65
    2766// Display CLIENTS table
    28 console.log('\nšŸ‘¤ CLIENTS TABLE:');
    29 console.log('================================================================================');
    30 tableExists('client', (exists) => {
    31     if (!exists) {
    32         console.log('Table does not exist');
    33         checkNext();
    34         return;
    35     }
    36 
    37     db.all('SELECT * FROM client', [], (err, rows) => {
    38         if (err) {
    39             console.log(`Error: ${err.message}`);
    40             checkNext();
    41             return;
    42         }
    43 
    44         if (!rows || rows.length === 0) {
    45             console.log('No clients found');
    46         } else {
    47             console.log(`Total: ${rows.length} clients\n`);
    48             rows.forEach((client, index) => {
    49                 console.log(`ID: ${client.client_id} | Name: ${client.first_name || ''} ${client.last_name || ''}`);
    50                 console.log(`Email: ${client.email || 'N/A'}`);
    51                 if (index < rows.length - 1) console.log('-'.repeat(80));
    52             });
    53         }
    54         checkNext();
    55     });
    56 });
     67function checkClients(next) {
     68    console.log('\nšŸ‘¤ CLIENTS TABLE:');
     69    console.log('================================================================================');
     70
     71    tableExists('client', (exists) => {
     72        if (!exists) {
     73            console.log('Table does not exist\n');
     74            if (next) next();
     75            return;
     76        }
     77
     78        db.all('SELECT * FROM client', [], (err, rows) => {
     79            if (err) {
     80                console.log(`Error: ${err.message}\n`);
     81                if (next) next();
     82                return;
     83            }
     84
     85            if (!rows || rows.length === 0) {
     86                console.log('No clients found\n');
     87            } else {
     88                console.log(`Total: ${rows.length} clients\n`);
     89                rows.forEach((client, index) => {
     90                    console.log(`ID: ${client.client_id} | Name: ${client.first_name || ''} ${client.last_name || ''}`);
     91                    console.log(`Email: ${client.email || 'N/A'}`);
     92                    if (index < rows.length - 1) console.log('-'.repeat(80));
     93                });
     94                console.log(); // Add blank line after table
     95            }
     96            if (next) next();
     97        });
     98    });
     99}
    57100
    58101// Display PERSONAL table
    59 function checkPersonal() {
     102function checkPersonal(next) {
    60103    console.log('\nšŸ‘” PERSONAL TABLE (STORE OWNERS/EMPLOYEES):');
    61104    console.log('================================================================================');
     105
    62106    tableExists('personal', (exists) => {
    63107        if (!exists) {
    64             console.log('Table does not exist');
    65             checkStore();
     108            console.log('Table does not exist\n');
     109            if (next) next();
    66110            return;
    67111        }
    … …  
    77121        `, [], (err, rows) => {
    78122            if (err) {
    79                 console.log(`Error: ${err.message}`);
    80                 checkStore();
    81                 return;
    82             }
    83 
    84             if (!rows || rows.length === 0) {
    85                 console.log('No personal records found');
     123                console.log(`Error: ${err.message}\n`);
     124                if (next) next();
     125                return;
     126            }
     127
     128            if (!rows || rows.length === 0) {
     129                console.log('No personal records found\n');
    86130            } else {
    87131                console.log(`Total: ${rows.length} personal records\n`);
    … …  
    91135                    if (index < rows.length - 1) console.log('-'.repeat(80));
    92136                });
    93             }
    94             checkStore();
     137                console.log();
     138            }
     139            if (next) next();
    95140        });
    96141    });
    … …  
    98143
    99144// Display STORE table
    100 function checkStore() {
     145function checkStore(next) {
    101146    console.log('\nšŸŖ STORE TABLE:');
    102147    console.log('================================================================================');
     148
    103149    tableExists('store', (exists) => {
    104150        if (!exists) {
    105             console.log('Table does not exist');
    106             checkProduct();
     151            console.log('Table does not exist\n');
     152            if (next) next();
    107153            return;
    108154        }
    … …  
    110156        db.all('SELECT * FROM store', [], (err, rows) => {
    111157            if (err) {
    112                 console.log(`Error: ${err.message}`);
    113                 checkProduct();
    114                 return;
    115             }
    116 
    117             if (!rows || rows.length === 0) {
    118                 console.log('No stores found');
     158                console.log(`Error: ${err.message}\n`);
     159                if (next) next();
     160                return;
     161            }
     162
     163            if (!rows || rows.length === 0) {
     164                console.log('No stores found\n');
    119165            } else {
    120166                console.log(`Total: ${rows.length} stores\n`);
    … …  
    126172                    if (index < rows.length - 1) console.log('-'.repeat(80));
    127173                });
    128             }
    129             checkProduct();
     174                console.log();
     175            }
     176            if (next) next();
    130177        });
    131178    });
    … …  
    133180
    134181// Display PRODUCT table
    135 function checkProduct() {
     182function checkProduct(next) {
    136183    console.log('\nšŸ›ļø PRODUCT TABLE:');
    137184    console.log('================================================================================');
     185
    138186    tableExists('product', (exists) => {
    139187        if (!exists) {
    140             console.log('Table does not exist');
    141             checkCategory();
     188            console.log('Table does not exist\n');
     189            if (next) next();
    142190            return;
    143191        }
    … …  
    149197        `, [], (err, rows) => {
    150198            if (err) {
    151                 console.log(`Error: ${err.message}`);
    152                 checkCategory();
    153                 return;
    154             }
    155 
    156             if (!rows || rows.length === 0) {
    157                 console.log('No products found');
     199                console.log(`Error: ${err.message}\n`);
     200                if (next) next();
     201                return;
     202            }
     203
     204            if (!rows || rows.length === 0) {
     205                console.log('No products found\n');
    158206            } else {
    159207                console.log(`Total: ${rows.length} products\n`);
    … …  
    165213                    if (index < rows.length - 1) console.log('-'.repeat(80));
    166214                });
    167             }
    168             checkCategory();
     215                console.log();
     216            }
     217            if (next) next();
    169218        });
    170219    });
    … …  
    172221
    173222// Display CATEGORY table
    174 function checkCategory() {
     223function checkCategory(next) {
    175224    console.log('\nšŸ“ CATEGORY TABLE:');
    176225    console.log('================================================================================');
     226
    177227    tableExists('category', (exists) => {
    178228        if (!exists) {
    179             console.log('Table does not exist');
    180             checkWorksInStore();
     229            console.log('Table does not exist\n');
     230            if (next) next();
    181231            return;
    182232        }
    … …  
    188238        `, [], (err, rows) => {
    189239            if (err) {
    190                 console.log(`Error: ${err.message}`);
    191                 checkWorksInStore();
    192                 return;
    193             }
    194 
    195             if (!rows || rows.length === 0) {
    196                 console.log('No categories found');
     240                console.log(`Error: ${err.message}\n`);
     241                if (next) next();
     242                return;
     243            }
     244
     245            if (!rows || rows.length === 0) {
     246                console.log('No categories found\n');
    197247            } else {
    198248                console.log(`Total: ${rows.length} categories\n`);
    … …  
    203253                    if (index < rows.length - 1) console.log('-'.repeat(80));
    204254                });
    205             }
    206             checkWorksInStore();
     255                console.log();
     256            }
     257            if (next) next();
    207258        });
    208259    });
    … …  
    210261
    211262// Display WORKS_IN_STORE table
    212 function checkWorksInStore() {
     263function checkWorksInStore(next) {
    213264    console.log('\nšŸ”— WORKS_IN_STORE TABLE:');
    214265    console.log('================================================================================');
     266
    215267    tableExists('works_in_store', (exists) => {
    216268        if (!exists) {
    217             console.log('Table does not exist');
    218             checkPermissions();
     269            console.log('Table does not exist\n');
     270            if (next) next();
    219271            return;
    220272        }
    … …  
    227279        `, [], (err, rows) => {
    228280            if (err) {
    229                 console.log(`Error: ${err.message}`);
    230                 checkPermissions();
    231                 return;
    232             }
    233 
    234             if (!rows || rows.length === 0) {
    235                 console.log('No assignments found');
     281                console.log(`Error: ${err.message}\n`);
     282                if (next) next();
     283                return;
     284            }
     285
     286            if (!rows || rows.length === 0) {
     287                console.log('No assignments found\n');
    236288            } else {
    237289                console.log(`Total: ${rows.length} assignments\n`);
    … …  
    241293                    if (index < rows.length - 1) console.log('-'.repeat(80));
    242294                });
    243             }
    244             checkPermissions();
     295                console.log();
     296            }
     297            if (next) next();
    245298        });
    246299    });
    … …  
    248301
    249302// Display PERMISSIONS table
    250 function checkPermissions() {
     303function checkPermissions(next) {
    251304    console.log('\nšŸ” PERMISSIONS TABLE:');
    252305    console.log('================================================================================');
     306
    253307    tableExists('permissions', (exists) => {
    254308        if (!exists) {
    255             console.log('Table does not exist');
    256             checkEmployees();
     309            console.log('Table does not exist\n');
     310            if (next) next();
    257311            return;
    258312        }
    … …  
    264318        `, [], (err, rows) => {
    265319            if (err) {
    266                 console.log(`Error: ${err.message}`);
    267                 checkEmployees();
    268                 return;
    269             }
    270 
    271             if (!rows || rows.length === 0) {
    272                 console.log('No permissions found');
     320                console.log(`Error: ${err.message}\n`);
     321                if (next) next();
     322                return;
     323            }
     324
     325            if (!rows || rows.length === 0) {
     326                console.log('No permissions found\n');
    273327            } else {
    274328                console.log(`Total: ${rows.length} permissions\n`);
    … …  
    278332                    if (index < rows.length - 1) console.log('-'.repeat(80));
    279333                });
    280             }
    281             checkEmployees();
     334                console.log();
     335            }
     336            if (next) next();
    282337        });
    283338    });
    … …  
    285340
    286341// Display EMPLOYEES table
    287 function checkEmployees() {
     342function checkEmployees(next) {
    288343    console.log('\nšŸ‘· EMPLOYEES TABLE:');
    289344    console.log('================================================================================');
     345
    290346    tableExists('employees', (exists) => {
    291347        if (!exists) {
    292             console.log('Table does not exist');
    293             checkBoss();
     348            console.log('Table does not exist\n');
     349            if (next) next();
    294350            return;
    295351        }
    … …  
    301357        `, [], (err, rows) => {
    302358            if (err) {
    303                 console.log(`Error: ${err.message}`);
    304                 checkBoss();
    305                 return;
    306             }
    307 
    308             if (!rows || rows.length === 0) {
    309                 console.log('No employees found');
     359                console.log(`Error: ${err.message}\n`);
     360                if (next) next();
     361                return;
     362            }
     363
     364            if (!rows || rows.length === 0) {
     365                console.log('No employees found\n');
    310366            } else {
    311367                console.log(`Total: ${rows.length} employees\n`);
    … …  
    315371                    if (index < rows.length - 1) console.log('-'.repeat(80));
    316372                });
    317             }
    318             checkBoss();
     373                console.log();
     374            }
     375            if (next) next();
    319376        });
    320377    });
    … …  
    322379
    323380// Display BOSS table
    324 function checkBoss() {
     381function checkBoss(next) {
    325382    console.log('\nšŸ‘‘ BOSS TABLE:');
    326383    console.log('================================================================================');
     384
    327385    tableExists('boss', (exists) => {
    328386        if (!exists) {
    329             console.log('Table does not exist');
    330             checkOrder();
     387            console.log('Table does not exist\n');
     388            if (next) next();
    331389            return;
    332390        }
    … …  
    338396        `, [], (err, rows) => {
    339397            if (err) {
    340                 console.log(`Error: ${err.message}`);
    341                 checkOrder();
    342                 return;
    343             }
    344 
    345             if (!rows || rows.length === 0) {
    346                 console.log('No bosses found');
     398                console.log(`Error: ${err.message}\n`);
     399                if (next) next();
     400                return;
     401            }
     402
     403            if (!rows || rows.length === 0) {
     404                console.log('No bosses found\n');
    347405            } else {
    348406                console.log(`Total: ${rows.length} bosses\n`);
    … …  
    352410                    if (index < rows.length - 1) console.log('-'.repeat(80));
    353411                });
    354             }
    355             checkOrder();
     412                console.log();
     413            }
     414            if (next) next();
    356415        });
    357416    });
    … …  
    359418
    360419// Display ORDER table
    361 function checkOrder() {
     420function checkOrder(next) {
    362421    console.log('\nšŸ“¦ ORDERS TABLE:');
    363422    console.log('================================================================================');
     423
    364424    tableExists('order', (exists) => {
    365425        if (!exists) {
    366             console.log('Table does not exist');
    367             checkReport();
     426            console.log('Table does not exist\n');
     427            if (next) next();
    368428            return;
    369429        }
    … …  
    376436        `, [], (err, rows) => {
    377437            if (err) {
    378                 console.log(`Error: ${err.message}`);
    379                 checkReport();
    380                 return;
    381             }
    382 
    383             if (!rows || rows.length === 0) {
    384                 console.log('No orders found');
     438                console.log(`Error: ${err.message}\n`);
     439                if (next) next();
     440                return;
     441            }
     442
     443            if (!rows || rows.length === 0) {
     444                console.log('No orders found\n');
    385445            } else {
    386446                console.log(`Total: ${rows.length} orders\n`);
    … …  
    392452                    if (index < rows.length - 1) console.log('-'.repeat(80));
    393453                });
    394             }
    395             checkReport();
     454                console.log();
     455            }
     456            if (next) next();
    396457        });
    397458    });
    … …  
    399460
    400461// Display REPORT table
    401 function checkReport() {
     462function checkReport(next) {
    402463    console.log('\nšŸ“Š REPORTS TABLE:');
    403464    console.log('================================================================================');
     465
    404466    tableExists('report', (exists) => {
    405467        if (!exists) {
    406             console.log('Table does not exist');
    407             checkRefund();
     468            console.log('Table does not exist\n');
     469            if (next) next();
    408470            return;
    409471        }
    … …  
    411473        db.all('SELECT * FROM report', [], (err, rows) => {
    412474            if (err) {
    413                 console.log(`Error: ${err.message}`);
    414                 checkRefund();
    415                 return;
    416             }
    417 
    418             if (!rows || rows.length === 0) {
    419                 console.log('No reports found');
     475                console.log(`Error: ${err.message}\n`);
     476                if (next) next();
     477                return;
     478            }
     479
     480            if (!rows || rows.length === 0) {
     481                console.log('No reports found\n');
    420482            } else {
    421483                console.log(`Total: ${rows.length} reports\n`);
    … …  
    425487                    if (index < rows.length - 1) console.log('-'.repeat(80));
    426488                });
    427             }
    428             checkRefund();
     489                console.log();
     490            }
     491            if (next) next();
    429492        });
    430493    });
    … …  
    432495
    433496// Display REFUND table
    434 function checkRefund() {
     497function checkRefund(next) {
    435498    console.log('\nšŸ’° REFUND TABLE:');
    436499    console.log('================================================================================');
     500
    437501    tableExists('refund', (exists) => {
    438502        if (!exists) {
    439             console.log('Table does not exist');
    440             checkImage();
     503            console.log('Table does not exist\n');
     504            if (next) next();
    441505            return;
    442506        }
    … …  
    444508        db.all('SELECT * FROM refund', [], (err, rows) => {
    445509            if (err) {
    446                 console.log(`Error: ${err.message}`);
    447                 checkImage();
    448                 return;
    449             }
    450 
    451             if (!rows || rows.length === 0) {
    452                 console.log('No refunds found');
     510                console.log(`Error: ${err.message}\n`);
     511                if (next) next();
     512                return;
     513            }
     514
     515            if (!rows || rows.length === 0) {
     516                console.log('No refunds found\n');
    453517            } else {
    454518                console.log(`Total: ${rows.length} refunds\n`);
    … …  
    459523                    if (index < rows.length - 1) console.log('-'.repeat(80));
    460524                });
    461             }
    462             checkImage();
     525                console.log();
     526            }
     527            if (next) next();
    463528        });
    464529    });
    … …  
    466531
    467532// Display IMAGE table
    468 function checkImage() {
     533function checkImage(next) {
    469534    console.log('\nšŸ–¼ļø IMAGE TABLE:');
    470535    console.log('================================================================================');
     536
    471537    tableExists('image', (exists) => {
    472538        if (!exists) {
    473             console.log('Table does not exist');
    474             checkColor();
     539            console.log('Table does not exist\n');
     540            if (next) next();
    475541            return;
    476542        }
    … …  
    478544        db.all('SELECT * FROM image', [], (err, rows) => {
    479545            if (err) {
    480                 console.log(`Error: ${err.message}`);
    481                 checkColor();
    482                 return;
    483             }
    484 
    485             if (!rows || rows.length === 0) {
    486                 console.log('No images found');
     546                console.log(`Error: ${err.message}\n`);
     547                if (next) next();
     548                return;
     549            }
     550
     551            if (!rows || rows.length === 0) {
     552                console.log('No images found\n');
    487553            } else {
    488554                console.log(`Total: ${rows.length} images\n`);
    … …  
    491557                    if (index < rows.length - 1) console.log('-'.repeat(80));
    492558                });
    493             }
    494             checkColor();
     559                console.log();
     560            }
     561            if (next) next();
    495562        });
    496563    });
    … …  
    498565
    499566// Display COLOR table
    500 function checkColor() {
     567function checkColor(next) {
    501568    console.log('\nšŸŽØ COLOR TABLE:');
    502569    console.log('================================================================================');
     570
    503571    tableExists('color', (exists) => {
    504572        if (!exists) {
    505             console.log('Table does not exist');
    506             finish();
     573            console.log('Table does not exist\n');
     574            if (next) next();
    507575            return;
    508576        }
    … …  
    510578        db.all('SELECT * FROM color', [], (err, rows) => {
    511579            if (err) {
    512                 console.log(`Error: ${err.message}`);
    513                 finish();
    514                 return;
    515             }
    516 
    517             if (!rows || rows.length === 0) {
    518                 console.log('No colors found');
     580                console.log(`Error: ${err.message}\n`);
     581                if (next) next();
     582                return;
     583            }
     584
     585            if (!rows || rows.length === 0) {
     586                console.log('No colors found\n');
    519587            } else {
    520588                console.log(`Total: ${rows.length} colors\n`);
    … …  
    523591                    if (index < rows.length - 1) console.log('-'.repeat(80));
    524592                });
    525             }
    526             finish();
    527         });
    528     });
    529 }
    530 
    531 // Start the chain of checks
    532 function checkNext() {
    533     checkPersonal();
    534 }
    535 
     593                console.log();
     594            }
     595            if (next) next();
     596        });
     597    });
     598}
     599
     600// Finish and close database
    536601function finish() {
    537     console.log('\n' + '='.repeat(80));
     602    console.log('='.repeat(80));
    538603    console.log('āœ… Database inspection complete');
    539604    console.log('='.repeat(80) + '\n');
    540605
    541     db.close();
    542 }
    543 
    544 // Start with CLIENTS
    545 checkNext();
     606    db.close((err) => {
     607        if (err) {
     608            console.error('Error closing database:', err.message);
     609        }
     610    });
     611}
     612
     613// Start the execution chain
     614executeChecks();
Note: See TracChangeset for help on using the changeset viewer.