Changeset 81bc7da for server.js


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

File:
1 edited

Legend:

Unmodified
Added
Removed
  • 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(),
Note: See TracChangeset for help on using the changeset viewer.