Skip to content

Commit 023e0d1

Browse files
committed
initial commit
0 parents  commit 023e0d1

10 files changed

+2039
-0
lines changed

Diff for: .gitignore

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# dependencies
2+
/node_modules
3+
/.pnp
4+
.pnp.js
5+
.env
6+
7+
# testing
8+
/coverage
9+
10+
# production
11+
/build
12+
13+
# misc
14+
.DS_Store
15+
.env.local
16+
.env.development.local
17+
.env.test.local
18+
.env.production.local
19+
20+
npm-debug.log*
21+
yarn-debug.log*
22+
yarn-error.log*

Diff for: controllers/authController.js

+232
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
// controllers/authController.js
2+
3+
const bcrypt = require('bcrypt');
4+
const passport = require('passport');
5+
const User = require('../models/User');
6+
const validator = require('validator');
7+
8+
//Register
9+
exports.register = async (req, res) => {
10+
const { name, username, password } = req.body;
11+
12+
try {
13+
// Input validation
14+
if (!name || !username || !password) {
15+
return res.status(400).json({ message: 'Missing required fields' });
16+
}
17+
18+
if (!validator.isEmail(username)) {
19+
return res.status(400).json({ message: 'Invalid email format' });
20+
}
21+
22+
// Password complexity validation (e.g., at least 8 characters with numbers and letters)
23+
const passwordRegex = /^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/;
24+
if (!passwordRegex.test(password)) {
25+
return res.status(400).json({
26+
message:
27+
'Password must be at least 8 characters long and contain both letters and numbers',
28+
});
29+
}
30+
// Check if the user already exists
31+
const existingUser = await User.findOne({ username });
32+
if (existingUser) {
33+
return res.status(409).json({ message: 'User Already Exists' });
34+
}
35+
36+
// Hash the password
37+
const hashedPassword = await bcrypt.hash(password, 10);
38+
39+
// Create a new user
40+
const user = new User({
41+
name,
42+
username,
43+
password: hashedPassword,
44+
});
45+
46+
// Save the user to the database
47+
await user.save();
48+
49+
// Respond with the created user object
50+
res.status(201).json(user);
51+
} catch (error) {
52+
console.error(error);
53+
54+
// Handle specific error scenarios
55+
if (error.name === 'ValidationError') {
56+
return res
57+
.status(400)
58+
.json({ message: 'Validation Error', details: error.message });
59+
}
60+
61+
// For other errors, respond with a generic error message
62+
res.status(500).json({ message: 'Server error' });
63+
}
64+
};
65+
66+
//Login
67+
exports.login = (req, res, next) => {
68+
// eslint-disable-next-line no-unused-vars
69+
passport.authenticate('local', (err, user, info) => {
70+
if (err) {
71+
console.error(err);
72+
return res.status(500).json({ message: 'Server error' });
73+
}
74+
if (!user) {
75+
return res.status(401).json({ message: 'Invalid credentials' });
76+
}
77+
req.logIn(user, (err) => {
78+
if (err) {
79+
console.error(err);
80+
return res.status(500).json({ message: 'Server error' });
81+
}
82+
res.status(200).json(user);
83+
});
84+
})(req, res, next);
85+
};
86+
87+
// Logout
88+
// exports.logout = (req, res) => {
89+
// const loggedOutUser = req.user; // Retrieve the currently logged-in user
90+
91+
// req.logout(function (err) {
92+
// if (err) {
93+
// console.error(err);
94+
// return res.status(500).json({ message: 'Server error' });
95+
// }
96+
97+
// // Include the logged-out user information in the response if available
98+
// if (loggedOutUser) {
99+
// res.status(200).json({
100+
// message: 'Logged out successfully',
101+
// user: loggedOutUser,
102+
// });
103+
// } else {
104+
// res.status(200).json({ message: 'Logged out successfully' });
105+
// }
106+
// });
107+
// };
108+
109+
//Get Single User Details
110+
// exports.getUserDetails = (req, res) => {
111+
// const userId = req.params.id;
112+
113+
// User.findById(userId)
114+
// .then((user) => {
115+
// if (!user) {
116+
// return res.status(404).json({ message: 'User not found' });
117+
// }
118+
// res.json(user);
119+
// })
120+
// .catch((error) => {
121+
// console.error('Failed to get user details', error);
122+
// res.status(500).json({ message: 'Failed to get user details' });
123+
// });
124+
// };
125+
126+
// Get all users list
127+
exports.getAllUsers = (req, res) => {
128+
try {
129+
User.find()
130+
.then((users) => {
131+
if (!users || users.length === 0) {
132+
return res.status(404).json({ message: 'Users not found' });
133+
}
134+
res.json(users);
135+
})
136+
.catch((error) => {
137+
console.error('Failed to get users list', error);
138+
res.status(500).json({ message: 'Failed to get users list' });
139+
});
140+
} catch (error) {
141+
console.error('Error fetching users', error);
142+
res.status(500).json({ message: 'Server error' });
143+
}
144+
};
145+
146+
//Update Password
147+
// exports.updatePassword = async (req, res) => {
148+
// const userId = req.params.id;
149+
// const { currentPassword, newPassword } = req.body;
150+
151+
// try {
152+
// const user = await User.findById(userId);
153+
// if (!user) {
154+
// return res.status(404).json({ message: 'User not found' });
155+
// }
156+
157+
// const isMatch = await bcrypt.compare(currentPassword, user.password);
158+
// if (!isMatch) {
159+
// return res
160+
// .status(401)
161+
// .json({ message: 'Incorrect current password' });
162+
// }
163+
164+
// const hashedPassword = await bcrypt.hash(newPassword, 10);
165+
// user.password = hashedPassword;
166+
// await user.save();
167+
168+
// res.json({ message: 'Password updated successfully' });
169+
// } catch (error) {
170+
// console.error('Failed to update password', error);
171+
// res.status(500).json({ message: 'Failed to update password' });
172+
// }
173+
// };
174+
175+
//Update User Details
176+
exports.updateUserDetails = async (req, res) => {
177+
const { name, username, password } = req.body;
178+
const userId = req.params.id;
179+
console.log(userId)
180+
if(name) console.log(name)
181+
if(username) console.log(username)
182+
if(password)console.log(password)
183+
184+
try {
185+
// Find the user by the provided userId
186+
const user = await User.findById(userId);
187+
if (!user) {
188+
return res.status(404).json({ message: 'User not found' });
189+
}
190+
191+
// Update the user details
192+
user.name = name;
193+
user.username = username;
194+
195+
// Check if the password field is provided and not empty
196+
if (password && password.trim() !== '') {
197+
// Hash the new password and update it
198+
const hashedPassword = await bcrypt.hash(password, 10);
199+
user.password = hashedPassword;
200+
}
201+
202+
// Save the updated user to the database
203+
await user.save();
204+
205+
res.json({ message: 'User details updated successfully' });
206+
} catch (error) {
207+
console.error('Failed to update user:', error);
208+
res.status(500).json({ message: 'Failed to update user details' });
209+
}
210+
};
211+
212+
//Delete User
213+
// DELETE /users/:userId - Delete a user by their userId
214+
exports.deleteUser = async (req, res) => {
215+
const userId = req.params.id;
216+
217+
try {
218+
// Find the user by the provided userId
219+
const user = await User.findById(userId);
220+
if (!user) {
221+
return res.status(404).json({ message: 'User not found' });
222+
}
223+
224+
// Delete the user from the database
225+
await user.deleteOne(); // Or use await User.deleteOne({ _id: userId }); directly
226+
227+
res.json({ message: 'User deleted successfully' });
228+
} catch (error) {
229+
console.error('Failed to delete user:', error);
230+
res.status(500).json({ message: 'Failed to delete user' });
231+
}
232+
};

