- cleaned some code.
- routing offline - pushNotification
This commit is contained in:
@@ -8,11 +8,12 @@ var authenticate = (req, res, next) => {
|
|||||||
var token = req.header('x-auth');
|
var token = req.header('x-auth');
|
||||||
|
|
||||||
const useragent = req.get('User-Agent');
|
const useragent = req.get('User-Agent');
|
||||||
|
const access = 'auth ' + useragent;
|
||||||
|
|
||||||
// tools.mylog("TOKEN = ", token);
|
tools.mylog("TOKEN = ", token);
|
||||||
// tools.mylog("USER-AGENT = ", useragent);
|
tools.mylog("USER-AGENT = ", useragent);
|
||||||
|
|
||||||
User.findByToken(token, 'auth ' + useragent).then((user) => {
|
User.findByToken(token, access).then((user) => {
|
||||||
if (!user) {
|
if (!user) {
|
||||||
tools.mylog("TOKEN NOT FOUND! Maybe Connected to other Page");
|
tools.mylog("TOKEN NOT FOUND! Maybe Connected to other Page");
|
||||||
return Promise.reject(server_constants.RIS_CODE_HTTP_INVALID_TOKEN);
|
return Promise.reject(server_constants.RIS_CODE_HTTP_INVALID_TOKEN);
|
||||||
@@ -22,6 +23,7 @@ var authenticate = (req, res, next) => {
|
|||||||
|
|
||||||
req.user = user;
|
req.user = user;
|
||||||
req.token = token;
|
req.token = token;
|
||||||
|
req.access = access;
|
||||||
next();
|
next();
|
||||||
}).catch((e) => {
|
}).catch((e) => {
|
||||||
tools.mylog("ERR =", e);
|
tools.mylog("ERR =", e);
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ const SubscriberSchema = new Schema({
|
|||||||
endpoint: String,
|
endpoint: String,
|
||||||
keys: Schema.Types.Mixed,
|
keys: Schema.Types.Mixed,
|
||||||
userId: String,
|
userId: String,
|
||||||
|
access: String,
|
||||||
createDate: {
|
createDate: {
|
||||||
type: Date,
|
type: Date,
|
||||||
default: Date.now
|
default: Date.now
|
||||||
|
|||||||
@@ -4,12 +4,53 @@ const mongoose = require('mongoose');
|
|||||||
const Subscription = mongoose.model('subscribers');
|
const Subscription = mongoose.model('subscribers');
|
||||||
const webpush = require('web-push');
|
const webpush = require('web-push');
|
||||||
|
|
||||||
|
var { authenticate } = require('../middleware/authenticate');
|
||||||
|
|
||||||
|
const isValidSaveRequest = (req, res) => {
|
||||||
|
try {
|
||||||
|
if (!req.body || !req.body.subs.endpoint) {
|
||||||
|
res.status(400);
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
res.send(JSON.stringify({
|
||||||
|
error: {
|
||||||
|
id: 'no-endpoint',
|
||||||
|
message: 'Subscription must have an endpoint'
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
} catch (e) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
router.post('/', (req, res) => {
|
router.post('/', (req, res) => {
|
||||||
console.log('req.body.others', req.body.others);
|
console.log('req.body.others', req.body.others);
|
||||||
let subscriptionModel = new Subscription(req.body.subs);
|
|
||||||
subscriptionModel.userId = req.body.others.userId
|
|
||||||
|
|
||||||
subscriptionModel.save((err, subscription) => {
|
if (!isValidSaveRequest(req, res)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let subscriptionModel = new Subscription(req.body.subs);
|
||||||
|
subscriptionModel.userId = req.body.others.userId;
|
||||||
|
subscriptionModel.access = req.body.others.access;
|
||||||
|
|
||||||
|
// Find if already exist
|
||||||
|
Subscription.findOne( {userId: subscriptionModel.userId, access: subscriptionModel.access})
|
||||||
|
.then(itemsub => {
|
||||||
|
return itemsub
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
// Not found
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
.then(myitem => {
|
||||||
|
|
||||||
|
if (myitem === null)
|
||||||
|
myitem = subscriptionModel;
|
||||||
|
|
||||||
|
myitem.save((err, subscription) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error(`Error occurred while saving subscription. Err: ${err}`);
|
console.error(`Error occurred while saving subscription. Err: ${err}`);
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
@@ -17,20 +58,27 @@ router.post('/', (req, res) => {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Send 201 - resource created
|
// Send 201 - resource created
|
||||||
res.status(201).json({ data: 'Subscription saved.' });
|
// res.status(201).json({ data: 'Subscription saved.' });
|
||||||
|
res.send({ data: 'Subscription saved.' });
|
||||||
|
|
||||||
sendBackNotif(subscription, req.body.options)
|
tools.sendBackNotif(subscription, req.body.options)
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
router.delete('/del', authenticate, (req, res) => {
|
||||||
|
// tools.mylog("TOKENREM = " + req.token);
|
||||||
|
Subscription.findOneAndRemove( { userId: req.user._id, access: req.access } ).then(() => {
|
||||||
|
res.status(200).send();
|
||||||
|
}, () => {
|
||||||
|
res.status(400).send();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function sendBackNotif(subscription, payload) {
|
|
||||||
|
|
||||||
console.log('payload');
|
|
||||||
// Pass object into sendNotification
|
|
||||||
webpush.sendNotification(subscription, JSON.stringify(payload)).catch(err => console.error(err));
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
router.get('/', (req, res) => {
|
router.get('/', (req, res) => {
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
|
|
||||||
|
// SETTINGS WebPush Configuration
|
||||||
const webpush = require('web-push');
|
const webpush = require('web-push');
|
||||||
|
|
||||||
|
const publicVapidKey = process.env.PUBLIC_VAPI_KEY;
|
||||||
|
const privateVapidKey = process.env.PRIVATE_VAPI_KEY;
|
||||||
|
webpush.setVapidDetails('mailto:' + process.env.EMAIL_FROM, publicVapidKey, privateVapidKey);
|
||||||
|
|
||||||
const tools = require('../tools/general');
|
const tools = require('../tools/general');
|
||||||
|
|
||||||
var server_constants = require('../tools/server_constants');
|
var server_constants = require('../tools/server_constants');
|
||||||
@@ -27,11 +34,7 @@ router.post('/', authenticate, (req, res) => {
|
|||||||
|
|
||||||
// todo.expiring_at = new Date(todo.expiring_at);
|
// todo.expiring_at = new Date(todo.expiring_at);
|
||||||
|
|
||||||
tools.mylogshow('TODO', todo);
|
tools.mylog('ID :', todo._id, todo.descr, todo.userId, req.user._id);
|
||||||
|
|
||||||
tools.mylog('ID :', todo._id);
|
|
||||||
|
|
||||||
tools.mylog('userid', todo.userId, req.user._id);
|
|
||||||
|
|
||||||
if (!('descr' in req.body)){
|
if (!('descr' in req.body)){
|
||||||
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
||||||
@@ -50,14 +53,19 @@ router.post('/', authenticate, (req, res) => {
|
|||||||
console.log('RECORD NON VALIDO !?', req.body)
|
console.log('RECORD NON VALIDO !?', req.body)
|
||||||
}
|
}
|
||||||
|
|
||||||
sendNotificationToUser(todo.userId, 'New Todo', 'New Todo added!', '/' + todo.category, 'todo');
|
|
||||||
|
|
||||||
todo.save().then((writeresult) => {
|
todo.save().then((writeresult) => {
|
||||||
let idobj = writeresult._id;
|
let idobj = writeresult._id;
|
||||||
Todo.findById(idobj)
|
Todo.findById(idobj)
|
||||||
.then(record => {
|
.then(record => {
|
||||||
tools.mylog('REC SAVED :', record.descr);
|
tools.mylog('REC SAVED :', record.descr);
|
||||||
res.send({record});
|
res.send({record});
|
||||||
|
|
||||||
|
try {
|
||||||
|
sendNotificationToUser(todo.userId, 'Todo: ' + record.descr, record.descr, '/' + todo.category, 'todo');
|
||||||
|
} catch (e) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
}).catch((e) => {
|
}).catch((e) => {
|
||||||
console.log('ERRORE in TODO POST', e.message);
|
console.log('ERRORE in TODO POST', e.message);
|
||||||
@@ -80,7 +88,7 @@ function sendNotificationToUser(userId, title, content, openUrl, tag) {
|
|||||||
// tag: req.body.tag
|
// tag: req.body.tag
|
||||||
};
|
};
|
||||||
|
|
||||||
Subscription.find({userId: userId}, (err, subscriptions) => {
|
Subscription.find({ userId }, (err, subscriptions) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error(`Error occurred while getting subscriptions`);
|
console.error(`Error occurred while getting subscriptions`);
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
@@ -108,6 +116,10 @@ function sendNotificationToUser(userId, title, content, openUrl, tag) {
|
|||||||
headers: {}
|
headers: {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// console.log('pushSubscription', pushSubscription);
|
||||||
|
// console.log('pushOptions', pushOptions);
|
||||||
|
// console.log('pushPayload', pushPayload);
|
||||||
|
|
||||||
webpush.sendNotification(
|
webpush.sendNotification(
|
||||||
pushSubscription,
|
pushSubscription,
|
||||||
pushPayload,
|
pushPayload,
|
||||||
@@ -126,8 +138,7 @@ function sendNotificationToUser(userId, title, content, openUrl, tag) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}).catch(error => {
|
}).catch(error => {
|
||||||
console.log('ERROR: sendNotificationToUser', error
|
console.log('ERROR: sendNotificationToUser', error.data)
|
||||||
)
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
|
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
|
||||||
@@ -154,7 +165,7 @@ router.patch('/:id', authenticate, (req, res) => {
|
|||||||
|
|
||||||
|
|
||||||
Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
|
Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
|
||||||
tools.mylogshow(' TODO TO MODIFY: ', todo)
|
tools.mylogshow(' TODO TO MODIFY: ', todo.descr, todo.expiring_at);
|
||||||
if (!todo) {
|
if (!todo) {
|
||||||
return res.status(404).send();
|
return res.status(404).send();
|
||||||
}
|
}
|
||||||
@@ -193,7 +204,7 @@ router.get('/:userId', authenticate, (req, res) => {
|
|||||||
// Extract all the todos of the userId only
|
// Extract all the todos of the userId only
|
||||||
Todo.findAllByUserId(userId).then((todos) => {
|
Todo.findAllByUserId(userId).then((todos) => {
|
||||||
|
|
||||||
tools.mylog('todos', todos);
|
tools.mylog('todos', todos.length);
|
||||||
|
|
||||||
res.send({ todos: todos });
|
res.send({ todos: todos });
|
||||||
}).catch((e) => {
|
}).catch((e) => {
|
||||||
|
|||||||
@@ -15,6 +15,19 @@ var reg = require('../reg/registration');
|
|||||||
|
|
||||||
var { authenticate } = require('../middleware/authenticate');
|
var { authenticate } = require('../middleware/authenticate');
|
||||||
|
|
||||||
|
var mongoose = require('mongoose');
|
||||||
|
const Subscription = mongoose.model('subscribers');
|
||||||
|
|
||||||
|
function existSubScribe(userId, access) {
|
||||||
|
return Subscription.findOne({ userId, access })
|
||||||
|
.then(itemsub => {
|
||||||
|
return itemsub
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
// POST /users
|
// POST /users
|
||||||
router.post('/', (req, res) => {
|
router.post('/', (req, res) => {
|
||||||
@@ -90,7 +103,10 @@ router.post('/login', (req, res) => {
|
|||||||
if (!user) {
|
if (!user) {
|
||||||
tools.mylogshow("NOT FOUND !");
|
tools.mylogshow("NOT FOUND !");
|
||||||
res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
|
res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
|
||||||
} else {
|
}
|
||||||
|
})
|
||||||
|
.then(user => {
|
||||||
|
let mytoken = '';
|
||||||
return user.generateAuthToken(req).then((token) => {
|
return user.generateAuthToken(req).then((token) => {
|
||||||
var usertosend = User();
|
var usertosend = User();
|
||||||
usertosend.username = user.username;
|
usertosend.username = user.username;
|
||||||
@@ -103,13 +119,53 @@ router.post('/login', (req, res) => {
|
|||||||
|
|
||||||
// tools.mylog("usertosend:");
|
// tools.mylog("usertosend:");
|
||||||
// tools.mylog(usertosend);
|
// tools.mylog(usertosend);
|
||||||
res.header('x-auth', token).send({usertosend, code: server_constants.RIS_CODE_OK});
|
return usertosend
|
||||||
|
})
|
||||||
|
.then((usertosend) => {
|
||||||
|
const useragent = req.get('User-Agent');
|
||||||
|
const access = 'auth ' + useragent;
|
||||||
|
// if (usertosend.tokens.length > 0)
|
||||||
|
// access = usertosend.tokens[usertosend.tokens.length - 1].access;
|
||||||
|
|
||||||
|
return existSubScribe(usertosend.userId, access)
|
||||||
|
.then(subscribe => {
|
||||||
|
if (subscribe === null) {
|
||||||
|
// Doesn't exist, so save sub passed in INPUT
|
||||||
|
let subscriptionModel = new Subscription(req.body.subs);
|
||||||
|
subscriptionModel.userId = usertosend._id;
|
||||||
|
subscriptionModel.access = access;
|
||||||
|
|
||||||
|
return subscriptionModel.save((err, subscription) => {
|
||||||
|
if (err) {
|
||||||
|
console.error(`Error occurred while saving subscription. Err: ${err}`);
|
||||||
|
res.status(500).json({
|
||||||
|
error: 'Technical error occurred'
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Send 201 - resource created
|
||||||
|
// res.status(201).json({ data: 'Subscription saved.' });
|
||||||
|
// res.send({ data: 'Subscription saved.' });
|
||||||
|
|
||||||
|
tools.sendBackNotif(subscription, req.body.options)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { usertosend }
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
return { usertosend }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then((usertosend) => {
|
||||||
|
console.log('res', mytoken, usertosend);
|
||||||
|
|
||||||
|
res.header('x-auth', mytoken).send({ usertosend, code: server_constants.RIS_CODE_OK });
|
||||||
// tools.mylog("TROVATOOO!");
|
// tools.mylog("TROVATOOO!");
|
||||||
|
|
||||||
tools.mylog('FINE LOGIN')
|
tools.mylog('FINE LOGIN')
|
||||||
});
|
});
|
||||||
}
|
})
|
||||||
}).catch((e) => {
|
.catch((e) => {
|
||||||
tools.mylog("ERRORE IN LOGIN: " + e);
|
tools.mylog("ERRORE IN LOGIN: " + e);
|
||||||
res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -64,12 +64,6 @@ app.use(bodyParser.json());
|
|||||||
|
|
||||||
app.use(i18n.init);
|
app.use(i18n.init);
|
||||||
|
|
||||||
// SETTINGS WebPush Configuration
|
|
||||||
const webpush = require('web-push');
|
|
||||||
|
|
||||||
const publicVapidKey = process.env.PUBLIC_VAPI_KEY;
|
|
||||||
const privateVapidKey = process.env.PRIVATE_VAPI_KEY;
|
|
||||||
webpush.setVapidDetails('mailto:' + process.env.EMAIL_FROM, publicVapidKey, privateVapidKey);
|
|
||||||
|
|
||||||
|
|
||||||
// Use Routes
|
// Use Routes
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ const IndexTodoToCreate = 3;
|
|||||||
// const useragent = "auth Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36";
|
// const useragent = "auth Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36";
|
||||||
const useragent = "node-superagent/2.3.0";
|
const useragent = "node-superagent/2.3.0";
|
||||||
|
|
||||||
const testsingolo = true;
|
const testsingolo = false;
|
||||||
|
|
||||||
if (testsingolo) {
|
if (testsingolo) {
|
||||||
it('should create a new Todos', (done) => {
|
it('should create a new Todos', (done) => {
|
||||||
@@ -181,40 +181,40 @@ if (testsingolo) {
|
|||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// describe('DELETE /users/me/token', () => {
|
describe('DELETE /users/me/token', () => {
|
||||||
// it('should logout user deleting auth token', (done) => {
|
it('should logout user deleting auth token', (done) => {
|
||||||
// request(app)
|
request(app)
|
||||||
// .delete('/users/me/token')
|
.delete('/users/me/token')
|
||||||
// .set('x-auth', users[0].tokens[0].token)
|
.set('x-auth', users[0].tokens[0].token)
|
||||||
// .send()
|
.send()
|
||||||
// .expect(200)
|
.expect(200)
|
||||||
// .expect((res) => {
|
.expect((res) => {
|
||||||
// expect(res.headers['x-auth']).toNotExist();
|
expect(res.headers['x-auth']).toNotExist();
|
||||||
// })
|
})
|
||||||
// .end((err, res) => {
|
.end((err, res) => {
|
||||||
// if (err) {
|
if (err) {
|
||||||
// return done(err);
|
return done(err);
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// done();
|
done();
|
||||||
// });
|
});
|
||||||
// });
|
});
|
||||||
//
|
|
||||||
// it('should return 403 deleting with an invalid token', (done) => {
|
it('should return 403 deleting with an invalid token', (done) => {
|
||||||
// request(app)
|
request(app)
|
||||||
// .delete('/users/me/token')
|
.delete('/users/me/token')
|
||||||
// .set('x-auth', users[0].tokens[0].token + '1')
|
.set('x-auth', users[0].tokens[0].token + '1')
|
||||||
// .send()
|
.send()
|
||||||
// .expect(403)
|
.expect(403)
|
||||||
// .end((err, res) => {
|
.end((err, res) => {
|
||||||
// if (err) {
|
if (err) {
|
||||||
// return done(err);
|
return done(err);
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// done();
|
done();
|
||||||
// });
|
});
|
||||||
// });
|
});
|
||||||
// });
|
});
|
||||||
|
|
||||||
|
|
||||||
describe('POST /todos', () => {
|
describe('POST /todos', () => {
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
var os = require("os");
|
var os = require("os");
|
||||||
|
|
||||||
|
// SETTINGS WebPush Configuration
|
||||||
|
const webpush = require('web-push');
|
||||||
|
|
||||||
|
const publicVapidKey = process.env.PUBLIC_VAPI_KEY;
|
||||||
|
const privateVapidKey = process.env.PRIVATE_VAPI_KEY;
|
||||||
|
webpush.setVapidDetails('mailto:' + process.env.EMAIL_FROM, publicVapidKey, privateVapidKey);
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
getHostname: function () {
|
getHostname: function () {
|
||||||
return os.hostname()
|
return os.hostname()
|
||||||
@@ -28,6 +35,14 @@ module.exports = {
|
|||||||
|
|
||||||
allfieldTodoWithId: function () {
|
allfieldTodoWithId: function () {
|
||||||
return ['_id', ...this.allfieldTodo()]
|
return ['_id', ...this.allfieldTodo()]
|
||||||
|
},
|
||||||
|
|
||||||
|
sendBackNotif: function (subscription, payload) {
|
||||||
|
|
||||||
|
// console.log('sendBackNotif:', subscription, payload);
|
||||||
|
// Pass object into sendNotification
|
||||||
|
webpush.sendNotification(subscription, JSON.stringify(payload)).catch(err => console.error(err));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user