- fix: Date problems... (it was a bad "copy" function, the object date was not valid...)

- fix: error fetch on loading... (offline appeared)
This commit is contained in:
Paolo Arena
2019-02-11 02:59:05 +01:00
parent 636ee92786
commit d24b232a2d
7 changed files with 437 additions and 370 deletions

View File

@@ -9,22 +9,22 @@ var authenticate = (req, res, next) => {
const useragent = req.get('User-Agent'); const useragent = req.get('User-Agent');
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, 'auth ' + useragent).then((user) => {
if (!user) { if (!user) {
tools.mylogshow("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);
// res.status().send(); // res.status().send();
} }
tools.mylog('userid', user._id); // tools.mylog('userid', user._id);
req.user = user; req.user = user;
req.token = token; req.token = token;
next(); next();
}).catch((e) => { }).catch((e) => {
tools.mylogshow("ERR =", e); tools.mylog("ERR =", e);
res.status(server_constants.RIS_CODE_HTTP_INVALID_TOKEN).send(); res.status(server_constants.RIS_CODE_HTTP_INVALID_TOKEN).send();
}); });
}; };

View File

@@ -44,7 +44,7 @@ var TodoSchema = new mongoose.Schema({
type: Date type: Date
}, },
expiring_at: { expiring_at: {
type: Date type: Date,
}, },
enableExpiring: { enableExpiring: {
type: Boolean, type: Boolean,
@@ -83,10 +83,15 @@ TodoSchema.statics.findAllByUserId = function (userId) {
}; };
TodoSchema.pre('save', function (next) { TodoSchema.pre('save', function (next) {
// var todo = this;
// console.log('todo.expiring_at', todo.expiring_at);
next(); next();
}); });
var Todo = mongoose.model('Todos', TodoSchema); var Todo = mongoose.model('Todos', TodoSchema);
module.exports = { Todo }; module.exports = { Todo };

View File

@@ -64,7 +64,10 @@ var UserSchema = new mongoose.Schema({
token: { token: {
type: String, type: String,
required: true required: true
} },
date_login: {
type: Date
},
}], }],
date_tokenforgot: { date_tokenforgot: {
type: Date type: Date
@@ -91,10 +94,11 @@ UserSchema.methods.generateAuthToken = function (req) {
var access = 'auth ' + useragent; var access = 'auth ' + useragent;
var token = jwt.sign({ _id: user._id.toHexString(), access }, process.env.SIGNCODE).toString(); var token = jwt.sign({ _id: user._id.toHexString(), access }, process.env.SIGNCODE).toString();
var date_login = new Date();
// CANCELLA IL PRECEDENTE ! // CANCELLA IL PRECEDENTE !
user.tokens = user.tokens.filter(function(tok) { return tok.access !== access; }); user.tokens = user.tokens.filter(function(tok) { return tok.access !== access; });
user.tokens.push({ access, token }); user.tokens.push({ access, token, date_login });
return user.save() return user.save()
.then(() => { .then(() => {
@@ -119,7 +123,7 @@ UserSchema.statics.findByToken = function (token, typeaccess) {
return User.findOne({ return User.findOne({
'_id': decoded._id, '_id': decoded._id,
'tokens.token': token, 'tokens.token': token,
'tokens.access': typeaccess 'tokens.access': typeaccess,
}); });
}; };

View File

@@ -22,11 +22,16 @@ const { ObjectID } = require('mongodb');
router.post('/', authenticate, (req, res) => { router.post('/', authenticate, (req, res) => {
var body = _.pick(req.body, tools.allfieldTodoWithId()); var body = _.pick(req.body, tools.allfieldTodoWithId());
tools.mylogshow('INPUT', body);
var todo = new Todo(body); var todo = new Todo(body);
// tools.mylogshow('ID :', todo._id) // todo.expiring_at = new Date(todo.expiring_at);
// tools.mylogshow('userid', todo.userId, req.user._id) tools.mylogshow('TODO', todo);
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 });
@@ -38,7 +43,7 @@ router.post('/', authenticate, (req, res) => {
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
} }
tools.mylog('POST :', todo.descr, todo._id); tools.mylog('TODO POST :', todo.descr, todo._id);
todo.modified = false; todo.modified = false;
if (!todo.descr) { if (!todo.descr) {
@@ -55,7 +60,7 @@ router.post('/', authenticate, (req, res) => {
res.send({record}); res.send({record});
}) })
}).catch((e) => { }).catch((e) => {
console.log(e.message); console.log('ERRORE in TODO POST', e.message);
res.status(400).send(e); res.status(400).send(e);
}); });
}); });
@@ -102,6 +107,7 @@ function sendNotificationToUser(userId, title, content, openUrl, tag) {
TTL: payload.ttl, TTL: payload.ttl,
headers: {} headers: {}
}; };
webpush.sendNotification( webpush.sendNotification(
pushSubscription, pushSubscription,
pushPayload, pushPayload,
@@ -119,6 +125,9 @@ function sendNotificationToUser(userId, title, content, openUrl, tag) {
data: err data: err
}); });
}); });
}).catch(error => {
console.log('ERROR: sendNotificationToUser', error
)
}); });
}); });
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => { // q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
@@ -136,6 +145,8 @@ router.patch('/:id', authenticate, (req, res) => {
var id = req.params.id; var id = req.params.id;
var body = _.pick(req.body, tools.allfieldTodo()); var body = _.pick(req.body, tools.allfieldTodo());
tools.mylogshow('PATCH TODO: ', id)
if (!ObjectID.isValid(id)) { if (!ObjectID.isValid(id)) {
tools.mylog('ERROR: id not VALID', id); tools.mylog('ERROR: id not VALID', id);
return res.status(404).send(); return res.status(404).send();
@@ -143,6 +154,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)
if (!todo) { if (!todo) {
return res.status(404).send(); return res.status(404).send();
} }
@@ -180,8 +192,10 @@ 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)
res.send({ todos }); tools.mylog('todos', todos);
res.send({ todos: todos });
}).catch((e) => { }).catch((e) => {
console.log(e); console.log(e);
res.status(400).send(e); res.status(400).send(e);
@@ -209,4 +223,5 @@ router.delete('/:id', authenticate, (req, res) => {
}); });
}); });
module.exports = router; module.exports = router;