Diff for: database-setup.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const mongoose = require('mongoose');
2+
3+
const URI = process.env.URI;
4+
5+
// Connect to MongoDB
6+
exports.connectMongoose = async () => {
7+
try {
8+
await mongoose.connect(URI, {
9+
useNewUrlParser: true,
10+
useUnifiedTopology: true,
11+
});
12+
console.log('Connected to MongoDB');
13+
} catch (error) {
14+
console.error('MongoDB connection error:', error);
15+
}
16+
};

Diff for: index.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
const express = require('express');
2+
const session = require('express-session');
3+
const passport = require('passport');
4+
5+
// Routes Import
6+
const authRoutes = require('./routes/authRoutes');
7+
8+
// env setup
9+
require('dotenv').config();
10+
11+
// eslint-disable-next-line no-unused-vars
12+
const passportConfig = require('./passportConfig');
13+
const { connectMongoose } = require('./database-setup');
14+
15+
const app = express();
16+
const PORT = process.env.PORT;
17+
const SESSION_SECRET_KEY = process.env.SESSION_SECRET_KEY;
18+
19+
//cors setup
20+
const cors = require('cors');
21+
app.use(cors());
22+
23+
// Middleware
24+
app.use(express.json());
25+
app.use(express.urlencoded({ extended: true }));
26+
app.use(
27+
session({
28+
secret: SESSION_SECRET_KEY,
29+
resave: true,
30+
saveUninitialized: true,
31+
cookie: {
32+
httpOnly: true,
33+
// secure: true //for https not for localhost
34+
// 1000 milliseconds
35+
expires: Date.now * 1000 * 60 * 60 * 24,
36+
maxAge: 1000 * 60 * 60 * 24,
37+
},
38+
}),
39+
);
40+
// Initialize Passport configuration
41+
app.use(passport.initialize());
42+
app.use(passport.session());
43+
44+
// Connect to MongoDB
45+
connectMongoose();
46+
47+
// Routes
48+
app.use(authRoutes);
49+
50+
// Start server
51+
app.listen(PORT, () =>
52+
console.log(`Server listening on port http://localhost:${PORT}`),
53+
);

Diff for: models/User.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// models/User.js
2+
const mongoose = require('mongoose');
3+
4+
const userSchema = new mongoose.Schema({
5+
name: { type: String, required: true },
6+
username: { type: String, required: true, unique: true },
7+
password: { type: String, required: true },
8+
});
9+
10+
const User = mongoose.model('User', userSchema);
11+
12+
module.exports = User;

0 commit comments

Comments
 (0)