diff --git a/server/api/app.js b/server/api/app.js index 3dc5b5c..c58ab33 100644 --- a/server/api/app.js +++ b/server/api/app.js @@ -6,16 +6,22 @@ import bodyParser from "body-parser" const app = express() +app.get('/', async (req,res) => { + res.status(200).send("express and mongodb, eventica server") +}) + app.use(cors()) app.use(express.json({ limit: '16kb' })); app.use(express.urlencoded({ extended: true, limit: '16kb' })); -app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({ extended: true })); +// app.use(bodyParser.json()); +// app.use(bodyParser.urlencoded({ extended: true })); //import roouter import { authRouter } from "../routes/auth.routes.js" +import { profileRouter } from "../routes/profile.routes.js" //use router app.use("/api/v1/auth", authRouter) +app.use('/api/v1/profile', profileRouter) export {app} \ No newline at end of file diff --git a/server/controllers/profile.controller.js b/server/controllers/profile.controller.js new file mode 100644 index 0000000..7e3d4d6 --- /dev/null +++ b/server/controllers/profile.controller.js @@ -0,0 +1,158 @@ +import { User } from "../model/user.model.js"; +import jwt from "jsonwebtoken" +import dotenv from "dotenv" + +dotenv.config() + + +const secretKey = process.env.SECRET_KEY + +if (!secretKey) { + console.log("No secretKey defined check env path") + process.exit() +} + + +// Get user profile function +const getProfile = async (req, res) => { + try { + console.log("getProfile called"); + + // Step 1: Get the token from the authorization header + const authHeader = req.headers.authorization; + if (!authHeader) { + // If the header is missing, return an error + console.error("Authorization header is missing."); + return res.status(401).send({ error: "No token provided." }); + } + + // Step 2: Extract the token from the Authorization header + const token = authHeader.split(' ')[1]; + if (!token) { + // If the token is missing, return an error + console.error("Bearer token is missing."); + return res.status(401).send({ error: "Invalid token format." }); + } + + // Step 3: Verify the token + const decoded = jwt.verify(token, secretKey); + + // Step 4: Retrieve user information based on the decoded token's ID + const user = await User.findById(decoded.id); + if (!user) { + // If no user is found, return an error + console.error(`User not found for token with userId: ${decoded.userId}.`); + return res.status(404).send({ error: "User not found." }); + } + + // Step 5: Send back detailed user profile data + return res.status(200).send({message:"fetched successfully", fetchedUser: user}) + + console.log(`Profile fetched successfully for user ${user.username}.`); + } catch (error) { + console.error("Error during profile retrieval:", error); + if (error.name === "JsonWebTokenError") { + // Handle invalid JWT errors + return res.status(401).send({ error: "Invalid token." }); + } + // Handle unexpected errors + res.status(500).send({ error: "An error occurred while fetching the profile." }); + } +}; + + +//eedit profile +const editProfile = async (req,res) => { + try { + console.log("editProfile called"); + + // Step 1: Get the token from the authorization header + const authHeader = req.headers.authorization; + if (!authHeader) { + // If the header is missing, return an error + console.error("Authorization header is missing."); + return res.status(401).json({ error: "No token provided." }); + } + + // Step 2: Extract the token from the Authorization header + const token = authHeader.split(' ')[1]; + if (!token) { + // If the token is missing, return an error + console.error("Bearer token is missing."); + return res.status(401).json({ error: "Invalid token format." }); + } + + // Step 3: Verify the token + const decoded = jwt.verify(token, secretKey); + + // Step 4: Find the user by ID from the decoded token + const user = await User.findById(decoded.id); + if (!user) { + // If no user is found, return an error + console.error(`User not found for token with userId: ${decoded.id}.`); + return res.status(404).json({ error: "User not found." }); + } + + // Step 5: Update the user's profile fields if provided in the request body + const { username, password, email, dob, location } = req.body; + if (username) user.username = username; + if (password) user.password = password; // Ensure to hash the password if implementing + if (email) user.email = email; + if (dob) user.dob = dob; + if (location) user.location = location; + + // Step 6: Save the updated user information + await user.save(); + + console.log(`Profile updated successfully for user ${user.username}.`); + res.json({ message: "Profile updated successfully.", user }); + } catch (error) { + console.error("Error during profile update:", error); + if (error.name === "JsonWebTokenError") { + // Handle invalid JWT errors + return res.status(401).json({ error: "Invalid token." }); + } + // Handle unexpected errors + res.status(500).json({ error: "An error occurred while updating the profile." }); + } +} + + +// Delete user profile function +const deleteProfile = async (req, res) => { + try { + // Step 1: Get the token from the authorization header + const authHeader = req.headers.authorization; + if (!authHeader) { + // If the header is missing, return an error + return res.status(401).json({ error: "No token provided." }); + } + + // Step 2: Extract the token from the Authorization header + const token = authHeader.split(' ')[1]; + // Step 3: Verify the token + const decoded = jwt.verify(token, secretKey); + + // Step 4: Find the user by ID from the decoded token + const user = await User.findById(decoded.id); + if (!user) { + // If no user is found, return an error + return res.status(404).json({ error: "User not found." }); + } + + // Step 5: Delete the user profile + await user.deleteOne(); + res.json({ message: "Profile deleted successfully." }); + } catch (error) { + // Handle unexpected errors + res.status(500).json({ error: "An error occurred while deleting the profile." }); + } +}; + + + +export { + getProfile, + editProfile, + deleteProfile +} \ No newline at end of file diff --git a/server/model/user.model.js b/server/model/user.model.js index bf22b6e..a94d523 100644 --- a/server/model/user.model.js +++ b/server/model/user.model.js @@ -17,10 +17,19 @@ const userSchema = new mongoose.Schema({ type: String, required: true, }, - isOrganiser: { - type: Boolean, - default: false, - required: true + role: { + type: String, + enum: ['user', 'organiser', 'admin'], + default: 'user' + }, + location:{ + type: String + }, + dob:{ + type: Date + }, + picture:{ + type: String } }, { timestamps: true }) diff --git a/server/routes/profile.routes.js b/server/routes/profile.routes.js new file mode 100644 index 0000000..f2ca8b4 --- /dev/null +++ b/server/routes/profile.routes.js @@ -0,0 +1,13 @@ +import express from 'express' +import { deleteProfile, editProfile, getProfile } from '../controllers/profile.controller.js' + + +const profileRouter = express.Router() + + +profileRouter.get('/getprofile',getProfile) +profileRouter.post('/editprofile', editProfile) +profileRouter.delete('/deleteProfile', deleteProfile) + + +export {profileRouter} \ No newline at end of file