Commit e3dcca4e authored by janithgamage1.ed's avatar janithgamage1.ed

fix: update

Desc : update project
parent 556bf2eb
......@@ -157,3 +157,23 @@ export const deleteUser = async (req, res) => {
}
}
export const currentUser = async (req, res) => {
try {
// req.userId contains the user ID extracted from the token by the auth middleware
const userId = req.userId;
// Fetch the user account information from the database
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
// Send the user account information as a response
res.status(200).json({ user });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Server error' });
}
}
import Curriculum from "../models/curriculum.model.js";
import UserProgress from "../models/userProgress.model.js";
// Logic to subscribe to a curriculum for a user
export const subscribeCurriculum = async (req, res) => {
const { userId, curriculum } = req.body;
try {
let userProgress = await UserProgress.findOne({ userId });
// Check if the user is already subscribed to the curriculum
const userProgress = await UserProgress.findOne({ userId });
if (!userProgress) {
// If there is no user progress record for this user, create a new one
userProgress = new UserProgress({
const newUserProgress = new UserProgress({
userId,
curriculums: [curriculum], // Add the curriculum to the curriculums array
curriculums: [curriculum],
});
await newUserProgress.save();
} else {
// If there is an existing user progress record, check if the curriculum already exists
const existingCurriculumIndex = userProgress.curriculums.findIndex(c => c.curriculumCode === curriculum.curriculumCode);
if (existingCurriculumIndex !== -1) {
// If the curriculum exists, update it
userProgress.curriculums[existingCurriculumIndex] = curriculum;
return res.status(400).json({ error: 'User already subscribed to this curriculum' });
} else {
// If the curriculum doesn't exist, add it to the array
userProgress.curriculums.push(curriculum);
......@@ -31,8 +33,17 @@ export const subscribeCurriculum = async (req, res) => {
const curriculumMark = typeof curriculum.curriculumMark === 'string' ? parseFloat(curriculum.curriculumMark) : curriculum.curriculumMark;
return total + (isNaN(curriculumMark) ? 0 : curriculumMark);
}, 0);
userProgress.totalCurriculumsMarks = totalCurriculumsMarks;
const curriculumCode = curriculum.curriculumCode
// Now, update the curriculum collection with the subscribed user
await Curriculum.updateOne(
{ curriculumCode },
{ $addToSet: { subscribedUser: userId } }
);
// Save the user progress record
await userProgress.save();
......
......@@ -35,7 +35,11 @@ const curriculumSchema = new mongoose.Schema({
type: Number,
default: 1, // Default status as active (1)
},
...commonFields
...commonFields,
subscribedUser: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User", // Reference to the User model if you have one
}],
});
const Curriculum = mongoose.model("Curriculum", curriculumSchema);
......
import express from "express";
import { deleteUser, getUser, getUserAccordingToType, getUsers, signIn, signUp, updateUser } from "../controllers/user.controller.js";
import { currentUser, deleteUser, getUser, getUserAccordingToType, getUsers, signIn, signUp, updateUser } from "../controllers/user.controller.js";
import auth from "../middleware/auth.middleware.js";
const router = express.Router();
router.post('/sign-in', signIn)
router.post('/sign-up', signUp)
router.get('/all', getUsers);
router.get('/current-user', auth, currentUser);
router.get('/:id', getUser);
router.get('/all/type/:userType', getUserAccordingToType);
router.put('/:id', updateUser);
......
......@@ -23,9 +23,13 @@ import userProgressRoutes from "./routes/userProgress.routes.js";
dotenv.config();
const app = express();
const corsOptions = {
origin: 'http://localhost:3000',
};
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
app.use(cors(corsOptions));
//end
app.get("/", (req, res) => {
......
......@@ -56,17 +56,29 @@ export const JWTProvider = ({ children }: { children: React.ReactElement }) => {
const init = async () => {
try {
const serviceToken = window.localStorage.getItem('serviceToken');
console.log(verifyToken(serviceToken!));
if (serviceToken && verifyToken(serviceToken)) {
setSession(serviceToken);
// const response = await axios.get('/api/account/me');
// const { user } = response.data;
// Set the token in your Axios instance for future requests
axiosServices.defaults.headers.common['Authorization'] = `Bearer ${serviceToken}`;
// Make the API request
const response = await axiosServices.get('/rest_node/user/current-user');
const { user } = response.data;
console.log(user);
dispatch({
type: LOGIN,
payload: {
isLoggedIn: true,
// user
user: {
id: user._id,
email: user.email,
name: `${user.firstName} ${user.lastName}`,
role: user.type
}
}
});
} else {
......
// material-ui
import useAuth from "hooks/useAuth";
import { useEffect } from "react";
// project import
// ==============================|| Dashboard ||============================== //
const Dashboard = () => (
<>
</>
);
const Dashboard = () => {
const { user } = useAuth()
// const serviceToken = window.localStorage.getItem('serviceToken');
// useEffect(() => {
// const fetchData = async () => {
// try {
// // Set the token in your Axios instance for future requests
// axiosServices.defaults.headers.common['Authorization'] = `Bearer ${serviceToken}`;
// // Make the API request
// const response = await axiosServices.get('/rest_node/user/current-user');
// const { user } = response.data;
// console.log(user);
// console.log(response);
// // Handle the user data or dispatch it to your state here
// } catch (error) {
// // Handle errors here (e.g., token expiration, network issues)
// console.error('Error fetching user data:', error);
// // You can dispatch a logout action or handle the error accordingly
// }
// };
// fetchData();
// }, [])
useEffect(() => {
console.log(user?.id);
}, [user])
return (
<>
</>
);
}
export default Dashboard;
......@@ -31,6 +31,8 @@ const slice = createSlice({
// HAS ERROR
hasError(state, action) {
console.log(action.payload);
state.error = action.payload;
},
......
......@@ -14,6 +14,7 @@ export interface curriculumType {
createdAt?: Date
updatedBy?: string
updatedAt?: Date
subscribedUser?: any[]
}
export type Curriculum = {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment