@websy/websy-designs 1.12.15 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -131,8 +131,7 @@ class AuthHelper {
131
131
  res.redirect('/login')
132
132
  }
133
133
  }
134
- checkPermissions (req, res, next) {
135
- // console.log('hello')
134
+ checkPermissions (req, res, next) {
136
135
  if (process.env.USE_PERMISSIONS === 'true' || process.env.USE_PERMISSIONS === true) {
137
136
  const permissions = {
138
137
  entities: {
@@ -4,49 +4,6 @@ const report = require('./puppeteer-report/index')
4
4
  const fs = require('fs')
5
5
  const utils = require('../../utils')
6
6
  const http = require('http')
7
- let lastHTML = ''
8
- let testHTML = `
9
- <!DOCTYPE html>
10
- <html lang="en">
11
- <head>
12
- <meta charset="UTF-8">
13
- <meta name="viewport" content="width=device-width, initial-scale=1">
14
- <link rel="stylesheet" href="/external/@websy/websy-designs/dist/websy-designs.min.css">
15
- <link rel="stylesheet" href="/styles/pdf.min.css">
16
- <style>
17
- html {
18
- -webkit-print-color-adjust: exact;
19
- width: unset;
20
- background-color: white;
21
- }
22
- body {
23
- width: unset;
24
- background-color: white;
25
- }
26
- #header {
27
- margin: 0 15px;
28
- max-height: unset;
29
- }
30
- #footer {
31
- margin: 0 15px;
32
- }
33
- </style>
34
- </head>
35
-
36
- <body>
37
- <div id="app">
38
- <div id="header">
39
- Header
40
- </div>
41
- ${(new Array(300).fill({}).map((d, i) => '<p>val ' + i + '</p>')).join('')}
42
- <div id="footer">
43
- Footer
44
- </div>
45
- </div>
46
- </body>
47
-
48
- </html>
49
- `
50
7
 
51
8
  let convertHTMLToPDF = (html, name, callback, options_in = null, displayHeaderFooter) => {
52
9
  const pOptions = {
@@ -198,22 +155,10 @@ ${
198
155
  </div>
199
156
  </body>
200
157
  </html>
201
- `
202
- lastHTML = html
158
+ `
203
159
  convertHTMLToPDF(html, data.name || utils.createIdentity(), (err, pdf) => {
204
160
  console.log('info', `HTML converted to PDF`)
205
- // setTimeout(() => {
206
- // try {
207
- // // fs.unlinkSync(`${process.env.APP_ROOT}/pdf/${pdfId}.pdf`)
208
- // }
209
- // catch (error) {
210
- // console.log('Could not remove temp PDF')
211
- // }
212
- // }, 120000)
213
161
  callbackFn(err, pdf)
214
162
  }, data.options, (header !== '' || footer !== ''))
215
- },
216
- getLastHTML: () => {
217
- return lastHTML
218
- }
163
+ }
219
164
  }
@@ -86,7 +86,7 @@ class PGHelper {
86
86
  ]
87
87
  }
88
88
  init (options) {
89
- this.options = Object.assign({}, this.options, options)
89
+ this.options = Object.assign({}, this.options, options)
90
90
  return new Promise((resolve, reject) => {
91
91
  this.pool.connect().then(client => {
92
92
  this.client = client
@@ -101,13 +101,23 @@ class PGHelper {
101
101
  }, err => reject(err))
102
102
  })
103
103
  }
104
- buildDelete (entity, where) {
105
- return `
106
- DELETE FROM ${entity}
107
- WHERE ${this.buildWhere(where)}
108
- `
104
+ buildDelete (entity, whereQuery) {
105
+ if (!this.options.entityConfig[entity]) {
106
+ return { sql: 'SELECT 1=1', values: [] }
107
+ }
108
+ const { where, values } = this.buildWhere(whereQuery)
109
+ return {
110
+ sql: `
111
+ DELETE FROM ${entity}
112
+ WHERE ${where}
113
+ `,
114
+ values
115
+ }
109
116
  }
110
117
  buildInsert (entity, data, user) {
118
+ if (!this.options.entityConfig[entity]) {
119
+ return { sql: 'SELECT 1=1', values: [] }
120
+ }
111
121
  delete data[(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id']
112
122
  // data.create_user = user
113
123
  if (process.env.CREATE_USER_FIELD && process.env.USERID_FIELD && user) {
@@ -121,23 +131,26 @@ class PGHelper {
121
131
  INSERT INTO ${entity} (${Object.keys(data).join(',')})
122
132
  VALUES (
123
133
  `
124
- sql += Object.values(data).map(d => {
134
+ const placeholders = []
135
+ const values = []
136
+ Object.values(data).forEach(d => {
125
137
  if (d === null) {
126
- return d
138
+ // return d
127
139
  }
128
140
  else {
129
141
  if (typeof d === 'string') {
130
142
  d = d.replace(/'/g, `''`)
131
143
  }
132
- return `'${d}'`
133
- // (d === null ? `${d}` : `'${d.replace(/'/)}'`)
144
+ values.push(d)
145
+ placeholders.push(`$${values.length}`)
134
146
  }
135
- }).join(',')
147
+ })
136
148
  sql += `
149
+ ${placeholders.join(',')}
137
150
  )
138
151
  RETURNING ${(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id'}
139
152
  `
140
- return sql
153
+ return { sql, values }
141
154
  }
142
155
  buildOrderBy (query) {
143
156
  return `
@@ -145,6 +158,9 @@ class PGHelper {
145
158
  `
146
159
  }
147
160
  buildSelect (entity, query, columns, lang) {
161
+ if (!this.options.entityConfig[entity]) {
162
+ return { sql: 'SELECT 1=1', values: [] }
163
+ }
148
164
  let sql = `
149
165
  SELECT ${columns || '*'}
150
166
  FROM ${entity}
@@ -160,8 +176,9 @@ class PGHelper {
160
176
  ON ${entity}.${(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id'} = t2.entity_id
161
177
  `
162
178
  }
179
+ const { where, values } = this.buildWhere(query.where, entity)
163
180
  sql += `
164
- WHERE ${this.buildWhere(query.where, entity)}
181
+ WHERE ${where}
165
182
  ${this.buildOrderBy(query)}
166
183
  `
167
184
  if (query.limit) {
@@ -169,10 +186,13 @@ class PGHelper {
169
186
  }
170
187
  if (query.offset) {
171
188
  sql += ` OFFSET ${query.offset}`
172
- }
173
- return sql
189
+ }
190
+ return { sql, values }
174
191
  }
175
192
  buildSelectWithId (entity, id, query, columns, lang) {
193
+ if (!this.options.entityConfig[entity]) {
194
+ return { sql: 'SELECT 1=1', values: [] }
195
+ }
176
196
  let sql = `
177
197
  SELECT ${columns || '*'}
178
198
  FROM ${entity}
@@ -187,64 +207,94 @@ class PGHelper {
187
207
  ) t2
188
208
  ON ${entity}.${(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id'} = t2.entity_id
189
209
  `
190
- }
210
+ }
211
+ const { where, values } = this.buildWhereWithId(entity, id)
191
212
  sql += `
192
- WHERE ${this.buildWhereWithId(entity, id)}
213
+ WHERE ${where}
193
214
  ${this.buildOrderBy(query)}
194
215
  `
195
- return sql
216
+ return { sql, values }
196
217
  }
197
- buildUpdate (entity, where, data, user) {
198
- let updates = []
199
- for (let key in data) {
200
- if (this.updateIgnores.indexOf(key) === -1) {
201
- if (typeof data[key] === 'string') {
202
- data[key] = data[key].replace(/''/gm, `'`).replace(/'/gm, `''`).replace(/\\\\/gm, '\\')
203
- }
204
- updates.push(`${key} = ${(data[key] === null ? data[key] : `'${data[key]}'`)}`)
205
- }
206
- }
207
- if (process.env.CREATE_USER_FIELD && process.env.USERID_FIELD && user) {
208
- let userId = user[process.env.USERID_FIELD || 'id']
209
- updates.push(`${process.env.EDIT_USER_FIELD} = '${userId}'`)
210
- }
211
- if (process.env.EDIT_DATE_FIELD) {
212
- updates.push(`${process.env.EDIT_DATE_FIELD} = '${(new Date()).toISOString()}'`)
213
- }
214
- return `
215
- UPDATE ${entity}
216
- SET ${updates.join(',')}
217
- WHERE ${this.buildWhere(where)}
218
- `
218
+ buildUpdate (entity, whereQuery, data, user) {
219
+ // disabling bulk updates for now
220
+ return { sql: `SELECT 'Cannot perform bulk update' as result`, values: [] }
221
+ // if (!this.options.entityConfig[entity]) {
222
+ // return { sql: 'SELECT 1=1', values: [] }
223
+ // }
224
+ // if (!whereQuery || whereQuery === '') {
225
+ // }
226
+ // let updates = []
227
+ // let updateValues = []
228
+ // for (let key in data) {
229
+ // if (this.updateIgnores.indexOf(key) === -1) {
230
+ // if (typeof data[key] === 'string') {
231
+ // data[key] = data[key].replace(/''/gm, `'`).replace(/'/gm, `''`).replace(/\\\\/gm, '\\')
232
+ // }
233
+ // updateValues.push((data[key] === null ? data[key] : `'${data[key]}'`))
234
+ // updates.push(`${key} = $${updateValues.length}`)
235
+ // }
236
+ // }
237
+ // if (process.env.CREATE_USER_FIELD && process.env.USERID_FIELD && user) {
238
+ // let userId = user[process.env.USERID_FIELD || 'id']
239
+ // updateValues.push(userId)
240
+ // updates.push(`${process.env.EDIT_USER_FIELD} = $${updateValues.length}`)
241
+ // }
242
+ // if (process.env.EDIT_DATE_FIELD) {
243
+ // updateValues.push((new Date()).toISOString())
244
+ // updates.push(`${process.env.EDIT_DATE_FIELD} = $${updateValues.length}`)
245
+ // }
246
+ // const { where, values } = this.buildWhere(whereQuery, entity, updateValues.length)
247
+ // return {
248
+ // sql: `
249
+ // UPDATE ${entity}
250
+ // SET ${updates.join(',')}
251
+ // WHERE ${where}
252
+ // `,
253
+ // values: updateValues.concat(values)
254
+ // }
219
255
  }
220
256
  buildUpdateWithId (entity, id, data, user) {
257
+ if (!this.options.entityConfig[entity]) {
258
+ return { sql: 'SELECT 1=1', values: [] }
259
+ }
221
260
  let updates = []
261
+ let updateValues = []
222
262
  for (let key in data) {
223
263
  if (this.updateIgnores.indexOf(key) === -1) {
224
264
  if (typeof data[key] === 'string') {
225
265
  data[key] = data[key].replace(/''/gm, `'`).replace(/'/gm, `''`).replace(/\\\\/gm, '\\')
226
266
  }
227
- updates.push(`${key} = ${(data[key] === null ? data[key] : `'${data[key]}'`)}`)
267
+ updateValues.push((data[key] === null ? data[key] : data[key]))
268
+ updates.push(`${key} = $${updateValues.length}`)
228
269
  }
229
270
  }
230
271
  if (process.env.CREATE_USER_FIELD && process.env.USERID_FIELD && user) {
231
272
  let userId = user[process.env.USERID_FIELD || 'id']
232
- updates.push(`${process.env.EDIT_USER_FIELD} = '${userId}'`)
273
+ updateValues.push(userId)
274
+ updates.push(`${process.env.EDIT_USER_FIELD} = $${updateValues.length}`)
233
275
  }
234
276
  if (process.env.EDIT_DATE_FIELD) {
235
- updates.push(`${process.env.EDIT_DATE_FIELD} = '${(new Date()).toISOString()}'`)
277
+ updateValues.push((new Date()).toISOString())
278
+ updates.push(`${process.env.EDIT_DATE_FIELD} = $${updateValues.length}`)
279
+ }
280
+ const { where, values } = this.buildWhereWithId(entity, id, updateValues.length)
281
+ return {
282
+ sql: `
283
+ UPDATE ${entity}
284
+ SET ${updates.join(',')}
285
+ WHERE ${where}
286
+ `,
287
+ values: updateValues.concat(values)
236
288
  }
237
- return `
238
- UPDATE ${entity}
239
- SET ${updates.join(',')}
240
- WHERE ${this.buildWhereWithId(entity, id)}
241
- `
242
289
  }
243
290
  buildUpsert (entity, data, user) {
244
- // delete data[(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id']
245
- // data.create_user = user
246
- let sql = ``
291
+ if (!this.options.entityConfig[entity]) {
292
+ return { sql: 'SELECT 1=1', values: [] }
293
+ }
294
+ const queries = []
247
295
  data.forEach(row => {
296
+ let sql = ``
297
+ let allValues = []
248
298
  if (process.env.CREATE_USER_FIELD && process.env.USERID_FIELD && user) {
249
299
  row[process.env.CREATE_USER_FIELD] = user[process.env.USERID_FIELD || 'id']
250
300
  row[process.env.EDIT_USER_FIELD] = user[process.env.USERID_FIELD || 'id']
@@ -261,47 +311,45 @@ class PGHelper {
261
311
  if (typeof row[key] === 'string') {
262
312
  row[key] = row[key].replace(/''/gm, `'`).replace(/'/gm, `''`).replace(/\\\\/gm, '\\')
263
313
  }
264
- updates.push(`${key} = ${(row[key] === null ? row[key] : `'${row[key]}'`)}`)
314
+ allValues.push((row[key] === null ? row[key] : `'${row[key]}'`))
315
+ updates.push(`${key} = $${allValues.length}`)
265
316
  }
266
- }
267
- console.log('updates 1')
268
- console.log(updates)
269
- sql += `
317
+ }
318
+ allValues.push(id)
319
+ sql = `
270
320
  UPDATE ${entity}
271
321
  SET ${updates.join(',')}
272
- WHERE ${this.buildWhereWithId(entity, id)};
322
+ WHERE ${(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id'} = $${allValues.length};
273
323
  `
274
324
  }
275
325
  else {
276
326
  delete row[(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id']
277
- let sqlValues = Object.values(row).map(d => {
327
+ const placeholders = []
328
+ Object.values(row).forEach(d => {
278
329
  if (d === null) {
279
- return d
330
+ // return d
280
331
  }
281
332
  else {
282
333
  if (typeof d === 'string') {
283
334
  d = d.replace(/'/g, `''`)
284
335
  }
285
- return `'${d}'`
286
- // (d === null ? `${d}` : `'${d.replace(/'/)}'`)
336
+ allValues.push(d)
337
+ placeholders.push(`$${allValues.length}`)
287
338
  }
288
- }).join(',')
289
- console.log('updates 2')
290
- console.log(sqlValues)
291
- sql += `
339
+ })
340
+ sql = `
292
341
  INSERT INTO ${entity} (${Object.keys(row).join(',')})
293
- VALUES (${sqlValues})
342
+ VALUES (${placeholders.join(',')})
294
343
  RETURNING ${(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id'};
295
344
  `
296
345
  }
346
+ queries.push({ sql, values: allValues })
297
347
  })
298
- return sql
348
+ return queries
299
349
  }
300
- buildWhere (input, entity) {
301
- // console.log('building where', input)
302
-
350
+ buildWhere (input, entity, startCount = 0) {
303
351
  if (typeof input === 'undefined' || input.trim() === '') {
304
- return '1=1'
352
+ return { where: '1=1', values: [] }
305
353
  }
306
354
  else {
307
355
  try {
@@ -309,55 +357,58 @@ class PGHelper {
309
357
  }
310
358
  catch (error) {
311
359
  // console.log(error)
312
- }
313
- // console.log('where input', input)
314
- // console.log('splitter is', this.options.fieldValueSeparator)
315
- // console.log('splitter is', this.options.whereValueSeparator)
360
+ }
361
+ let values = []
316
362
  let list = input.split(this.options.whereValueSeparator).map(d => {
317
- let parts = d.split(this.options.fieldValueSeparator)
318
- // console.log(parts)
363
+ let parts = d.split(this.options.fieldValueSeparator)
319
364
  if (parts.length === 2) {
320
365
  parts[1] = parts[1].replace(/%20/g, ' ')
321
366
  let partValues = parts[1]
322
367
  partValues = partValues.split('|')
323
368
  if (partValues.length === 1) {
324
369
  if (parts[1].indexOf('_gt') !== -1) {
325
- return `${entity ? entity + '.' : ''}${parts[0]} > '${parts[1].replace('_gt', '')}'`
370
+ values.push(parts[1].replace('_gt', ''))
371
+ return `${entity ? entity + '.' : ''}${parts[0]} > $${startCount + values.length}`
326
372
  }
327
373
  else if (parts[1].indexOf('_lt') !== -1) {
328
- return `${entity ? entity + '.' : ''}${parts[0]} < '${parts[1].replace('_lt', '')}'`
374
+ values.push(parts[1].replace('_lt', ''))
375
+ return `${entity ? entity + '.' : ''}${parts[0]} < $${startCount + values.length}`
329
376
  }
330
377
  else if (parts[1].indexOf('%') !== -1) {
331
- return `LOWER(${entity ? entity + '.' : ''}${parts[0]}) LIKE '${parts[1]}'`
378
+ values.push(parts[1])
379
+ return `LOWER(${entity ? entity + '.' : ''}${parts[0]}) LIKE $${startCount + values.length}`
332
380
  }
333
381
  else {
334
- return `${entity ? entity + '.' : ''}${parts[0]} = '${parts[1]}'`
382
+ values.push(parts[1])
383
+ return `${entity ? entity + '.' : ''}${parts[0]} = $${startCount + values.length}`
335
384
  }
336
385
  }
337
386
  else {
338
- return `${entity ? entity + '.' : ''}${parts[0]} IN ('${partValues.join('\',\'')}')`
387
+ const placeholders = partValues.map((p, i) => `$${i + startCount + values.length}`).join(', ')
388
+ values.push(...partValues)
389
+ return `${entity ? entity + '.' : ''}${parts[0]} IN (${placeholders})`
339
390
  }
340
391
  }
341
392
  else {
342
393
  parts = d.split('!')
343
394
  if (parts.length === 2) {
344
- return `${entity ? entity + '.' : ''}${parts[0]} <> '${parts[1]}'`
395
+ values.push(parts[1])
396
+ return `${entity ? entity + '.' : ''}${parts[0]} <> $${startCount + values.length}`
345
397
  }
346
398
  }
347
- })
348
- // console.log(list)
349
-
350
- return `
351
- ${list.length > 0 ? list.join(' AND ') : ''}
352
- `
399
+ })
400
+ return {
401
+ where: `${list.length > 0 ? list.join(' AND ') : ''}`,
402
+ values
403
+ }
353
404
  }
