Skip to content

Commit

Permalink
change authenticated() to return token so users can request their data
Browse files Browse the repository at this point in the history
  • Loading branch information
ccerav-bu committed Oct 6, 2024
1 parent ada6b1a commit 47f29af
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
13 changes: 12 additions & 1 deletion code/client/src/components/ManageProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { useEffect, useState } from "react";
import apiClient from "../services/apiClient.js";
import { Box, Typography, TextField, MenuItem, Button } from "@mui/material";
import { box, bigTitle, inputBackground, menuPropsStyles, submitButton } from "./style/styles.js";
import { authenticated } from "../utils/authenticate.js";

function ManageProfile() {



const [profileData, setProfileData] = useState({
userId: "",
email: "",
Expand All @@ -19,8 +22,16 @@ function ManageProfile() {
const [errorMessage, setErrorMessage] = useState('');

useEffect(() => {
const token = authenticated()

if (token) {

}

apiClient
.get("/api/users/manage-profile") // Fetch user profile data from the backend (e.g., /manage-profile)
.get("/api/users/manage-profile", {
headers: { Authorization: `Bearer ${token}` }
}) // Fetch user profile data from the backend (e.g., /manage-profile)
.then((res) => {
setProfileData(res.data);
})
Expand Down
1 change: 1 addition & 0 deletions code/client/src/utils/authenticate.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export function authenticated() {
window.location.href = '/login';
}
}
return token
}

function validateToken(token) {
Expand Down
21 changes: 18 additions & 3 deletions code/server/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,25 @@ exports.viewUsers = async (req, res) => {
// Manage Profile (GET)
exports.manageProfile = async (req, res) => {
try {
const userId = 1; // Hardcoded, should be dynamic (e.g., from token)
const userProfile = await User.findOne({ userId });
// Get token from Authorization header
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).json({ message: 'Authorization header is missing' });
}

const token = authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Token is missing' });
}

// Verify and decode the token
const secretKey = process.env.SECRET_KEY;
const decoded = jwt.verify(token, secretKey);

console.log(userProfile)
// Extract userId from the decoded token
const userId = decoded.userId;

const userProfile = await User.findOne({ userId });

if (!userProfile) {
return res.status(404).json({ message: 'User not found' });
Expand Down

0 comments on commit 47f29af

Please sign in to comment.