Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified WeatherWatch/backend/routes/users.db
Binary file not shown.
48 changes: 47 additions & 1 deletion WeatherWatch/backend/routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt'); // for password hashing
const sqlite3 = require('sqlite3').verbose(); // SQLite3 database
const path = require('path');

// database setup
// initialize SQLite database, the file users.db will store user data
Expand All @@ -20,6 +21,16 @@ db.run(`CREATE TABLE IF NOT EXISTS users (
password TEXT NOT NULL
)`);

// create trip history table if it doesn't exist
db.run(`CREATE TABLE IF NOT EXISTS trip_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
location TEXT NOT NULL,
date TEXT,
info TEXT,
FOREIGN KEY(user_id) REFERENCES users(id)
)`);

// register, handles new user registration
router.post('/register', async (req, res) => {
console.log("Register request body:", req.body);
Expand Down Expand Up @@ -76,7 +87,42 @@ router.post('/login', (req, res) => {
const match = await bcrypt.compare(password, user.password);
if (!match) return res.status(401).json({ message: "Invalid email or password" });
// success, return user info (excluding password)
res.json({ id: user.id, name: user.name, email: user.email });
res.json({
user: {
id: user.id,
name: user.name,
email: user.email
}
});
});
});

// retrieve trip history
router.get('/:id/history', (req, res) => {
const userID = req.params.id;

db.all('SELECT location, date, info FROM trip_history WHERE user_id = ? ORDER BY id DESC', [userID],
(err, rows) => {
if (err) {
return res.status(500).json({ message: "DB error", error: err.message });}
res.json({ history: rows });
});
});

// save trip history
router.post('/:id/history', (req, res) => {
const userID = req.params.id;
const { location, date, info } = req.body;
if (!location) {
return res.status(400).json({ message: "Location is required" });
}
db.run('INSERT INTO trip_history (user_id, location, date, info) VALUES (?, ?, ?, ?)',
[userID, location, date || "", info || ""],
function(err) {
if (err) {
return res.status(500).json({ message: "DB error", error: err.message });
}
res.json({ message: "Trip saved successfully", tripId: this.lastID });
});
});

Expand Down
4 changes: 2 additions & 2 deletions WeatherWatch/backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ const usersRouter = require('./routes/users'); // import user routes

const app = express();

// CORS configuration to allow any requests from frontend
// CORS configuration to allow requests from local dev ports
app.use(cors({
origin: 'http://localhost:5173',
origin: ['http://localhost:5173', 'http://localhost:5174'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
Expand Down
27 changes: 9 additions & 18 deletions WeatherWatch/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions WeatherWatch/src/TripPlanner.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import Calendar from './Calendar';
import './Calendar.css';
import './TripPlanner.css';
import { getDailyAggregation, geocodeLocation } from './api/openweather';
import axios from 'axios';
import { useAuth } from './context/AuthContext';

// convert kelvin to fahrenheit
const kelvinToFahrenheit = (k) => +(((k - 273.15) * 9) / 5 + 32).toFixed(0);
Expand Down Expand Up @@ -43,6 +45,7 @@ const formatWeather = (data, dateObj) => {
};

function TripPlanner() {
const { user } = useAuth();
const [tripStart, setTripStart] = useState(null);
const [tripEnd, setTripEnd] = useState(null);
const [tripDates, setTripDates] = useState([]);
Expand Down Expand Up @@ -174,6 +177,22 @@ function TripPlanner() {
await fetchWeatherForTrip(selectedPlace, start, end);
};

const handleSaveTrip = async () => {
if (!user || !selectedPlace || !tripStart) {
return;
}
try {
const response = await axios.post(`http://localhost:5001/users/${user.id}/history`, {
location: selectedPlace.name,
date: tripStart.toLocaleDateString(),
info: JSON.stringify(weatherData)
});
alert('Trip saved successfully!');
} catch (err) {
alert('Failed to save trip.');
}
};

// render
return (
<section className="page">
Expand Down Expand Up @@ -223,6 +242,13 @@ return (
</p>
)}

{/* Save Trip Button */}
{user && selectedPlace && tripStart && (
<button className="trip-action" onClick={handleSaveTrip} style={{ marginBottom: 16 }}>
Save Trip
</button>
)}

{/* Loading and error */}
{loading && <p>Loading weather info...</p>}
{error && <p style={{ color: 'red' }}>{error}</p>}
Expand Down
13 changes: 12 additions & 1 deletion WeatherWatch/src/Users.css
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,15 @@
.red-alert {
color: red;
font-weight: bold;
}
}
.users-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}

.users-logout {
white-space: nowrap;
}
Loading
Loading