Skip to content

Commit

Permalink
fix some test + security
Browse files Browse the repository at this point in the history
  • Loading branch information
pelazas committed Mar 8, 2024
1 parent fe789c5 commit 8c905c2
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 21 deletions.
5 changes: 2 additions & 3 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ app.get('/health', (_req, res) => {
app.post('/login', async (req, res) => {
try {
// Forward the login request to the authentication service
console.log(authServiceUrl)
const authResponse = await axios.post(authServiceUrl+'/login', req.body);
res.json(authResponse.data);
} catch (error) {
Expand Down Expand Up @@ -64,7 +63,7 @@ app.post('/createGame', async (req, res) => {
const gameResponse = await axios.post(gameServiceUrl+'/createGame', {players, questions});
const game = gameResponse.data;
const gameUUID = game.uuid;
const updateLastGameResponse = await axios.post(userServiceUrl+'/updateLastGame', {gameUUID, players});
await axios.post(userServiceUrl+'/updateLastGame', {gameUUID, players});
res.json(questions);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
Expand All @@ -78,7 +77,7 @@ app.get('/getStats/:id', async (req, res) => {
const userStats = statsResponse.data;
const gameResponse = await axios.get(gameServiceUrl+'/getGame/'+userStats.lastGameId);
const ids = gameResponse.data[0].questions;
const questionsResponse = await axios.post(qgServiceUrl+'/getQuestionsByIds/', {ids});
const questionsResponse = await axios.post(qgServiceUrl+'/getQuestionsByIds', {ids});
const questionsData = questionsResponse.data;
const combinedResponse = {
userStats,
Expand Down
52 changes: 52 additions & 0 deletions gatewayservice/gateway-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ afterAll(async () => {

jest.mock('axios');

const authServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8002';
const userServiceUrl = process.env.USER_SERVICE_URL || 'http://localhost:8001';
const qgServiceUrl = process.env.QG_SERVICE_URL || 'http://localhost:8003';
const gameServiceUrl = process.env.GAME_SERVICE_URL || 'http://localhost:8004';

describe('Gateway Service', () => {
// Mock responses from external services
axios.post.mockImplementation((url, data) => {
Expand Down Expand Up @@ -41,6 +46,52 @@ describe('Gateway Service', () => {
expect(response.body.userId).toBe('mockedUserId');
});

it('fetches user stats successfuly', async () => {

const mockUserStats = {
id: 1,
username: 'testuser',
lastGameId: 2,
};

const mockGameResponse = {
data: [
{
questions: [1, 2, 3],
},
],
};

const mockQuestionsData = [
{ id: 1, question: 'Question 1' },
{ id: 2, question: 'Question 2' },
{ id: 3, question: 'Question 3' },
];
axios.get.mockImplementation((url) => {
if (url.endsWith(`/getStatistics/1`)) {
return Promise.resolve({ data: mockUserStats });
} else if (url.endsWith('/getGame/2')) {
return Promise.resolve(mockGameResponse);
}
return Promise.reject(new Error('Unexpected URL'));
});

axios.post.mockImplementation((url, data) => {
if (url.endsWith('/getQuestionsByIds')) {
expect(data).toEqual({ ids: [1, 2, 3] });
return Promise.resolve({ data: mockQuestionsData });
}
return Promise.reject(new Error('Unexpected URL'));
});

const response = await request(app).get('/getStats/1');

expect(response.statusCode).toBe(200);
expect(response.body).toEqual({
userStats: mockUserStats,
lastGame: mockQuestionsData,
});
})
/*it('should return questions on successful request to /createGame', async () => {
const testData = {
"players": [
Expand Down Expand Up @@ -69,4 +120,5 @@ describe('Gateway Service', () => {
expect(response.body).toEqual({ error: 'Internal server error' });
});
*/

});
16 changes: 0 additions & 16 deletions users/authservice/auth-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,6 @@ app.post('/login', async (req, res) => {
}
});

app.post("/updateLastGame", async (req, res) => {
try {
const { _id, players } = req.body;
players.map(async (p) => {
const user = await User.findById(p._id);
user.lastGame = _id;
await user.save();
console.log(user);
return user;
})
res.json(user);
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
})

// Start the server
const server = app.listen(port, () => {
console.log(`Auth Service listening at http://localhost:${port}`);
Expand Down
7 changes: 5 additions & 2 deletions users/userservice/UserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,20 @@ let UserController = {

for (const p of players) {
try {
const user = await User.findOne({ uuid: p.uuid });
let user;

Check failure

Code scanning / SonarCloud

NoSQL operations should not be vulnerable to injection attacks High

Change this code to not construct database queries directly from user-controlled data. See more on SonarCloud
if(p.uuid instanceof String){
user = await User.findOne({ uuid: p.uuid });

if (user) {
user.lastGameId = gameUUID;
await user.save();
} else {
console.error(`User with UUID ${p.uuid} not found.`);
}
}}
} catch (error) {
console.error(`Error updating last game for user with UUID ${p.uuid}: ${error.message}`);
}

}

const nPlayers = players.length;
Expand Down

0 comments on commit 8c905c2

Please sign in to comment.