Skip to content

Commit

Permalink
Backend for rankings
Browse files Browse the repository at this point in the history
  • Loading branch information
adriiglz committed Mar 8, 2024
1 parent 58a7509 commit 11ebe96
Show file tree
Hide file tree
Showing 8 changed files with 106 additions and 2 deletions.
20 changes: 20 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,32 @@ const express = require('express');
const axios = require('axios');
const cors = require('cors');
const promBundle = require('express-prom-bundle');
const cookieParser = require('cookie-parser');

const app = express();
const port = 8000;

const authServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8002';
const userServiceUrl = process.env.USER_SERVICE_URL || 'http://localhost:8001';

function parseCookies(response) {
const cookies = {};
const cookieHeader = response.headers['set-cookie']

if (cookieHeader) {
const cookieStrings = Array.isArray(cookieHeader) ? cookieHeader : [cookieHeader];
for (const cookieString of cookieStrings) {
const [name, value] = cookieString.split(';')[0].split('=');
cookies[name.trim()] = value.trim();
}
}

return cookies;
}

app.use(cors());
app.use(express.json());
app.use(cookieParser());

//Prometheus configuration
const metricsMiddleware = promBundle({includeMethod: true});
Expand All @@ -25,6 +42,9 @@ app.post('/login', async (req, res) => {
try {
// Forward the login request to the authentication service
const authResponse = await axios.post(authServiceUrl+'/login', req.body);
const cookies = parseCookies(authResponse)
const token = cookies.token
res.cookie('token', token)
res.json(authResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
Expand Down
21 changes: 21 additions & 0 deletions gatewayservice/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions gatewayservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"homepage": "https://github.com/arquisoft/wiq_en1a#readme",
"dependencies": {
"axios": "^1.6.5",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"express": "^4.18.2",
"express-prom-bundle": "^7.0.0"
Expand Down
8 changes: 6 additions & 2 deletions users/authservice/auth-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('./auth-model')
const User = require('./auth-model');
const cookieParser = require('cookie-parser')

const app = express();
const port = 8002;

// Middleware to parse JSON in request body
app.use(express.json());
// Middleware to do anything related with cookies
app.use(cookieParser())

// Connect to MongoDB
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb';
Expand Down Expand Up @@ -36,8 +39,9 @@ app.post('/login', async (req, res) => {

// Check if the user exists and verify the password
if (user && await bcrypt.compare(password, user.password)) {
// Generate a JWT token
// Generate a JWT token and save it in a cookie
const token = jwt.sign({ userId: user._id }, 'your-secret-key', { expiresIn: '1h' });
res.cookie('token', token);
// Respond with the token and user information
res.json({ token: token, username: username, createdAt: user.createdAt });
} else {
Expand Down
21 changes: 21 additions & 0 deletions users/authservice/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions users/authservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"dependencies": {
"bcrypt": "^5.1.1",
"body-parser": "^1.20.2",
"cookie-parser": "^1.4.6",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.4"
Expand Down
7 changes: 7 additions & 0 deletions users/userservice/user-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ const userSchema = new mongoose.Schema({
type: Date,
default: Date.now,
},
points: {
type: Number,
default: function() {
// Generate a random integer between 0 and 100
return Math.floor(Math.random() * 101);
}
}
});

const User = mongoose.model('User', userSchema);
Expand Down
29 changes: 29 additions & 0 deletions users/userservice/user-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,35 @@ function validateRequiredFields(req, requiredFields) {
}
}

// Function to get the user's ranking data
async function getRankingFor(loggedUser) {
const users = await User.find().sort({points: -1})
const ranking = users.indexOf( (user) => user._id == loggedUser._id)

return { ranking: ranking, points: loggedUser.points, user: loggedUser.username }
}

app.get('/rankings', async (req, res) => {
try {
const { token } = req.cookies
const decoded = jwt.verify(token, 'your-secret-key')
const userId = decoded.userId
const loggedUser = await User.findById(userId)
const userRanking = getRankingFor(loggedUser)
const usersRanking = (await User.find().sort({points: -1})).map( (user, index) => {
return {
ranking: index+1,
points: user.points,
user: user.username }
})

res.json(userRanking, usersRanking)

} catch (error) {
res.status(400).json({ error: error.message });
}
})

app.post('/adduser', async (req, res) => {
try {
// Check if required fields are present in the request body
Expand Down

0 comments on commit 11ebe96

Please sign in to comment.