Skip to content

Commit 2f040b5

Browse files
Updated Profile page
1 parent c8ba1ac commit 2f040b5

File tree

6 files changed

+95
-4
lines changed

6 files changed

+95
-4
lines changed

backend/.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,6 @@ lerna-debug.log*
2020
# OS generated files
2121
.DS_Store
2222
Thumbs.db
23+
24+
25+
config/serviceAccountKey.json

backend/config/firebaseAdmin.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import * as admin from 'firebase-admin';
2+
import dotenv from 'dotenv';
3+
import path from 'path'; // Import path module
4+
5+
dotenv.config(); // Load environment variables
6+
7+
const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_KEY_PATH;
8+
9+
if (!serviceAccountPath) {
10+
console.error(' FATAL ERROR: FIREBASE_SERVICE_ACCOUNT_KEY_PATH is not defined in .env file');
11+
process.exit(1);
12+
}
13+
14+
// Construct the absolute path from the project's root directory (where package.json is)
15+
const absolutePath = path.resolve(process.cwd(), serviceAccountPath);
16+
17+
try {
18+
// eslint-disable-next-line @typescript-eslint/no-var-requires
19+
const serviceAccount = require(absolutePath); // Use the absolute path
20+
21+
admin.initializeApp({
22+
credential: admin.credential.cert(serviceAccount)
23+
});
24+
25+
console.log(' Firebase Admin SDK Initialized Successfully');
26+
27+
} catch (error: any) {
28+
console.error('Firebase Admin SDK Initialization Error:', error.message);
29+
console.error(`Attempted to load key from: ${absolutePath}`);
30+
console.error('Ensure the path in .env is correct (relative to project root) and the JSON file exists.');
31+
process.exit(1);
32+
}
33+
34+
export default admin;
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { Request, Response, NextFunction } from 'express';
2+
import admin from '../config/firebaseAdmin'; // Import initialized admin SDK
3+
4+
// Extend the Express Request type to include our 'user' property
5+
declare global {
6+
// eslint-disable-next-line @typescript-eslint/no-namespace
7+
namespace Express {
8+
interface Request {
9+
// The 'user' property will hold the decoded Firebase token
10+
user?: admin.auth.DecodedIdToken;
11+
}
12+
}
13+
}
14+
15+
/**
16+
* Middleware to protect routes.
17+
* Verifies the Firebase ID token from the Authorization header.
18+
* If valid, attaches the decoded token (including user UID) to req.user.
19+
* If invalid, sends a 401 Unauthorized response.
20+
*/
21+
export const protect = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
22+
let token: string | undefined;
23+
24+
// 1. Check for Authorization header and ensure it starts with "Bearer "
25+
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
26+
try {
27+
// 2. Extract the token (the part *after* "Bearer ")
28+
token = req.headers.authorization.split(' ')[1];
29+
30+
if (!token) {
31+
res.status(401).json({ message: 'Not authorized, token format is invalid' });
32+
return;
33+
}
34+
35+
// 3. Verify the token using the Firebase Admin SDK
36+
const decodedToken = await admin.auth().verifyIdToken(token);
37+
38+
// 4. Token is valid! Attach the decoded user info to the request object
39+
req.user = decodedToken;
40+
41+
// 5. Pass control to the next function (the actual route handler)
42+
next();
43+
44+
} catch (error) {
45+
// Token is invalid (expired, wrong signature, etc.)
46+
console.error('Token verification failed:', error);
47+
res.status(401).json({ message: 'Not authorized, token verification failed' });
48+
}
49+
} else {
50+
// No Authorization header found
51+
res.status(401).json({ message: 'Not authorized, no token provided' });
52+
}
53+
};

backend/src/server.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@ import express, { Express, Request, Response } from 'express';
22
import cors from 'cors';
33
import dotenv from 'dotenv';
44
import connectDB from './db';
5+
import '../config/firebaseAdmin'; // <-- CORRECTED PATH HERE
56
// --- Import Routes ---
67
import profileRoutes from './routes/profile';
78
import tripRoutes from './routes/trips';
89
import userRoutes from './routes/users';
910
// -------------------
1011

1112
dotenv.config();
12-
connectDB();
13+
connectDB(); // Connect to DB
1314

1415
const app: Express = express();
1516
const port = process.env.PORT || 5001;
@@ -30,6 +31,6 @@ app.use('/api/users', userRoutes);
3031
// ------------------
3132

3233
app.listen(port, () => {
33-
console.log(`🚀 Backend server listening on http://localhost:${port}`);
34+
console.log(` Backend server listening on http://localhost:${port}`);
3435
});
3536

frontend/src/components/UserNav.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Link, useNavigate } from 'react-router-dom';
1+
import { useNavigate } from 'react-router-dom';
22
import { Button } from './ui/button'; // Standard button
33
import { auth } from '../firebase'; // Go UP one level from components to src
44
import { signOut } from 'firebase/auth';

frontend/src/pages/Profile.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { useAuth } from '../AuthContext';
1212
// --- End Corrected Paths ---
1313
import { signOut, updateProfile } from 'firebase/auth';
1414
import { motion } from 'framer-motion';
15-
import { Car, Loader2, Edit, X, ArrowUp, ArrowDown, Filter, Trash2, AlertTriangle, ArrowUpDown } from 'lucide-react';
15+
import { Car, Loader2, Edit, X, ArrowUp, ArrowDown,Trash2, AlertTriangle, ArrowUpDown } from 'lucide-react';
1616
import { Link, useNavigate } from 'react-router-dom';
1717
import { format, isValid } from 'date-fns'; // Make sure date-fns is installed: pnpm add date-fns
1818

0 commit comments

Comments
 (0)