Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added profile related controllers #97

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 8 additions & 2 deletions server/api/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}
158 changes: 158 additions & 0 deletions server/controllers/profile.controller.js
Original file line number Diff line number Diff line change
@@ -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
}
17 changes: 13 additions & 4 deletions server/model/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
Expand Down
13 changes: 13 additions & 0 deletions server/routes/profile.routes.js
Original file line number Diff line number Diff line change
@@ -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}