Skip to content

Commit ef95b03

Browse files
committed
added profile controller
1 parent 5877a60 commit ef95b03

File tree

4 files changed

+192
-6
lines changed

4 files changed

+192
-6
lines changed

server/api/app.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,22 @@ import bodyParser from "body-parser"
66
const app = express()
77

88

9+
app.get('/', async (req,res) => {
10+
res.status(200).send("express and mongodb, eventica server")
11+
})
12+
913
app.use(cors())
1014
app.use(express.json({ limit: '16kb' }));
1115
app.use(express.urlencoded({ extended: true, limit: '16kb' }));
12-
app.use(bodyParser.json());
13-
app.use(bodyParser.urlencoded({ extended: true }));
16+
// app.use(bodyParser.json());
17+
// app.use(bodyParser.urlencoded({ extended: true }));
1418

1519
//import roouter
1620
import { authRouter } from "../routes/auth.routes.js"
21+
import { profileRouter } from "../routes/profile.routes.js"
1722

1823

1924
//use router
2025
app.use("/api/v1/auth", authRouter)
26+
app.use('/api/v1/profile', profileRouter)
2127
export {app}
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import { User } from "../model/user.model.js";
2+
import jwt from "jsonwebtoken"
3+
import dotenv from "dotenv"
4+
5+
dotenv.config()
6+
7+
8+
const secretKey = process.env.SECRET_KEY
9+
10+
if (!secretKey) {
11+
console.log("No secretKey defined check env path")
12+
process.exit()
13+
}
14+
15+
16+
// Get user profile function
17+
const getProfile = async (req, res) => {
18+
try {
19+
console.log("getProfile called");
20+
21+
// Step 1: Get the token from the authorization header
22+
const authHeader = req.headers.authorization;
23+
if (!authHeader) {
24+
// If the header is missing, return an error
25+
console.error("Authorization header is missing.");
26+
return res.status(401).send({ error: "No token provided." });
27+
}
28+
29+
// Step 2: Extract the token from the Authorization header
30+
const token = authHeader.split(' ')[1];
31+
if (!token) {
32+
// If the token is missing, return an error
33+
console.error("Bearer token is missing.");
34+
return res.status(401).send({ error: "Invalid token format." });
35+
}
36+
37+
// Step 3: Verify the token
38+
const decoded = jwt.verify(token, secretKey);
39+
40+
// Step 4: Retrieve user information based on the decoded token's ID
41+
const user = await User.findById(decoded.id);
42+
if (!user) {
43+
// If no user is found, return an error
44+
console.error(`User not found for token with userId: ${decoded.userId}.`);
45+
return res.status(404).send({ error: "User not found." });
46+
}
47+
48+
// Step 5: Send back detailed user profile data
49+
return res.status(200).send({message:"fetched successfully", fetchedUser: user})
50+
51+
console.log(`Profile fetched successfully for user ${user.username}.`);
52+
} catch (error) {
53+
console.error("Error during profile retrieval:", error);
54+
if (error.name === "JsonWebTokenError") {
55+
// Handle invalid JWT errors
56+
return res.status(401).send({ error: "Invalid token." });
57+
}
58+
// Handle unexpected errors
59+
res.status(500).send({ error: "An error occurred while fetching the profile." });
60+
}
61+
};
62+
63+
64+
//eedit profile
65+
const editProfile = async (req,res) => {
66+
try {
67+
console.log("editProfile called");
68+
69+
// Step 1: Get the token from the authorization header
70+
const authHeader = req.headers.authorization;
71+
if (!authHeader) {
72+
// If the header is missing, return an error
73+
console.error("Authorization header is missing.");
74+
return res.status(401).json({ error: "No token provided." });
75+
}
76+
77+
// Step 2: Extract the token from the Authorization header
78+
const token = authHeader.split(' ')[1];
79+
if (!token) {
80+
// If the token is missing, return an error
81+
console.error("Bearer token is missing.");
82+
return res.status(401).json({ error: "Invalid token format." });
83+
}
84+
85+
// Step 3: Verify the token
86+
const decoded = jwt.verify(token, secretKey);
87+
88+
// Step 4: Find the user by ID from the decoded token
89+
const user = await User.findById(decoded.id);
90+
if (!user) {
91+
// If no user is found, return an error
92+
console.error(`User not found for token with userId: ${decoded.id}.`);
93+
return res.status(404).json({ error: "User not found." });
94+
}
95+
96+
// Step 5: Update the user's profile fields if provided in the request body
97+
const { username, password, email, dob, location } = req.body;
98+
if (username) user.username = username;
99+
if (password) user.password = password; // Ensure to hash the password if implementing
100+
if (email) user.email = email;
101+
if (dob) user.dob = dob;
102+
if (location) user.location = location;
103+
104+
// Step 6: Save the updated user information
105+
await user.save();
106+
107+
console.log(`Profile updated successfully for user ${user.username}.`);
108+
res.json({ message: "Profile updated successfully.", user });
109+
} catch (error) {
110+
console.error("Error during profile update:", error);
111+
if (error.name === "JsonWebTokenError") {
112+
// Handle invalid JWT errors
113+
return res.status(401).json({ error: "Invalid token." });
114+
}
115+
// Handle unexpected errors
116+
res.status(500).json({ error: "An error occurred while updating the profile." });
117+
}
118+
}
119+
120+
121+
// Delete user profile function
122+
const deleteProfile = async (req, res) => {
123+
try {
124+
// Step 1: Get the token from the authorization header
125+
const authHeader = req.headers.authorization;
126+
if (!authHeader) {
127+
// If the header is missing, return an error
128+
return res.status(401).json({ error: "No token provided." });
129+
}
130+
131+
// Step 2: Extract the token from the Authorization header
132+
const token = authHeader.split(' ')[1];
133+
// Step 3: Verify the token
134+
const decoded = jwt.verify(token, secretKey);
135+
136+
// Step 4: Find the user by ID from the decoded token
137+
const user = await User.findById(decoded.id);
138+
if (!user) {
139+
// If no user is found, return an error
140+
return res.status(404).json({ error: "User not found." });
141+
}
142+
143+
// Step 5: Delete the user profile
144+
await user.deleteOne();
145+
res.json({ message: "Profile deleted successfully." });
146+
} catch (error) {
147+
// Handle unexpected errors
148+
res.status(500).json({ error: "An error occurred while deleting the profile." });
149+
}
150+
};
151+
152+
153+
154+
export {
155+
getProfile,
156+
editProfile,
157+
deleteProfile
158+
}

server/model/user.model.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,19 @@ const userSchema = new mongoose.Schema({
1717
type: String,
1818
required: true,
1919
},
20-
isOrganiser: {
21-
type: Boolean,
22-
default: false,
23-
required: true
20+
role: {
21+
type: String,
22+
enum: ['user', 'organiser', 'admin'],
23+
default: 'user'
24+
},
25+
location:{
26+
type: String
27+
},
28+
dob:{
29+
type: Date
30+
},
31+
picture:{
32+
type: String
2433
}
2534

2635
}, { timestamps: true })

server/routes/profile.routes.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import express from 'express'
2+
import { deleteProfile, editProfile, getProfile } from '../controllers/profile.controller.js'
3+
4+
5+
const profileRouter = express.Router()
6+
7+
8+
profileRouter.get('/getprofile',getProfile)
9+
profileRouter.post('/editprofile', editProfile)
10+
profileRouter.delete('/deleteProfile', deleteProfile)
11+
12+
13+
export {profileRouter}

0 commit comments

Comments
 (0)