-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackEnd.Server
More file actions
318 lines (241 loc) · 7.46 KB
/
BackEnd.Server
File metadata and controls
318 lines (241 loc) · 7.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
Step-by-Step Plan to Code the **Job Connect Platform**
This plan will guide you through the process of creating a **Job Connect Platform** with features such as **authentication**, **job listing**, **application management**, and **user profiles** using **React.js** for the frontend and **Node.js with Express** for the backend.
---
**Part 1: Setting Up the Backend (Node.js & Express)**
Step 1: Set Up the Project Directory
1. **Create a new directory** for the project:
```bash
mkdir job-connect
cd job-connect
```
2. **Initialize a new Node.js project**:
```bash
npm init -y
```
3. **Install required dependencies**:
```bash
npm install express mongoose bcryptjs jsonwebtoken dotenv
npm install --save-dev nodemon
```
4. **Create the folder structure**:
```bash
mkdir server
cd server
mkdir models routes controllers middleware config
touch server.js
```
---
Step 2: Configure Environment Variables
1. **Create a `.env` file** in the `server` folder:
```bash
touch .env
```
2. Add your MongoDB URI, JWT secret, and other environment variables:
```plaintext
MONGO_URI=your_mongo_connection_string
JWT_SECRET=your_jwt_secret_key
```
---
Step 3: Create Database Models
1. **Create `User.js` model** (`server/models/User.js`):
```js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
passwordHash: {
type: String,
required: true,
},
role: {
type: String,
enum: ["job_seeker", "recruiter"],
required: true,
},
});
module.exports = mongoose.model("User", userSchema);
```
2. **Create `Job.js` model** (`server/models/Job.js`):
```js
const mongoose = require("mongoose");
const jobSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
companyName: {
type: String,
required: true,
},
location: {
type: String,
required: true,
},
jobDescription: {
type: String,
required: true,
},
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
datePosted: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Job", jobSchema);
```
3. **Create `Application.js` model** (`server/models/Application.js`):
```js
const mongoose = require("mongoose");
const applicationSchema = new mongoose.Schema({
jobId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Job",
required: true,
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
status: {
type: String,
enum: ["applied", "under review", "rejected", "accepted"],
default: "applied",
},
dateApplied: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Application", applicationSchema);
```
---
Step 4: Create Authentication Logic
1. **Create Authentication Controller** (`server/controllers/authController.js`):
```js
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/User");
// Register User
const registerUser = async (req, res) => {
const { username, email, password, role } = req.body;
try {
const userExist = await User.findOne({ email });
if (userExist) return res.status(400).json({ message: "User already exists!" });
const salt = await bcrypt.genSalt(10);
const passwordHash = await bcrypt.hash(password, salt);
const newUser = new User({ username, email, passwordHash, role });
await newUser.save();
res.status(201).json({ message: "User registered successfully!" });
} catch (error) {
res.status(500).json({ message: "Server error!" });
}
};
// Login User
const loginUser = async (req, res) => {
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) return res.status(400).json({ message: "User not found!" });
const isMatch = await bcrypt.compare(password, user.passwordHash);
if (!isMatch) return res.status(400).json({ message: "Invalid credentials!" });
const token = jwt.sign({ userId: user._id, role: user.role }, process.env.JWT_SECRET, { expiresIn: "1h" });
res.status(200).json({ token });
} catch (error) {
res.status(500).json({ message: "Server error!" });
}
};
module.exports = { registerUser, loginUser };
```
2. **Create Authentication Routes** (`server/routes/authRoutes.js`):
```js
const express = require("express");
const { registerUser, loginUser } = require("../controllers/authController");
const router = express.Router();
router.post("/register", registerUser);
router.post("/login", loginUser);
module.exports = router;
```
---
Step 5: Create Job Listing Logic
1. **Create Job Controller** (`server/controllers/jobController.js`):
```js
const Job = require("../models/Job");
// Create Job Listing
const createJob = async (req, res) => {
const { title, companyName, location, jobDescription } = req.body;
const job = new Job({ title, companyName, location, jobDescription, createdBy: req.userId });
try {
await job.save();
res.status(201).json({ message: "Job posted successfully!" });
} catch (error) {
res.status(500).json({ message: "Error creating job!" });
}
};
module.exports = { createJob };
```
2. **Create Job Routes** (`server/routes/jobRoutes.js`):
```js
const express = require("express");
const { createJob } = require("../controllers/jobController");
const { protect } = require("../middleware/authMiddleware");
const router = express.Router();
router.post("/jobs", protect, createJob);
module.exports = router;
```
---
Step 6: Middleware for Protecting Routes
1. **Create Authentication Middleware** (`server/middleware/authMiddleware.js`):
```js
const jwt = require("jsonwebtoken");
const protect = (req, res, next) => {
const token = req.header("x-auth-token");
if (!token) return res.status(401).json({ message: "No token, authorization denied" });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
req.role = decoded.role;
next();
} catch (error) {
res.status(401).json({ message: "Token is not valid" });
}
};
module.exports = { protect };
```
---
Step 7: Set Up the Server
1. **Create the Express server** (`server/server.js`):
```js
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const authRoutes = require("./routes/authRoutes");
const jobRoutes = require("./routes/jobRoutes");
dotenv.config();
const app = express();
app.use(express.json());
app.use("/api/auth", authRoutes);
app.use("/api", jobRoutes);
const start = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log("Connected to MongoDB");
app.listen(5000, () => console.log("Server running on port 5000"));
} catch (error) {
console.error(error);
}
};
start();
```
---