354
405
  }
355
- buildWhereWithId (entity, id) {
406
+ buildWhereWithId (entity, id, startCount = 0) {
356
407
  if (typeof id === 'undefined') {
357
- return '1=1'
408
+ return { where: '1=1', values: [] }
358
409
  }
359
410
  else {
360
- return `${(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id'} = ${id}`
411
+ return { where: `${(this.options.entityConfig[entity] && this.options.entityConfig[entity].idColumn) || 'id'} = $${startCount + 1}`, values: [id] }
361
412
  }
362
413
  }
363
414
  checkTables () {
@@ -442,24 +493,25 @@ class PGHelper {
442
493
  })
443
494
  })
444
495
  }
445
- execute (query) {
446
- console.log(query)
447
- return new Promise((resolve, reject) => {
448
- // console.log(query)
496
+ execute (query, values) {
497
+ return new Promise((resolve, reject) => {
498
+ const params = [query]
499
+ if (values && values.length > 0) {
500
+ params.push(values)
501
+ }
449
502
  if (query !== null) {
450
- this.client.query(query, (err, queryResponse) => {
503
+ this.client.query(...params).then(queryResponse => {
504
+ resolve({
505
+ rowCount: queryResponse.rowCount,
506
+ rows: queryResponse.rows
507
+ })
508
+ }, err => {
451
509
  if (err) {
452
510
  console.log('Error creating request')
453
511
  console.log(err)
454
512
  console.log(query)
455
513
  this.rollback(err, reject)
456
514
  }
457
- else {
458
- resolve({
459
- rowCount: queryResponse.rowCount,
460
- rows: queryResponse.rows
461
- })
462
- }
463
515
  })
464
516
  }
465
517
  else {
@@ -468,13 +520,24 @@ class PGHelper {
468
520
  }
469
521
  })
470
522
  }
523
+ executeUpsert (index, queries, callbackFn) {
524
+ if (!queries[index]) {
525
+ callbackFn()
526
+ }
527
+ else {
528
+ this.execute(queries[index].sql, queries[index].values).then(() => {
529
+ index++
530
+ this.executeUpsert(index, queries, callbackFn)
531
+ }, callbackFn)
532
+ }
533
+ }
471
534
  getBasket (req, basketCompare) {
472
535
  return new Promise((resolve, reject) => {
473
536
  if (req.session && req.session.user) {
474
537
  const sql = `
475
- SELECT * FROM ${basketCompare} WHERE userid = '${req.session.user.id}'
538
+ SELECT * FROM ${basketCompare} WHERE userid = $1
476
539
  `
477
- this.execute(sql).then(result => {
540
+ this.execute(sql, [req.session.user.id]).then(result => {
478
541
  if (result.rows.length > 0) {
479
542
  let basket = result.rows[0]
480
543
  try {
@@ -491,8 +554,7 @@ class PGHelper {
491
554
  try {
492
555
  basket.meta = JSON.parse(this.JSONSafeRead(basket.meta))
493
556
  }
494
- catch (error) {
495
- // console.log('data got saved incorrectly')
557
+ catch (error) {
496
558
  if (basket.meta) {
497
559
  try {
498
560
  basket.meta = JSON.parse(basket.meta)
@@ -526,9 +588,8 @@ class PGHelper {
526
588
  rollback (err, callbackFn) {
527
589
  console.log('Rolling Back')
528
590
  console.log(err)
529
- this.client.query('ROLLBACK', function (rollbackErr) {
530
- console.log(err)
531
- // done()
591
+ this.client.query('ROLLBACK').then(() => {
592
+ console.log(err)
532
593
  callbackFn(err)
533
594
  })
534
595
  }
@@ -1,18 +1,24 @@
1
1
  const express = require('express')
2
2
  const router = express.Router()
3
- // const PG = require('../helpers/dbHelper')
4
- // const dbHelper = new PG()
5
3
 
6
- function APIRoutes (dbHelper, authHelper) {
7
- router.delete('/:entity/:id', (req, res) => {
8
- const sql = `DELETE FROM ${req.params.entity} WHERE ${dbHelper.buildWhereWithId(req.params.entity, req.params.id)}`
9
- dbHelper.execute(sql).then(response => res.json(response), err => res.json(err))
4
+ function APIRoutes (dbHelper, authHelper) {
5
+ router.delete('/:entity/:id', authHelper.checkPermissions.bind(authHelper), (req, res) => {
6
+ const { where, values } = dbHelper.buildWhereWithId(req.params.entity, req.params.id)
7
+ let sql = `DELETE FROM ${req.params.entity} WHERE ${where}`
8
+ if (!dbHelper.options.entityConfig[req.params.entity]) {
9
+ sql = 'SELECT 1=1'
10
+ }
11
+ dbHelper.execute(sql, values).then(response => res.json(response), err => res.json(err))
10
12
  })
11
- router.delete('/:entity', (req, res) => {
12
- const sql = dbHelper.buildDelete(req.params.entity, req.query.where)
13
+ router.delete('/:entity', authHelper.checkPermissions.bind(authHelper), (req, res) => {
14
+ // if (!dbHelper.options.entityConfig[req.params.entity]) {
15
+ // return 'SELECT 1=1'
16
+ // }
17
+ // const { sql, values } = dbHelper.buildDelete(req.params.entity, req.query.where)
18
+ const sql = `SELECT 'Cannot perform bulk delete' as result`
13
19
  dbHelper.execute(sql).then(response => res.json(response), err => res.json(err))
14
20
  })
15
- router.get('/currentuser', (req, res) => {
21
+ router.get('/currentuser', authHelper.checkPermissions.bind(authHelper), (req, res) => {
16
22
  let user = {}
17
23
  if (req.session && req.session.user) {
18
24
  user = req.session.user
@@ -24,28 +30,28 @@ function APIRoutes (dbHelper, authHelper) {
24
30
  }
25
31
  res.json(user)
26
32
  })
27
- router.get('/:entity/:id', (req, res) => {
33
+ router.get('/:entity/:id', authHelper.checkPermissions.bind(authHelper), (req, res) => {
28
34
  let lang = process.env.DEFAULT_LANGUAGE
29
35
  if (req.session && req.session.language && req.query.notranslate !== 'true') {
30
36
  lang = req.session.language
31
37
  }
32
- const sql = dbHelper.buildSelectWithId(req.params.entity, req.params.id, req.query, req.query.columns, lang)
33
- dbHelper.execute(sql).then(response => {
38
+ const { sql, values } = dbHelper.buildSelectWithId(req.params.entity, req.params.id, req.query, req.query.columns, lang)
39
+ dbHelper.execute(sql, values).then(response => {
34
40
  res.json(translate(response))
35
41
  }, err => res.json(err))
36
42
  })
37
- router.get('/:entity', (req, res) => {
43
+ router.get('/:entity', authHelper.checkPermissions.bind(authHelper), (req, res) => {
38
44
  let lang = process.env.DEFAULT_LANGUAGE
39
45
  if (req.session && req.session.language && req.query.notranslate !== 'true') {
40
46
  lang = req.session.language
41
47
  }
42
- // console.log(`lang is ${lang}`)
43
- const sql = dbHelper.buildSelect(req.params.entity, req.query, req.query.columns, lang)
44
- dbHelper.execute(sql).then(response => {
45
- if (process.env.RETURN_COUNTS === true || process.env.RETURN_COUNTS === 'true') {
46
- let countWhere = ''
47
- const countSql = `SELECT COUNT(*) as total FROM ${req.params.entity} WHERE ${dbHelper.buildWhere(req.query.where, req.params.entity)}`
48
- dbHelper.execute(countSql).then(countResponse => {
48
+ const { sql, values } = dbHelper.buildSelect(req.params.entity, req.query, req.query.columns, lang)
49
+
50
+ dbHelper.execute(sql, values).then(response => {
51
+ if (process.env.RETURN_COUNTS === true || process.env.RETURN_COUNTS === 'true') {
52
+ const { where: countWhere, values: countValues } = dbHelper.buildWhere(req.query.where, req.params.entity)
53
+ const countSql = `SELECT COUNT(*) as total FROM ${req.params.entity} WHERE ${countWhere}`
54
+ dbHelper.execute(countSql, countValues).then(countResponse => {
49
55
  response.totalCount = countResponse.rows[0].total
50
56
  res.json(translate(response))
51
57
  })
@@ -55,47 +61,54 @@ function APIRoutes (dbHelper, authHelper) {
55
61
  }
56
62
  }, err => res.json(err))
57
63
  })
58
- router.post('/:entity/upsert', authHelper.checkPermissions, (req, res) => {
64
+ router.post('/:entity/upsert', authHelper.checkPermissions.bind(authHelper), (req, res) => {
59
65
  let user
60
66
  if (req.session && req.session.user) {
61
67
  user = req.session.user
62
68
  }
63
- const sql = dbHelper.buildUpsert(req.params.entity, req.body, user)
64
- console.log('upsert sql')
65
- console.log(sql)
66
- dbHelper.execute(sql).then(response => res.json(response), err => res.json(err))
69
+ if (req.body && req.body.data) {
70
+ const queries = dbHelper.buildUpsert(req.params.entity, req.body.data, user)
71
+ dbHelper.executeUpsert(0, queries, (err) => {
72
+ if (err) {
73
+ res.json(err)
74
+ }
75
+ else {
76
+ res.json(true)
77
+ }
78
+ })
79
+ }
80
+ else {
81
+ res.status(400)
82
+ res.json({ err: 'Malformed body. Missing data prop' })
83
+ }
67
84
  })
68
- router.post('/:entity', authHelper.checkPermissions, (req, res) => {
69
- // const sql = dbHelper.buildInsert(req.params.entity, req.body, req.session.passport.user.id)
70
- // console.log(req.body)
71
- // console.log(req.session)
85
+ router.post('/:entity', authHelper.checkPermissions.bind(authHelper), (req, res) => {
72
86
  let user
73
87
  if (req.session && req.session.user) {
74
88
  user = req.session.user
75
89
  }
76
- const sql = dbHelper.buildInsert(req.params.entity, req.body, user)
77
- // console.log(sql)
78
- dbHelper.execute(sql).then(response => res.json(response), err => {
90
+ const { sql, values } = dbHelper.buildInsert(req.params.entity, req.body, user)
91
+
92
+ dbHelper.execute(sql, values).then(response => res.json(response), err => {
79
93
  res.statusCode = 404
80
94
  res.json({err})
81
95
  })
82
- })
83
- // console.log('defining put endpoint for /:entity/:id')
84
- router.put('/:entity/:id', authHelper.checkPermissions, (req, res) => {
96
+ })
97
+ router.put('/:entity/:id', authHelper.checkPermissions.bind(authHelper), (req, res) => {
85
98
  let user
86
99
  if (req.session && req.session.user) {
87
100
  user = req.session.user
88
101
  }
89
- const sql = dbHelper.buildUpdateWithId(req.params.entity, req.params.id, req.body, user)
90
- dbHelper.execute(sql).then(response => res.json(response), err => res.json(err))
102
+ const { sql, values } = dbHelper.buildUpdateWithId(req.params.entity, req.params.id, req.body, user)
103
+ dbHelper.execute(sql, values).then(response => res.json(response), err => res.json(err))
91
104
  })
92
- router.put('/:entity', authHelper.checkPermissions, (req, res) => {
105
+ router.put('/:entity', authHelper.checkPermissions.bind(authHelper), (req, res) => {
93
106
  let user
94
107
  if (req.session && req.session.user) {
95
108
  user = req.session.user
96
109
  }
97
- const sql = dbHelper.buildUpdate(req.params.entity, req.query.where, req.body, user)
98
- dbHelper.execute(sql).then(response => res.json(response), err => res.json(err))
110
+ const { sql, values } = dbHelper.buildUpdate(req.params.entity, req.query.where, req.body, user)
111
+ dbHelper.execute(sql, values).then(response => res.json(response), err => res.json(err))
99
112
  })
100
113
  return router
101
114
  }
@@ -7,13 +7,11 @@ router.get('/', (req, res) => {
7
7
  // res.setHeader('Content-Disposition', 'attachment')
8
8
  // res.setHeader('filename', `${req.params.name || utils.createIdentity()}.pdf`)
9
9
  res.setHeader('Content-Disposition', `attachment;filename=${utils.createIdentity()}.pdf`)
10
- res.contentType('application/pdf')
11
- console.log(req.session.pdf)
10
+ res.contentType('application/pdf')
12
11
  res.send(req.session.pdf)
13
12
  })
14
13
 
15
- router.post('/', (req, res) => {
16
- console.log('creating pdf in wd')
14
+ router.post('/', (req, res) => {
17
15
  pdfHelper.createPDF(req.body, (err, pdf) => {
18
16
  if (err) {
19
17
  res.status(400)
@@ -21,6 +21,7 @@ module.exports = function (options) {
21
21
  }
22
22
  const app = express()
23
23
  app.set('trust proxy', 1)
24
+ app.set('case sensitive routing', true)
24
25
  process.env.wdRoot = __dirname
25
26
  let version = options.version || 'v1'
26
27
  process.env.WD_VERSION = version
@@ -30,15 +31,12 @@ module.exports = function (options) {
30
31
  app.use(bodyParser.raw({limit: options.maxBodySize || '5mb'}))
31
32
  const AuthHelper = require(`./helpers/${version}/authHelper`)
32
33
  const NoAuthHelper = require(`./helpers/${version}/noAuthHelper`)
33
- const allowCrossDomain = (req, res, next) => {
34
- // console.log(req.url);
35
- // const allowedOrigins = ['https://www.google.com', 'http://localhost:4000', 'https://localhost:4000', 'http://ec2-3-92-185-52.compute-1.amazonaws.com', 'https://ec2-3-92-185-52.compute-1.amazonaws.com']
34
+ const allowCrossDomain = (req, res, next) => {
36
35
  let allowedOrigins = ['*']
37
36
  if (process.env.ALLOWED_ORIGINS) {
38
37
  allowedOrigins = process.env.ALLOWED_ORIGINS.split(',')
39
38
  }
40
- const origin = req.headers.origin
41
- // console.log(allowedOrigins.indexOf(origin))
39
+ const origin = req.headers.origin
42
40
  if (allowedOrigins.indexOf(origin) !== -1 || allowedOrigins[0] === '*') {
43
41
  res.header('Access-Control-Allow-Origin', origin)
44
42
  }
@@ -55,31 +53,10 @@ module.exports = function (options) {
55
53
  }
56
54
  next()
57
55
  }
58
- // IMPLEMENT SESSION LOGIC HERE
59
56
  app.use(allowCrossDomain)
60
- // app.use(
61
- // sanitizer.clean({
62
- // xss: true,
63
- // noSql: true,
64
- // sql: true
65
- // })
66
- // )
67
- app.get('/health', (req, res) => {
68
- res.json('OK')
69
- })
70
- app.get('/environment', (req, res) => {
71
- const env = {}
72
- for (let key in process.env) {
73
- if (key.substring(0, 7) === 'CLIENT_') {
74
- env[key.substring(7)] = process.env[key]
75
- }
76
- }
77
- res.json(env)
78
- })
79
57
  if (options.useRecaptcha === true && process.env.RECAPTCHA_SECRET) {
80
58
  app.use('/google', require(`./routes/${version}/recaptcha`))
81
- }
82
- app.use('/pdf', require(`./routes/${version}/pdf`))
59
+ }
83
60
  if (options.useDB === true) {
84
61
  const dbHelper = require(`./helpers/${version}/${options.dbEngine}Helper`)
85
62
  let dbOptions = options.dbEngine === 'pg' ? options.dbOptions : options.dbOnError || {}
@@ -89,7 +66,7 @@ module.exports = function (options) {
89
66
  app.use(cookieParser(process.env.SESSION_SECRET))
90
67
  let cookieConfig = {
91
68
  maxAge: 7 * 24 * 60 * 60 * 1000,
92
- httpOnly: false,
69
+ httpOnly: process.env.COOKIE_HTTPS === 'true' || process.env.COOKIE_HTTPS === true,
93
70
  domain: process.env.COOKIE_DOMAIN || 'localhost',
94
71
  secure: process.env.COOKIE_SECURE === 'true' || process.env.COOKIE_SECURE === true,
95
72
  sameSite: process.env.COOKIE_SAMESITE || 'none',
@@ -167,7 +144,8 @@ module.exports = function (options) {
167
144
  else {
168
145
  let excludedRoutes = process.env.EXCLUDED_ROUTES.split(',')
169
146
  if (secureRoutes === true) {
170
- excludedRoutes.push('/resources', '/scripts', '/styles', '/external', '/templates', '/fonts')
147
+ // excludedRoutes.push('/resources', '/scripts', '/styles', '/templates', '/fonts')
148
+ excludedRoutes.push('/login')
171
149
  }
172
150
  if (secureRoutes === false && excludedRoutes.indexOf('/' + req.path.split('/')[1]) !== -1) {
173
151
  app.authHelper.isLoggedIn(req, res, next)
@@ -178,8 +156,6 @@ module.exports = function (options) {
178
156
  else {
179
157
  next()
180
158
  }
181
- // secureRoutes === false && excludedRoutes.indexOf(req.path) !== -1 && app.authHelper.isLoggedIn(req, res, next)
182
- // secureRoutes === true && excludedRoutes.indexOf(req.path) === -1 && app.authHelper.isLoggedIn(req, res, next)
183
159
  }
184
160
  }
185
161
  else {
@@ -187,6 +163,16 @@ module.exports = function (options) {
187
163
  }
188
164
  }
189
165
  app.use(protectedRoutes)
166
+ app.get('/environment', (req, res) => {
167
+ const env = {}
168
+ for (let key in process.env) {
169
+ if (key.substring(0, 7) === 'CLIENT_') {
170
+ env[key.substring(7)] = process.env[key]
171
+ }
172
+ }
173
+ res.json(env)
174
+ })
175
+ app.use('/pdf', require(`./routes/${version}/pdf`))
190
176
  if (options.useAPI === true) {
191
177
  app.use('/api', sanitizer.clean(Object.assign({}, {
192
178
  xss: true,
@@ -194,6 +180,7 @@ module.exports = function (options) {
194
180
  sql: true,
195
181
  noSqlLevel: 2,
196
182
  sqlLevel: 2,
183
+ level: 2,
197
184
  allowedKeys: options.allowedKeys || []
198
185
  }, (dbOptions.sanitizeOptions || {}))), checkReferrer, protectedRoutes, require(`./routes/${version}/api`)(dbHelper, app.authHelper))
199
186
  }
@@ -237,6 +224,16 @@ module.exports = function (options) {
237
224
  next()
238
225
  }
239
226
  }
227
+ app.use(protectedRoutes)
228
+ app.get('/environment', (req, res) => {
229
+ const env = {}
230
+ for (let key in process.env) {
231
+ if (key.substring(0, 7) === 'CLIENT_') {
232
+ env[key.substring(7)] = process.env[key]
233
+ }
234
+ }
235
+ res.json(env)
236
+ })
240
237
  resolve({app})
241
238
  }
242
239
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@websy/websy-designs",
3
- "version": "1.12.15",
3
+ "version": "2.0.0",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"