View File

@@ -24,6 +24,11 @@ const userTwoId = new ObjectID();
let mypwdchiaro = 'mypassword@1A'; let mypwdchiaro = 'mypassword@1A';
let mypwdcrypted = '$2b$12$mteST.isuWO0SNsfeZ0aCe.Dz3qwPh5SU8t9rc5SaPTkb3j0ywGv6' let mypwdcrypted = '$2b$12$mteST.isuWO0SNsfeZ0aCe.Dz3qwPh5SU8t9rc5SaPTkb3j0ywGv6'
const date_login = new Date();
// 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 users = [{ const users = [{
_id: userOneId, _id: userOneId,
keyappid: process.env.KEY_APP_ID, keyappid: process.env.KEY_APP_ID,
@@ -33,8 +38,9 @@ const users = [{
username: 'paoloar77B', username: 'paoloar77B',
password: mypwdcrypted, password: mypwdcrypted,
tokens: [{ tokens: [{
access: 'auth', access: 'auth ' + useragent,
token: jwt.sign({ _id: userOneId, access: 'auth' }, process.env.SIGNCODE).toString() token: jwt.sign({ _id: userOneId, access: 'auth ' + useragent }, process.env.SIGNCODE).toString(),
date_login
}] }]
}, },
{ {
@@ -46,8 +52,9 @@ const users = [{
password: mypwdcrypted, password: mypwdcrypted,
username: 'paoloar77C', username: 'paoloar77C',
tokens: [{ tokens: [{
access: 'auth', access: 'auth ' + useragent,
token: jwt.sign({ _id: userTwoId, access: 'auth' }, process.env.SIGNCODE).toString() token: jwt.sign({ _id: userTwoId, access: 'auth ' + useragent }, process.env.SIGNCODE).toString(),
date_login
}] }]
}, { }, {
keyappid: process.env.KEY_APP_ID, // RECORD CHE VERRA' UTILIZZATO PER UNA NUOVA REGISTRAZIONE keyappid: process.env.KEY_APP_ID, // RECORD CHE VERRA' UTILIZZATO PER UNA NUOVA REGISTRAZIONE
@@ -67,15 +74,15 @@ const todos = [{
_id: new ObjectID(), _id: new ObjectID(),
category: "personal", category: "personal",
completed: false, completed: false,
completed_at: 0, completed_at: new Date(),
created_at: 6, created_at: new Date(),
descr: "Primo Task Esempio", descr: "Primo Task Esempio",
enableExpiring: false, enableExpiring: false,
expiring_at: 16, expiring_at: new Date(),
id_next: "10000000", id_next: "10000000",
id_prev: "0", id_prev: "0",
modified: false, modified: false,
modify_at: 6, modify_at: new Date(),
pos: 1, pos: 1,
priority: 1, priority: 1,
progress: 0, progress: 0,
@@ -84,15 +91,15 @@ const todos = [{
_id: new ObjectID(), _id: new ObjectID(),
category: "personal", category: "personal",
completed: false, completed: false,
completed_at: 0, completed_at: new Date(),
created_at: 6, created_at: new Date(),
descr: "Secondo Task Esempio", descr: "Secondo Task Esempio",
enableExpiring: false, enableExpiring: false,
expiring_at: 16, expiring_at: new Date(),
id_next: "10000000", id_next: "10000000",
id_prev: "1", id_prev: "1",
modified: false, modified: false,
modify_at: 6, modify_at: new Date(),
pos: 2, pos: 2,
priority: 1, priority: 1,
progress: 0, progress: 0,
@@ -101,15 +108,15 @@ const todos = [{
_id: new ObjectID(), _id: new ObjectID(),
category: "personal", category: "personal",
completed: false, completed: false,
completed_at: 0, completed_at: new Date(),
created_at: 6, created_at: new Date(),
descr: "Terzo Task Esempio", descr: "Terzo Task Esempio",
enableExpiring: false, enableExpiring: false,
expiring_at: 16, expiring_at: new Date(),
id_next: "10000000", id_next: "10000000",
id_prev: "1", id_prev: "1",
modified: false, modified: false,
modify_at: 6, modify_at: new Date(),
pos: 3, pos: 3,
priority: 1, priority: 1,
progress: 0, progress: 0,
@@ -118,15 +125,15 @@ const todos = [{
_id: new ObjectID(), _id: new ObjectID(),
category: "personal", category: "personal",
completed: false, completed: false,
completed_at: 0, completed_at: new Date(),
created_at: 6, created_at: new Date(),
descr: "Nuovo Quarto Task Esempio da Inserire", descr: "Nuovo Quarto Task Esempio da Inserire",
enableExpiring: false, enableExpiring: false,
expiring_at: 16, expiring_at: new Date(),
id_next: "10000000", id_next: "10000000",
id_prev: "2", id_prev: "2",
modified: false, modified: false,
modify_at: 6, modify_at: new Date(),
pos: 4, pos: 4,
priority: 1, priority: 1,
progress: 0, progress: 0,
@@ -167,4 +174,4 @@ const populateUsers = (done) => {
}; };
module.exports = { todos, populateTodos, users, populateUsers, userjson, mypwdcrypted, mypwdchiaro }; module.exports = { todos, populateTodos, users, populateUsers, userjson, mypwdcrypted, mypwdchiaro, date_login };

View File

@@ -5,7 +5,7 @@ const { ObjectID } = require('mongodb');
const { app } = require('./../server'); const { app } = require('./../server');
const { Todo } = require('./../models/todo'); const { Todo } = require('./../models/todo');
const { User } = require('./../models/user'); const { User } = require('./../models/user');
const { todos, populateTodos, users, populateUsers, userjson, mypwdcrypted, mypwdchiaro } = require('./seed/seed'); const { todos, populateTodos, users, populateUsers, userjson, mypwdcrypted, mypwdchiaro, date_login } = require('./seed/seed');
const tools = require('../tools/general'); const tools = require('../tools/general');
@@ -33,7 +33,36 @@ const IndexTodoToCreate = 3;
// console.log('userjson', userjson); // console.log('userjson', userjson);
describe('POST /users', () => { // 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 testsingolo = true;
if (testsingolo) {
it('should create a new Todos', (done) => {
request(app)
.post('/todos')
.set('x-auth', users[0].tokens[0].token)
.send(todos[IndexTodoToCreate])
.expect(200)
.end((err, res) => {
if (err) {
return done(err);
}
Todo.find({ descr: todos[IndexTodoToCreate].descr }).then((arr_todos) => {
expect(arr_todos.length).toBe(1);
expect(arr_todos[0].descr).toBe(todos[IndexTodoToCreate].descr);
expect(String(arr_todos[0]._id)).toBe(String(todos[IndexTodoToCreate]._id));
expect(String(arr_todos[0].userId)).toBe(String(users[0]._id));
done();
}).catch((e) => done(e));
});
});
} else {
describe('POST /users', () => {
it('should create a user', (done) => { it('should create a user', (done) => {
request(app) request(app)
.post('/users') .post('/users')
@@ -76,9 +105,9 @@ describe('POST /users', () => {
.expect(400) .expect(400)
.end(done); .end(done);
}); });
}); });
describe('GET /users/myusername', () => { describe('GET /users/myusername', () => {
it('should return 200 if myusername exist', (done) => { it('should return 200 if myusername exist', (done) => {
request(app) request(app)
.get('/users/' + users[0].username) .get('/users/' + users[0].username)
@@ -93,13 +122,13 @@ describe('GET /users/myusername', () => {
.expect(404) .expect(404)
.end(done); .end(done);
}); });
}); });
describe('POST /users/login', () => { describe('POST /users/login', () => {
it('should login user and return auth token', (done) => { it('should login user and return auth token', (done) => {
request(app) request(app)
.post('/users/login') .post('/users/login')
.set('x-auth', users[0].tokens[0].token) // .set('x-auth', users[0].tokens[0].token)
.send({ .send({
username: users[0].username, username: users[0].username,
password: mypwdchiaro, password: mypwdchiaro,
@@ -118,8 +147,9 @@ describe('POST /users/login', () => {
User.findById(users[0]._id).then((user) => { User.findById(users[0]._id).then((user) => {
expect(user.tokens[0]).toInclude({ expect(user.tokens[0]).toInclude({
access: 'auth', access: 'auth ' + useragent,
token: res.headers['x-auth'] // token: res.headers['x-auth'],
date_login: date_login
}); });
done(); done();
}).catch((e) => done(e)); }).catch((e) => done(e));
@@ -149,45 +179,45 @@ describe('POST /users/login', () => {
}); });
}); });
});
describe('DELETE /users/me/token', () => {
it('should logout user deleting auth token', (done) => {
request(app)
.delete('/users/me/token')
.set('x-auth', users[0].tokens[0].token)
.send()
.expect(200)
.expect((res) => {
expect(res.headers['x-auth']).toNotExist();
})
.end((err, res) => {
if (err) {
return done(err);
}
done();
});
}); });
it('should return 403 deleting with an invalid token', (done) => { // describe('DELETE /users/me/token', () => {
request(app) // it('should logout user deleting auth token', (done) => {
.delete('/users/me/token') // request(app)
.set('x-auth', users[0].tokens[0].token + '1') // .delete('/users/me/token')
.send() // .set('x-auth', users[0].tokens[0].token)
.expect(403) // .send()
.end((err, res) => { // .expect(200)
if (err) { // .expect((res) => {
return done(err); // expect(res.headers['x-auth']).toNotExist();
} // })
// .end((err, res) => {
done(); // if (err) {
}); // return done(err);
}); // }
}); //
// done();
// });
// });
//
// it('should return 403 deleting with an invalid token', (done) => {
// request(app)
// .delete('/users/me/token')
// .set('x-auth', users[0].tokens[0].token + '1')
// .send()
// .expect(403)
// .end((err, res) => {
// if (err) {
// return done(err);
// }
//
// done();
// });
// });
// });
describe('POST /todos', () => { describe('POST /todos', () => {
it('should create a new Todos', (done) => { it('should create a new Todos', (done) => {
request(app) request(app)
@@ -237,9 +267,9 @@ describe('POST /todos', () => {
}).catch((e) => done(e)); }).catch((e) => done(e));
}); });
}); });
}); });
describe('GET /todos', () => { describe('GET /todos', () => {
it('should get all todos', (done) => { it('should get all todos', (done) => {
request(app) request(app)
.get(`/todos/${users[0]._id }`) .get(`/todos/${users[0]._id }`)
@@ -250,10 +280,10 @@ describe('GET /todos', () => {
}) })
.end(done); .end(done);
}); });
}); });
describe('GET /todos/:id', () => { describe('GET /todos/:id', () => {
it('should return todos of the User', (done) => { it('should return todos of the User', (done) => {
request(app) request(app)
.get(`/todos/${todos[0].userId}`) .get(`/todos/${todos[0].userId}`)
@@ -297,9 +327,9 @@ describe('GET /todos/:id', () => {
.expect(404) .expect(404)
.end(done); .end(done);
}); });
}); });
describe('DELETE /todos/:id', () => { describe('DELETE /todos/:id', () => {
it('should remove a todo', (done) => { it('should remove a todo', (done) => {
var hexId = todos[0]._id.toHexString(); var hexId = todos[0]._id.toHexString();
@@ -339,9 +369,9 @@ describe('DELETE /todos/:id', () => {
.expect(404) .expect(404)
.end(done); .end(done);
}); });
}); });
describe('PATCH /todos/:id', () => { describe('PATCH /todos/:id', () => {
it('should update the todo', (done) => { it('should update the todo', (done) => {
var hexId = todos[0]._id.toHexString(); var hexId = todos[0]._id.toHexString();
var descr = 'This should be the new text'; var descr = 'This should be the new text';
@@ -396,7 +426,9 @@ describe('PATCH /todos/:id', () => {
// }) // })
// .end(done); // .end(done);
// }); // });
}); });
}
/* /*

View File

@@ -13,6 +13,10 @@ module.exports = {
console.log(args) console.log(args)
}, },
mylogoff: function (...args) {
// doing nothing
},
mylogshow: function (...args) { mylogshow: function (...args) {
console.log(args) console.log(args)
}, },