Skip to content

Commit

Permalink
Merge pull request #60 from pes2324q2-gei-upc/notificacions
Browse files Browse the repository at this point in the history
Notificacions
  • Loading branch information
susssss23 authored May 28, 2024
2 parents 675045c + c0a1e94 commit bbfd617
Show file tree
Hide file tree
Showing 6 changed files with 157 additions and 5 deletions.
2 changes: 2 additions & 0 deletions back_api/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const xatsRoutes = require('./routes/xats')
const grupsRoutes = require('./routes/grups')
const organitzadorsRoutes = require('./routes/organitzadors')
const insigniesRoutes = require('./routes/insignies')
const notificacioRoutes = require('./routes/notificacio')

global.callCount = 0;

Expand All @@ -30,5 +31,6 @@ app.use('/xats', xatsRoutes)
app.use('/grups', grupsRoutes)
app.use('/organitzadors', organitzadorsRoutes)
app.use('/insignies', insigniesRoutes)
app.use('/notificacio', notificacioRoutes)

module.exports = app
1 change: 1 addition & 0 deletions back_api/routes/grups.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ router.post('/:grupId/mensajes', checkUserAndFetchData, async (req, res) => {
});

res.status(201).send("Mensaje agregado exitosamente al grup");

} catch (error) {
res.status(500).send("Error interno del servidor");
}
Expand Down
31 changes: 31 additions & 0 deletions back_api/routes/notificacio.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const admin = require('firebase-admin')
const express = require('express')
const router = express.Router()

router.use(express.json());

const checkUserAndFetchData = require('./middleware').checkUserAndFetchData;

//penjar notificacions
router.post('/enviar', checkUserAndFetchData, async (req, res) => {
const { title, mensaje, token } = req.body;

const message = {
notification: {
title: title,
body: mensaje,
},
token: token,
};

admin.messaging().send(message)
.then((response) => {
res.status(201).send('Notificacio enviada');
})
.catch((error) => {
res.status(500).send('Error enviant la notificació');
});

});

module.exports = router;
29 changes: 27 additions & 2 deletions back_api/routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,30 @@ router.post('/edit', checkUserAndFetchData, async(req, res) => { //MODIFICAR PAR
}
});

router.post('/addDevice', checkUserAndFetchData, async(req, res) => {
try {
const { uid, devices } = req.body;

userDoc = await req.userDocument;
const devicesNou = JSON.parse(devices);

const usersCollection = db.collection('users');

if (userDoc.exists && userDoc.id == uid) {
await usersCollection.doc(uid).update({
'devices': devicesNou
});
res.status(200).send('OK');
}
else {
res.status(401).send('Forbidden');
}

} catch (error){
res.send(error);
}
});

router.post('/changePrivacy', checkUserAndFetchData, async(req, res) => {

try {
Expand Down Expand Up @@ -665,7 +689,7 @@ router.put('/escanearQR', checkUserAndFetchData, async (req, res) => {

router.post('/create', async(req, res) => {
try {
const { uid, username, email, favcategories } = req.body;
const { uid, username, email, favcategories, devices } = req.body;

const categories = favcategories;

Expand All @@ -687,7 +711,8 @@ router.post('/create', async(req, res) => {
'valoradas': valoradas,
'blockedUsers': blockedUsers,
'AssitedActivities': AssitedActivities,
'private': false
'private': false,
'devices': devices
});
await crearInsignies(uid);
res.status(200).send('OK');
Expand Down
59 changes: 59 additions & 0 deletions back_api/tests/notificacio.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const request = require('supertest');
const app = require('../app');
const admin = require('firebase-admin');

const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
const iv = Buffer.from(process.env.ENCRYPTION_IV, 'hex');

function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
}

jest.mock('firebase-admin', () => {
const messaging = {
send: jest.fn(),
};
return {
messaging: () => messaging,
};
});

describe('POST /notificacio/enviar', () => {
const users = [
user1 = {
id: "user1",
username: "user1",
email: "",
blockedUsers: ["user2"]
},
];

beforeEach(async () => {
for (const user of users) {
await db.collection('users').doc(user.id).set(user);
}
});

it('should create a notification', async () => {
admin.messaging().send.mockResolvedValue('Successfully sent message');
const body = {
title: 'titleTest',
mensaje: 'mensajeTest',
token: 'tokenTest'
};

const res = await request(app)
.post('/notificacio/enviar')
.set('Authorization', `Bearer ${encrypt('user1').encryptedData}`)
.send(body);

expect(res.statusCode).toEqual(201);
expect(res.text).toBe('Notificacio enviada');
});

});
40 changes: 37 additions & 3 deletions back_api/tests/users.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,49 @@ describe('POST /users/create', () => {
uid: 'testUid',
username: 'testUser',
email: 'testEmail',
favcategories: JSON.stringify(['festa', 'cinema'])
favcategories: JSON.stringify(['festa', 'cinema']),
devices: JSON.stringify(['deviceTest'])
});

expect(res.statusCode).toEqual(200);
expect(res.text).toBe('OK');

const docs = await db.collection('users').doc('testUid').get();
expect(docs.empty).toBeFalsy();
});
});

describe('POST /users/addDevice', () => {
it('should add a new device', async () => {
const resA = await request(app)
.post('/users/create')
.send({
uid: 'testUid6',
username: 'testUser',
email: 'testEmail',
favcategories: JSON.stringify(['festa', 'cinema']),
devices: JSON.stringify(['deviceTest'])
});

expect(resA.statusCode).toEqual(200);
expect(resA.text).toBe('OK');

const res = await request(app)
.post('/users/addDevice')
.set('Authorization', `Bearer ${encrypt('testUid6').encryptedData}`)
.send({
uid: 'testUid6',
devices: JSON.stringify("[\"deviceTest\",\"deviceTest1\"]")
});

expect(res.statusCode).toEqual(200);
expect(res.text).toBe('OK');

const docs = await db.collection('users').doc('testUid6').get();
expect(docs.empty).toBeFalsy();
expect(docs.data().devices).toBe(JSON.stringify(['deviceTest', 'deviceTest1']));
});
});

describe('POST /users/activitats/signout', () => {
it('should signout a user from an activity', async () => {
const users = [
Expand Down Expand Up @@ -353,7 +385,8 @@ describe('POST /users/edit', () => {
uid: 'testUid1',
username: 'testUser',
email: 'testEmail',
favcategories: JSON.stringify(['circ'])
favcategories: JSON.stringify(['festa', 'cinema']),
devices: JSON.stringify(['deviceTest'])
});

expect(res.statusCode).toEqual(200);
Expand Down Expand Up @@ -387,6 +420,7 @@ describe('POST /users/changePrivacy', () => {
username: 'testUser',
email: 'testEmail',
favcategories: JSON.stringify(['circ', 'cinema']),
devices: JSON.stringify(['deviceTest']),
privacy: false
});

Expand Down

0 comments on commit bbfd617

Please sign in to comment.