Skip to content

Commit

Permalink
More merge changes from dev to HW-176-val
Browse files Browse the repository at this point in the history
  • Loading branch information
kenlight-bu committed Oct 5, 2024
1 parent 19286b2 commit 49431fd
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 415 deletions.
4 changes: 2 additions & 2 deletions code/client/src/components/ManageProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function ManageProfile() {

useEffect(() => {
apiClient
.get("/manage-profile") // Fetch user profile data from the backend (e.g., /manage-profile)
.get("/api/users/manage-profile") // Fetch user profile data from the backend (e.g., /manage-profile)
.then((res) => {
setProfileData(res.data);
})
Expand Down Expand Up @@ -64,7 +64,7 @@ function ManageProfile() {
setErrorMessage('');

try {
await apiClient.post("/manage-profile", profileData);
await apiClient.post("/api/users/manage-profile", profileData);
console.log("Updating profile")
setSuccessMessage('Profile updated!');
} catch (err) {
Expand Down
6 changes: 1 addition & 5 deletions code/client/src/services/apiClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@ import axios from 'axios';

// console.log("API Base URL:", process.env.REACT_APP_BASE_URL);

const apiClient = axios.create({
baseURL: 'http://localhost:5000', // Default to localhost for development
});

// const apiClient = axios.create({
// baseURL: 'https://peak-performance-backend-394f316db343.herokuapp.com/', // Default to localhost for development
// baseURL: process.env.REACT_APP_BASE_URL || 'http://localhost:5000', // Default to localhost for development
// });

// const apiClient = axios.create({
Expand Down
24 changes: 0 additions & 24 deletions code/server/app.js

This file was deleted.

146 changes: 88 additions & 58 deletions code/server/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,93 +14,123 @@ exports.viewUsers = async (req, res) => {

// Manage Profile (GET)
exports.manageProfile = async (req, res) => {
try {
const userId = req.body.userId || 10001; // This should dynamically come from the request, e.g., req.userId
const userProfile = await User.findOne({ userId });

if (!userProfile) {
return res.status(404).json({ error: "User not found" });
try {
// TO DO: UPDATE THIS TO GRAB USER ID FROM LOCAL STORAGE, rather than hardcode
const userId = 10001 // req.userId;
const userProfile = await User.findOne({ userId });
if (!userProfile) {
return res.status(404).json({ error: "User not found" });
}
res.json(userProfile);
} catch (error) {
res.status(500).json({ error: "Server error" });
}
res.json(userProfile);
} catch (error) {
res.status(500).json({ error: "Server error" });
}
};

// Manage Profile (POST)
exports.updateProfile = async (req, res) => {
try {
try {
const { userId, name, gender, dob, height } = req.body;

// Find user in the database using userId
const userProfile = await User.findOne({ userId });

// Check if user exists
if (!userProfile) {
return res.status(404).json({ error: "User not found" });
}

// Update the profile with the new values
userProfile.name = name;
userProfile.gender = gender;
userProfile.dob = dob;
userProfile.height = height;

// Save the updated user profile
await userProfile.save();

// Send a success response
res.status(200).json({ message: "Profile updated successfully", userProfile });
} catch (error) {
console.error(error); // Log the error for debugging
res.status(500).json({ message: "Error updating profile" });
}
};

// Create User
exports.createUser = async (req, res) => {
try {
const { name, email, password } = req.body;

const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: 'An account with this email already exists' });
}

const hashedPassword = await bcrypt.hash(password, 10);
let lastUser = await User.find().sort({ userId: -1 }).limit(1);
let newUserId = lastUser.length > 0 ? lastUser[0].userId + 1 : 1;

const newUser = new User({
userId: newUserId,
name,
email,
passwordHashed: hashedPassword,
});

await newUser.save();
res.status(201).json({ message: 'User created successfully!' });
} catch (error) {
res.status(500).json({ message: 'Error creating user' });
}
try {
const { name, email, password } = req.body;

const existingUser = await User.findOne({ email: email });
if (existingUser) {
return res.status(400).json({ message: 'Error: An account with this email already exists' });
}

const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);

// Autogenerate user ID based on maximum ID in users table
let lastUser = await User.find().sort({"userId": -1}).limit(1)
let newUserId = lastUser[0].userId + 1

const newUser = new User({
userId: newUserId,
name: name,
email: email,
passwordHashed: hashedPassword
})
await newUser.save();
res.status(201).json({ message: 'User created successfully!' });

} catch (error) {
res.status(500).json({ message: 'Error creating user' });
}
};

// User login
exports.loginUser = async (req, res) => {
try {
const { email, password } = req.body;

const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ message: 'Invalid email or password.' });
}

const isPasswordValid = await bcrypt.compare(password, user.passwordHashed);
if (!isPasswordValid) {
return res.status(401).json({ message: 'Invalid email or password.' });
}

const secretKey = process.env.SECRET_KEY;
if (!secretKey) {
return res.status(500).json({ message: 'Internal server error' });
}

const token = jwt.sign({ userId: user.userId, email: user.email }, secretKey, { expiresIn: '1h' });
res.json({ token, message: 'Login successful' });
} catch (error) {
res.status(500).json({ message: 'Internal server error' });
}
try {
const { email, password } = req.body;

// Find the user by email
const user = await User.findOne({ email: email });

if (!user) {
// User not found
return res.status(401).json({ message: 'Invalid email or password.' });
}

// Compare the provided password with the stored hashed password
const isPasswordValid = await bcrypt.compare(password, user.passwordHashed);
// console.log('Password validation result:', isPasswordValid);

if (!isPasswordValid) {
// Password does not match
return res.status(401).json({ message: 'Invalid email or password.' });
}

// Generate a token (e.g., JWT)
const secretKey = process.env.SECRET_KEY; // Use environment variable in production
// console.log('JWT_SECRET:', secretKey);
// const secretKey = "myproductionsecret"

if (!secretKey) {
// console.error('JWT_SECRET is not defined');
return res.status(500).json({ message: 'no secret key' });
}

const token = jwt.sign(
{ userId: user.userId, email: user.email },
secretKey,
{ expiresIn: '1h' }
);
// console.log('JWT Secret:', process.env.SECRET_KEY);

// Send the token to the client
res.json({ token: token, message: 'Login successful' });

} catch (error) {
res.status(500).json({ message: 'Internal Server Error' });
}
};
93 changes: 0 additions & 93 deletions code/server/db.js

This file was deleted.

17 changes: 17 additions & 0 deletions code/server/models/DailyEntry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const dailyEntrySchema = new Schema({
dailyEntryId: { type: Number, required: true },
userId: { type: Number, required: true },
entryDate: { type: Date, default: Date.now },
weight: { type: Number },
steps: { type: Number },
sleep: { type: Number },
water: { type: Number },
exercise: { type: Number },
}, {
collection: 'daily_entries',
});

module.exports = mongoose.model('DailyEntry', dailyEntrySchema);
Loading

0 comments on commit 49431fd

Please sign in to comment.