diff --git a/backend/src/app.js b/backend/src/app.js index b0ac441..b7b1876 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -17,10 +17,6 @@ const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET; const DATABASE = client.db("vehicleDB"); const EMAIL = process.env.EMAIL; - -console.log("\n\nPROCESS APP PAGE"+CLIENT_ID) -console.log("PROCESS APP PAGE"+CLIENT_SECRET) - const app = express(); const googleOAuthURL = getGoogleOauthURL(); @@ -34,15 +30,13 @@ app.use(bodyParser.json()); const port = process.env.PORT || 8080; -const JWTSecret = "test123"; +const JWTSecret = process.env.JWTSecret; const getAccessAndBearerTokenUrl = (access_token) => { return `https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=${access_token}`; } app.get( '/api/auth/google/callback', async (req, res) => { - console.log("Hit callback route"); - const { code } = req.query; console.log(code); @@ -82,7 +76,6 @@ app.get( '/api/auth/google/callback', async (req, res) => { }); app.get('/api/auth/google/url', async (req, res) => { - console.log("hit /api/auth/google/url") res.status(200).json({url: googleOAuthURL}); }); @@ -159,11 +152,32 @@ const updateOrCreateUserFromOauth = async (oauthUserInfo) => { * @param configId - The config_id of the vehicle */ app.get('/api/get-vehicle-info', async (req, res) => { - const vehicle = DATABASE.collection("configurations"); - const configId = req.query.configId; - const getConfiguration = await vehicle.findOne({config_id: parseInt(configId)}); + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ + + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + + console.log("Decoded: "+decoded); + + const vehicle = DATABASE.collection("configurations"); + const configId = req.query.configId; + const getConfiguration = await vehicle.findOne({config_id: parseInt(configId)}); - res.json(getConfiguration); + res.json(getConfiguration); + }); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } }); /*** @@ -173,25 +187,43 @@ app.get('/api/get-vehicle-info', async (req, res) => { */ app.get('/api/get-vehicle-history', async (req, res) => { - const history = DATABASE.collection("user_vehicle_info"); - const configId = req.query.configId; - + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - const getHistory = await history.aggregate([ - { - $match: { - config_id: parseInt(configId), - email: EMAIL - } - }, - { - $project: { - _id: 0, - completed_maintenance: 1 + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); } - } - ]).toArray(); - res.send(getHistory); + const history = DATABASE.collection("user_vehicle_info"); + const configId = req.query.configId; + + + const getHistory = await history.aggregate([ + { + $match: { + config_id: parseInt(configId), + email: EMAIL + } + }, + { + $project: { + _id: 0, + completed_maintenance: 1 + } + } + ]).toArray(); + res.send(getHistory); + }); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } }); /*** @@ -204,19 +236,37 @@ app.get('/api/get-vehicle-history', async (req, res) => { * @param email - The email of the user */ app.post('/api/add-maintenance-history', async (req, res) => { - const garage = DATABASE.collection("user_vehicle_info"); - const configId = req.query.configId; - const maintenance = { - type: req.body.type, - date: req.body.date, - maintenance: req.body.maintenance, - cost: parseInt(req.body.cost) - }; - const add = await garage.updateOne( - { email: EMAIL, config_id: parseInt(configId) }, - { $push: { completed_maintenance: maintenance } } - ); - return res.json(add.modifiedCount); + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ + + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const garage = DATABASE.collection("user_vehicle_info"); + const configId = req.query.configId; + const maintenance = { + type: req.body.type, + date: req.body.date, + maintenance: req.body.maintenance, + cost: parseInt(req.body.cost) + }; + const add = await garage.updateOne( + { email: EMAIL, config_id: parseInt(configId) }, + { $push: { completed_maintenance: maintenance } } + ); + return res.json(add.modifiedCount); + }); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } }); /*** @@ -233,100 +283,172 @@ app.post('/api/add-maintenance-history', async (req, res) => { * @param email - The email of the user */ app.post('/api/update-maintenance-history', async (req, res) => { - const garage = DATABASE.collection("user_vehicle_info"); - const { - old_type, old_date, old_maintenance, old_cost, - new_type, new_date, new_maintenance, new_cost - } = req.body; - const update = await garage.updateOne( - { - email: EMAIL, - config_id: parseInt(req.query.configId), - "completed_maintenance.type": old_type, - "completed_maintenance.date": old_date, - "completed_maintenance.maintenance": old_maintenance, - "completed_maintenance.cost": parseInt(old_cost) - }, - { - $set: { - "completed_maintenance.$.type": new_type, - "completed_maintenance.$.date": new_date, - "completed_maintenance.$.maintenance": new_maintenance, - "completed_maintenance.$.cost": parseInt(new_cost) + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ + + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); } + const garage = DATABASE.collection("user_vehicle_info"); + const { + old_type, old_date, old_maintenance, old_cost, + new_type, new_date, new_maintenance, new_cost + } = req.body; + const update = await garage.updateOne( + { + email: EMAIL, + config_id: parseInt(req.query.configId), + "completed_maintenance.type": old_type, + "completed_maintenance.date": old_date, + "completed_maintenance.maintenance": old_maintenance, + "completed_maintenance.cost": parseInt(old_cost) + }, + { + $set: { + "completed_maintenance.$.type": new_type, + "completed_maintenance.$.date": new_date, + "completed_maintenance.$.maintenance": new_maintenance, + "completed_maintenance.$.cost": parseInt(new_cost) + } + }); + return res.json(update.modifiedCount); }); - return res.json(update.modifiedCount); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } }); app.delete('/api/delete-maintenance-history', async (req, res) => { - const garage = DATABASE.collection("user_vehicle_info"); - - const { type, date, maintenance, cost } = req.body; - const deletion = await garage.updateOne( - { - email: EMAIL, - config_id: parseInt(req.query.configId) - }, - {$pull: + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ + + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const garage = DATABASE.collection("user_vehicle_info"); + + const { type, date, maintenance, cost } = req.body; + const deletion = await garage.updateOne( { - completed_maintenance: { - type: type, - date: date, - maintenance: maintenance, - cost: cost - } + email: EMAIL, + config_id: parseInt(req.query.configId) + }, + {$pull: + { + completed_maintenance: { + type: type, + date: date, + maintenance: maintenance, + cost: cost + } + } } - } - ); - return res.json(deletion.modifiedCount); + ); + return res.json(deletion.modifiedCount); + }); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } }); /*** * This route is used to get the user's vehicles from the DATABASE */ app.get('/api/get-user-vehicles', async (req, res) => { - const garage = DATABASE.collection("user_garage"); - + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - const vehicles = await garage.aggregate([ - { - $match: { - email: EMAIL - } - }, - { - $lookup: { - from: 'configurations', - localField: 'vehicle_config_ids', - foreignField: 'config_id', - as: 'configurations' - } - }, - { - $unwind: '$configurations' - }, - { - $project: { - _id: 0, - configurations: 1, + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); } - } - ]).toArray(); - res.send(vehicles); + const garage = DATABASE.collection("user_garage"); + + + const vehicles = await garage.aggregate([ + { + $match: { + email: EMAIL + } + }, + { + $lookup: { + from: 'configurations', + localField: 'vehicle_config_ids', + foreignField: 'config_id', + as: 'configurations' + } + }, + { + $unwind: '$configurations' + }, + { + $project: { + _id: 0, + configurations: 1, + } + } + ]).toArray(); + res.send(vehicles); + }); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } }); app.delete('/api/delete-user-vehicle', async (req, res) => { - const garage = DATABASE.collection("user_garage"); - const vehicInfo = DATABASE.collection("user_vehicle_info"); + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - const { config_id } = req.body; - const deletion = await garage.updateOne( - {email: EMAIL}, - {$pull: { vehicle_config_ids: config_id } } - ); - const deletionTwo = await vehicInfo.deleteOne( - {email: EMAIL, config_id: config_id} - ); - return res.json(deletion.modifiedCount+deletionTwo.deletedCount); + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const garage = DATABASE.collection("user_garage"); + const vehicInfo = DATABASE.collection("user_vehicle_info"); + + const { config_id } = req.body; + const deletion = await garage.updateOne( + {email: EMAIL}, + {$pull: { vehicle_config_ids: config_id } } + ); + const deletionTwo = await vehicInfo.deleteOne( + {email: EMAIL, config_id: config_id} + ); + return res.json(deletion.modifiedCount+deletionTwo.deletedCount); + }); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } }); @@ -339,26 +461,45 @@ app.get('/api/get-maintenance', async (req , res) => { const odometer = req.query.odometer; let maintenance = null; - const docObject = await message.findOne({config_id}); + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - if(docObject && docObject.schedules){ - for (const schedule of docObject.schedules) { - const mileage = parseInt(schedule.service_schedule_mileage.replace(',', '')); + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if (err) { + res.status(401).json({message: "Invalid Token"}); + } + + const docObject = await message.findOne({config_id}); + + if (docObject && docObject.schedules) { + for (const schedule of docObject.schedules) { + const mileage = parseInt(schedule.service_schedule_mileage.replace(',', '')); + + if (mileage > odometer) { + maintenance = schedule; + break; + } + } + } - if (mileage > odometer) { - maintenance = schedule; - break; + if (maintenance) { + res.send(maintenance); + } else { + res.status(404).json({message: "No maintenance found for this vehicle"}); } } + ); } - - if(maintenance){ - res.send(maintenance); - } else{ - res.status(404).json({message: "No maintenance found for this vehicle"}); + catch(err) { + res.status(500).json({message: "Error Validating User"}); } -}) - +}); app.get('/api/get-config-id', async (req, res) => { const year = req.query.year; @@ -370,26 +511,62 @@ app.get('/api/get-config-id', async (req, res) => { if(!year || !make || !model || !engine || !transmission) { return res.status(400).json({message: "Missing required fields"}); } - const database = client.db("vehicleDB"); + else{ + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - const message = DATABASE.collection("configurations"); + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const message = DATABASE.collection("configurations"); + + const config_id = await message.findOne({year: parseInt(year), make: make, model: model, engine: engine, transmission: transmission}); - const config_id = await message.findOne({year: parseInt(year), make: make, model: model, engine: engine, transmission: transmission}); - console.log("config_id: "+config_id.config_id); + res.send(config_id); - res.send(config_id); + }); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } + + } }) app.get('/api/get-years', async (req, res) => { - const database = client.db("vehicleDB"); - const configurations = database.collection("configurations"); - const years = await configurations.aggregate([ - { $group: { _id: "$year", years: { $addToSet: "$year" } }}, - { $sort: { _id: 1 }} - ]).toArray(); - console.log("years ", years); - res.send(years); -}) + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ + + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const database = client.db("vehicleDB"); + const configurations = database.collection("configurations"); + const years = await configurations.aggregate([ + { $group: { _id: "$year", years: { $addToSet: "$year" } }}, + { $sort: { _id: 1 }} + ]).toArray(); + res.send(years); + }); + } + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } +}); app.get('/api/get-makes', async (req, res) => { const carYear = req.query.year; @@ -397,41 +574,75 @@ app.get('/api/get-makes', async (req, res) => { if(!carYear) { return res.status(400).json({message: "Missing required fields"}); } + else{ + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - const database = client.db("vehicleDB"); - const configurations = database.collection("configurations"); + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const database = client.db("vehicleDB"); + const configurations = database.collection("configurations"); - const makes = await configurations.aggregate([ - { $match: { year: parseInt(carYear) }}, - { $group: { _id: "$make", makes: { $addToSet: "$make" } }}, - { $sort: { _id: 1 }} - ]).toArray(); - - const uniqueMakes = makes.map(make => make._id); + const makes = await configurations.aggregate([ + { $match: { year: parseInt(carYear) }}, + { $group: { _id: "$make", makes: { $addToSet: "$make" } }}, + { $sort: { _id: 1 }} + ]).toArray(); - res.send(uniqueMakes); -}) + const uniqueMakes = makes.map(make => make._id); + + res.send(uniqueMakes); + })} + catch(err) { + res.status(500).json({message: "Error Validating User"}); + + } +}}); app.get('/api/get-models', async (req, res) => { const year = req.query.year; const make = req.query.make; - console.log("year: "+ year + " make: "+make); if(!year || !make) { return res.status(400).json({message: "Missing required fields"}); } + else{ + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - const database = client.db("vehicleDB"); - const configurations = database.collection("configurations"); - const models = await configurations.aggregate([ - { $match: { year: parseInt(year), make: make }}, - { $group: { _id: "$model", models: { $addToSet: "$model" } }}, - { $sort: { _id: 1 }} - ]).toArray(); + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const database = client.db("vehicleDB"); + const configurations = database.collection("configurations"); + const models = await configurations.aggregate([ + { $match: { year: parseInt(year), make: make }}, + { $group: { _id: "$model", models: { $addToSet: "$model" } }}, + { $sort: { _id: 1 }} + ]).toArray(); + + const uniqueModels = models.map(model => model._id); + res.send(uniqueModels); + })} + catch(err) { + res.status(500).json({message: "Error Validating User"}); + }} - const uniqueModels = models.map(model => model._id); - console.log("models " + uniqueModels) - res.send(uniqueModels); }) app.get('/api/get-engines', async (req, res) => { @@ -442,18 +653,35 @@ app.get('/api/get-engines', async (req, res) => { if(!year || !make || !model) { return res.status(400).json({message: "Missing required fields"}); } + else{ + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - const database = client.db("vehicleDB"); - const configurations = database.collection("configurations"); - const engines = await configurations.aggregate([ - { $match: { year: parseInt(year), make: make, model: model }}, - { $group: { _id: "$engine", engines: { $addToSet: "$engine" } }}, - { $sort: { _id: 1 }} - ]).toArray(); - - const uniqueEngines = engines.map(engine => engine._id); - console.log("engines " + uniqueEngines) - res.send(uniqueEngines); + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const database = client.db("vehicleDB"); + const configurations = database.collection("configurations"); + const engines = await configurations.aggregate([ + { $match: { year: parseInt(year), make: make, model: model }}, + { $group: { _id: "$engine", engines: { $addToSet: "$engine" } }}, + { $sort: { _id: 1 }} + ]).toArray(); + + const uniqueEngines = engines.map(engine => engine._id); + res.send(uniqueEngines); + })} + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } + } }) app.get('/api/get-transmissions', async (req, res) => { @@ -464,159 +692,203 @@ app.get('/api/get-transmissions', async (req, res) => { if(!year || !make || !model || !engine) { return res.status(400).json({message: "Missing required fields"}); - } - - const database = client.db("vehicleDB"); - const configurations = database.collection("configurations"); - const transmissions = await configurations.aggregate([ - { $match: { year: parseInt(year), make: make, model: model, engine: engine }}, - { $group: { _id: "$transmission", transmissions: { $addToSet: "$transmission" } }}, - { $sort: { _id: 1 }} - ]).toArray(); + } else{ + const { authorization } = req.headers; + console.log("USER AUTHORIZ: "+authorization) + if(!authorization) { + res.status(400).json({message: "Authorization Needed!"}); + } + try{ - const uniqueTransmissions = transmissions.map(transmission => transmission._id); - console.log("transmissions " + uniqueTransmissions) - res.send(uniqueTransmissions); + const token = authorization.split(" ")[1]; + console.log(token+ ": TOKEN"); + jwt.verify(token, JWTSecret, async (err, decoded) => { + if(err) { + res.status(401).json({message: "Invalid Token"}); + } + const database = client.db("vehicleDB"); + const configurations = database.collection("configurations"); + const transmissions = await configurations.aggregate([ + { $match: { year: parseInt(year), make: make, model: model, engine: engine }}, + { $group: { _id: "$transmission", transmissions: { $addToSet: "$transmission" } }}, + { $sort: { _id: 1 }} + ]).toArray(); + + const uniqueTransmissions = transmissions.map(transmission => transmission._id); + res.send(uniqueTransmissions); + })} + catch(err) { + res.status(500).json({message: "Error Validating User"}); + } + } }); app.post('/api/add-vehicle', async (req, res) => { const userEmail = process.env.EMAIL; - console.log("ADD: Hit add vehicle route"); - const email = req.body.email; - console.log("ADD: Users email: "+email); - const config_id = req.body.config_id; - console.log("ADD: Config_id: "+config_id); - const database = client.db("vehicleDB"); - const garage = database.collection("user_garage"); - const userVehicle = database.collection("user_vehicle_info"); + const { authorization } = req.headers; + console.log(authorization); - try{ - const exist = await garage.findOne({email: userEmail}); - if(exist) { - await garage.updateOne( - { email: userEmail }, - { $addToSet: { vehicle_config_ids: config_id } } - ); - await userVehicle.insertOne( - { email: userEmail, config_id: config_id, odometer: 0, upcoming_maintenance: [], completed_maintenance: [] }) - return res.status(200).json({message: "Vehicle added to garage"}); + if( !authorization ) { + res.status(400).json({message: "Authorization needed"}) + } + try { + const token = authorization.split(' ')[1]; + console.log(token); + //ok so have a token and we want to verify it + jwt.verify( token, JWTSecret, async(err, decoded) => { + if(err) { + return res.status(400).json({message: 'Unable to verify token'}); + } + + const database = client.db("vehicleDB"); + const garage = database.collection("user_garage"); + const userVehicle = database.collection("user_vehicle_info"); + + try{ + const exist = await garage.findOne({email: userEmail}); + if(exist) { + await garage.updateOne( + { email: userEmail }, + { $addToSet: { vehicle_config_ids: config_id } } + ); + await userVehicle.insertOne( + { email: userEmail, config_id: config_id, odometer: 0, upcoming_maintenance: [], completed_maintenance: [] }) + return res.status(200).json({message: "Vehicle added to garage"}); + } + else { + await garage.insertOne( + { email: userEmail, vehicle_config_ids: [config_id] } + ) + await userVehicle.insertOne( + { email: userEmail, config_id: config_id, odometer: 0, upcoming_maintenance: [], completed_maintenance: [] }) + return res.status(200).json({message: "User Vehicle added to info"}); + } + } + catch(err) { + return res.status(500).json(err); + } + }); } - else { - await garage.insertOne( - { email: userEmail, vehicle_config_ids: [config_id] } - ) - await userVehicle.insertOne( - { email: userEmail, config_id: config_id, odometer: 0, upcoming_maintenance: [], completed_maintenance: [] }) - return res.status(200).json({message: "User Vehicle added to info"}); + catch(err) { + return res.status(500).json({message: "Error Validating User"}); } - } - catch(err) { - return res.status(500).json(err); - } }); app.post('/api/update-odometer', async (req, res) => { - console.log("HIT UPDATE ODOMETER") const userEmail = process.env.EMAIL; const odometer = req.body.odometer; const config_id = req.body.config_id; const picture_url = req.body.picture_url; - console.log("UPDATE BODY: "+JSON.stringify(req.body)); - console.log("UPDATE ODOMETER: "+odometer); - console.log("UPDATE config_id: "+config_id); - console.log("UPDATE EMAIL: "+userEmail) - console.log("UPDATE PICTURE URL: "+picture_url) + const { authorization } = req.headers; + console.log(authorization); - const database = client.db("vehicleDB"); - const userVehicle = database.collection("user_vehicle_info"); + if( !authorization ) { + res.status(400).json({message: "Authorization needed"}) + } + try { + const token = authorization.split(' ')[1]; + console.log(token); + //ok so have a token and we want to verify it + jwt.verify( token, JWTSecret, async(err, decoded) => { + if(err) { + return res.status(400).json({message: 'Unable to verify token'}); + } + const database = client.db("vehicleDB"); + const userVehicle = database.collection("user_vehicle_info"); - try{ - const updateFields = { email: userEmail, config_id: config_id}; - const updateData = {}; - console.log("IN TRY BLOCK") - - if(odometer !== undefined) { - console.log("ODOMETER DEFINED") - updateData.odometer = parseInt(odometer); - console.log("ODOMETER UPDATED") + try{ + const updateFields = { email: userEmail, config_id: config_id}; + const updateData = {}; + + if(odometer !== undefined) { + updateData.odometer = parseInt(odometer); + } + if(picture_url !== undefined) { + updateData.picture_url = picture_url; + } + + await userVehicle.updateOne( + updateFields, + { $set: updateData } + ); + return res.status(200).json({message: "Odometer updated"}); + } + catch(err) { + return res.status(500).json(err); + } + }); } - if(picture_url !== undefined) { - console.log("PICTURE DEFINED") - updateData.picture_url = picture_url; - console.log("PICTURE UPDATED") + catch(err) { + return res.status(500).json({message: "Error Validating User"}); } - - await userVehicle.updateOne( - updateFields, - { $set: updateData } - ); - console.log("ODOMETER/PICTURE UPDATED") - return res.status(200).json({message: "Odometer updated"}); - } - catch(err) { - return res.status(500).json(err); - } }); app.get('/api/get-user-vehicle-odometers', async (req, res) => { - console.log("HIT GET USER VEHICLE ODOMETERS") - const database = client.db("vehicleDB"); - const garage = database.collection("user_garage"); - const userVehicle = database.collection("user_vehicle_info"); - const userGarage = await garage.findOne({email: EMAIL}); - if(!userGarage){ - return res.status(404).json({message: "User not found"}); - } - - const vehicleConfigIds = userGarage.vehicle_config_ids; - if(!vehicleConfigIds){ - return res.status(404).json({message: "User has no vehicles"}); - } - - const odometerReadings = await userVehicle.find( - {email: EMAIL, config_id: {$in: vehicleConfigIds} }, - {_id: 0, undefined: 1, odometer: 1} - ).toArray(); - - const pictureReadings = await userVehicle.find( - {email: EMAIL, config_id: {$in: vehicleConfigIds} }, - {_id: 0, undefined: 1, picture_url: 1} - ).toArray(); - - const odometerMap = {}; - odometerReadings.forEach(reading => { - odometerMap[reading.config_id] = reading.odometer; - }); - - const pictureMap = {}; - pictureReadings.forEach(reading => { - pictureMap[reading.config_id] = reading.picture_url; - }); + const { authorization } = req.headers; + console.log(authorization); - const response = vehicleConfigIds.map(configId => ({ - config_id: configId, - odometer: odometerMap[configId], - picture_url: pictureMap[configId] - })); + if( !authorization ) { + res.status(400).json({message: "Authorization needed"}) + } + try { + const token = authorization.split(' ')[1]; + console.log(token); + //ok so have a token and we want to verify it + jwt.verify( token, JWTSecret, async(err, decoded) => { + if(err) { + return res.status(400).json({message: 'Unable to verify token'}); + } + const database = client.db("vehicleDB"); + const garage = database.collection("user_garage"); + const userVehicle = database.collection("user_vehicle_info"); + const userGarage = await garage.findOne({email: EMAIL}); + if(!userGarage){ + return res.status(404).json({message: "User not found"}); + } + const vehicleConfigIds = userGarage.vehicle_config_ids; + if(!vehicleConfigIds){ + return res.status(404).json({message: "User has no vehicles"}); + } - res.status(200).json(response); -}); + const odometerReadings = await userVehicle.find( + {email: EMAIL, config_id: {$in: vehicleConfigIds} }, + {_id: 0, undefined: 1, odometer: 1} + ).toArray(); + const pictureReadings = await userVehicle.find( + {email: EMAIL, config_id: {$in: vehicleConfigIds} }, + {_id: 0, undefined: 1, picture_url: 1} + ).toArray(); -//TODO: Request to get a list of all engines given a year, make, and model (Non-repeating). + const odometerMap = {}; + odometerReadings.forEach(reading => { + odometerMap[reading.config_id] = reading.odometer; + }); -//TODO: Request to get a list of all transmissions given a year, make, model, and engine (Non-repeating). + const pictureMap = {}; + pictureReadings.forEach(reading => { + pictureMap[reading.config_id] = reading.picture_url; + }); -//TODO: Request to get a list of all maintenance intervals given a vehicle's config_id. + const response = vehicleConfigIds.map(configId => ({ + config_id: configId, + odometer: odometerMap[configId], + picture_url: pictureMap[configId] + })); -//TODO: Request to get a list of all maintenance tasks given a vehicle's config_id and mileage. -//TODO: Request to get maintenance data given a vehicle's config_id and mileage. + res.status(200).json(response); + }); + } + catch(err) { + return res.status(500).json({message: "Error Validating User"}); + } +}); app.listen(port, () => { diff --git a/frontend/src/pages/Login.js b/frontend/src/pages/Login.js index e155f77..c5a0947 100644 --- a/frontend/src/pages/Login.js +++ b/frontend/src/pages/Login.js @@ -6,12 +6,12 @@ import '../App.css'; export const Login = () => { const [googleOauthURL, setGoogleOauthURL] = useState(''); - const [searchParams] = useSearchParams(); + const [searchParams, setSearchParams] = useSearchParams(); const [error, setError] = useState(''); let navigate = useNavigate(); - useEffect(() => { + useEffect( () => { fetchGoogleOauthURL(); }, []); @@ -26,16 +26,16 @@ export const Login = () => { }); }; - useEffect(() => { + useEffect( () => { const token = searchParams.get('token'); - if (token) { + if(token) { localStorage.setItem('token', token); navigate('/garage'); } - }, [searchParams, navigate]); + }, [searchParams, navigate]) const handleLogin = () => { - if (googleOauthURL) { + if(googleOauthURL) { window.location.href = googleOauthURL; } else { setError('Google OAuth URL not found'); @@ -55,4 +55,4 @@ export const Login = () => { ); }; -export default Login; \ No newline at end of file + export default Login; \ No newline at end of file diff --git a/frontend/src/pages/NavBar.js b/frontend/src/pages/NavBar.js index b4fc6bf..ccf40ec 100644 --- a/frontend/src/pages/NavBar.js +++ b/frontend/src/pages/NavBar.js @@ -1,8 +1,8 @@ -import {Nav, Navbar} from "react-bootstrap"; +import { Nav, Navbar } from "react-bootstrap"; import Container from "react-bootstrap/Container"; -import React from "react"; -import {useState, useEffect} from 'react'; +import React, { useState, useEffect } from 'react'; import Settings from "./Settings"; +import '../App.css'; import Button from "react-bootstrap/Button"; import { GearFill } from 'react-bootstrap-icons'; import '../App.css'; @@ -12,38 +12,40 @@ function NavBar() { useEffect(() => { const fetchUser = async () => { - try { + try{ const token = localStorage.getItem('token'); - if (token) { + if(token) { const response = await fetch('/api/user', { headers: { 'Authorization': `Bearer ${token}` } }); - if (response.ok) { + if(response.ok){ const data = await response.json(); - console.log("USERNAME DATA: ", data.name); + console.log("USERNAME DATA: " + data.name); setUser(data.name); - } else { + + } + else { console.error("User not found"); } } - } catch (error) { + } + catch (error) { console.log(error); } }; fetchUser(); }, []); - return ( - - Driveline + + Driveline - + -