Skip to content

Commit 066b17e

Browse files
authored
Merge pull request #46 from RahulHarihar/test/auth-signup-validation-cleanup
Test/auth signup validation cleanup
2 parents d14d04e + 563e56c commit 066b17e

File tree

5 files changed

+111
-37
lines changed

5 files changed

+111
-37
lines changed

backend/__tests__/auth.test.js

Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
process.env.NODE_ENV = 'test';
12
const request = require('supertest');
23
const mongoose = require('mongoose');
34
const { MongoMemoryServer } = require('mongodb-memory-server');
@@ -9,7 +10,11 @@ let mongoServer;
910
beforeAll(async () => {
1011
mongoServer = await MongoMemoryServer.create();
1112
const mongoUri = mongoServer.getUri();
12-
process.env.MONGO_URI = mongoUri;
13+
process.env.MONGO_URI = mongoUri;
14+
await mongoose.connect(mongoUri, {
15+
useNewUrlParser: true,
16+
useUnifiedTopology: true,
17+
});
1318
});
1419

1520
afterAll(async () => {
@@ -19,7 +24,6 @@ afterAll(async () => {
1924
});
2025

2126
describe('Auth API', () => {
22-
2327
beforeEach(async () => {
2428
await User.deleteMany({});
2529
});
@@ -36,7 +40,7 @@ describe('Auth API', () => {
3640

3741
expect(response.statusCode).toBe(201);
3842
expect(response.body).toHaveProperty('token');
39-
43+
4044
const savedUser = await User.findOne({ email: '[email protected]' });
4145
expect(savedUser).not.toBeNull();
4246
expect(savedUser.defaultCurrency).toBe('USD');
@@ -101,4 +105,71 @@ describe('Auth API', () => {
101105
expect(setupResponse.body.message).toBe('Default currency is required');
102106
});
103107

108+
it('should allow a new user to sign up', async () => {
109+
const newUser = {
110+
111+
password: 'Password123!',
112+
};
113+
114+
const response = await request(app).post('/api/auth/signup').send(newUser);
115+
116+
expect(response.statusCode).toBe(201);
117+
expect(response.body).toHaveProperty('token');
118+
119+
const savedUser = await User.findOne({ email: '[email protected]' });
120+
expect(savedUser).not.toBeNull();
121+
});
122+
123+
it('should reject signup with an existing email', async () => {
124+
const testUser = {
125+
126+
password: 'Password123!',
127+
};
128+
129+
await request(app).post('/api/auth/signup').send(testUser).expect(201);
130+
131+
const response = await request(app)
132+
.post('/api/auth/signup')
133+
.send(testUser)
134+
.expect(400);
135+
136+
expect(response.body.message).toBe('User already exists');
137+
138+
const users = await User.find({ email: testUser.email });
139+
expect(users.length).toBe(1);
140+
});
141+
142+
it('should reject signup when email is missing', async () => {
143+
const missingEmailUser = {
144+
email: "",
145+
password: 'Password123!',
146+
};
147+
148+
const response = await request(app)
149+
.post('/api/auth/signup')
150+
.send(missingEmailUser)
151+
.expect(400);
152+
153+
expect(response.body.message).toBe('Please enter all fields');
154+
155+
const users = await User.find({});
156+
expect(users.length).toBe(0);
157+
});
158+
159+
it('should reject signup when password is missing', async () => {
160+
const missingPasswordUser = {
161+
162+
password: "",
163+
};
164+
165+
const response = await request(app)
166+
.post('/api/auth/signup')
167+
.send(missingPasswordUser)
168+
.expect(400);
169+
170+
expect(response.body.message).toBe('Please enter all fields');
171+
172+
const users = await User.find({});
173+
expect(users.length).toBe(0);
174+
});
104175
});

backend/config/db.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ const connectDB = async () => {
66
console.log(`MongoDB Connected: ${conn.connection.host}`);
77
} catch (error) {
88
console.error(`Error: ${error.message}`);
9-
process.exit(1);
9+
if (process.env.NODE_ENV !== "test") {
10+
process.exit(1);
11+
}
1012
}
1113
};
1214

13-
module.exports = connectDB;
15+
module.exports = connectDB;

backend/middleware/validationMiddleware.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,19 @@ const { body, validationResult } = require('express-validator');
22
const dns = require('dns');
33

44
const validateRegistration = [
5+
(req, res, next) => {
6+
if (!req.body.email || !req.body.password) {
7+
return res.status(400).json({ message: "Please enter all fields" });
8+
}
9+
next();
10+
},
511
// Validate email
612
body('email')
713
.isEmail()
814
.withMessage('Please enter a valid email address.')
915
.bail() // Stop running validators if the previous one failed
1016
.custom(async (email) => {
11-
const domain = email.split('@')[1];
17+
const domain = email.split("@")[1];
1218

1319
// Quick blacklist for common invalid domains
1420
const blockedDomains = ['example.com', 'test.com', 'invalid.com'];
@@ -20,11 +26,15 @@ const validateRegistration = [
2026
try {
2127
const addresses = await dns.promises.resolveMx(domain);
2228
if (!addresses || addresses.length === 0) {
23-
return Promise.reject('Email domain does not exist or cannot receive mail.');
29+
return Promise.reject(
30+
'Email domain does not exist or cannot receive mail.'
31+
);
2432
}
2533
} catch (error) {
2634
// If DNS resolution fails
27-
return Promise.reject('Email domain does not exist or cannot receive mail.');
35+
return Promise.reject(
36+
'Email domain does not exist or cannot receive mail.'
37+
);
2838
}
2939
}),
3040

@@ -33,7 +43,9 @@ const validateRegistration = [
3343
.isLength({ min: 8, max: 16 })
3444
.withMessage('Password must be between 8 and 16 characters long.')
3545
.matches(/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_])/)
36-
.withMessage('Password must contain at least one alphabet, one digit, and one symbol.'),
46+
.withMessage(
47+
'Password must contain at least one alphabet, one digit, and one symbol.'
48+
),
3749

3850
// Middleware to handle the validation result
3951
(req, res, next) => {

backend/package-lock.json

Lines changed: 0 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

backend/server.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,18 @@ const allowedOrigins = [
2323
"https://paisable.netlify.app",
2424
];
2525

26-
app.use(cors({
27-
origin: function(origin, callback) {
28-
if (!origin || allowedOrigins.includes(origin)) {
29-
callback(null, true);
30-
} else {
31-
callback(new Error("Not allowed by CORS"));
32-
}
33-
},
34-
credentials: true
35-
}));
26+
app.use(
27+
cors({
28+
origin: function (origin, callback) {
29+
if (!origin || allowedOrigins.includes(origin)) {
30+
callback(null, true);
31+
} else {
32+
callback(new Error('Not allowed by CORS'));
33+
}
34+
},
35+
credentials: true,
36+
})
37+
);
3638
app.use(express.json());
3739

3840
// sanitizeMiddleware
@@ -55,9 +57,11 @@ app.get('/', (req, res) => {
5557

5658
const PORT = process.env.PORT || 5000;
5759

58-
const server = app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
60+
const server = app.listen(PORT, () =>
61+
console.log(`Server started on port ${PORT}`)
62+
);
5963

60-
cron.schedule("*/10 * * * *", async() => {
64+
cron.schedule("*/10 * * * *", async () => {
6165
const keepAliveUrl = process.env.KEEP_ALIVE_URL;
6266
if (!keepAliveUrl) {
6367
console.error(
@@ -74,4 +78,4 @@ cron.schedule("*/10 * * * *", async() => {
7478
}
7579
});
7680

77-
module.exports = { app, server };
81+
module.exports = { app, server };

0 commit comments

Comments
 (0)