@websy/websy-designs 1.1.12 → 1.2.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.
@@ -2,8 +2,13 @@ const bCrypt = require('bcrypt-nodejs')
2
2
  const md5 = require('md5')
3
3
 
4
4
  class AuthHelper {
5
- constructor (dbHelper) {
5
+ constructor (dbHelper, options) {
6
6
  this.dbHelper = dbHelper
7
+ const DEFAULTS = {
8
+ loginType: 'email'
9
+ }
10
+ this.options = Object.assign({}, DEFAULTS, options)
11
+ console.log(this.options)
7
12
  }
8
13
  login (req, res) {
9
14
  return new Promise((resolve, reject) => {
@@ -11,17 +16,19 @@ class AuthHelper {
11
16
  return (md5(md5(password) + user.salt)) === user.pepper
12
17
  }
13
18
  // check in mongo if a user with username exists or not
14
- const email = req.body.email.toLowerCase()
19
+ console.log(req.body)
20
+ const email = req.body[this.options.loginType].toLowerCase()
15
21
  const userQuery = `
16
22
  SELECT *
17
23
  FROM users
18
- WHERE email = '${email}'
19
- `
24
+ WHERE ${this.options.loginType} = '${email}'
25
+ `
26
+ console.log(userQuery)
20
27
  this.dbHelper.execute(userQuery).then(result => {
21
28
  // Username does not exist, log the error and redirect back
22
29
  if (result.rows.length === 0) {
23
30
  console.log('No User')
24
- reject(`User not found with email ${email}`)
31
+ reject(`User not found with ${this.options.loginType} ${email}`)
25
32
  return
26
33
  }
27
34
  const user = result.rows[0]
@@ -38,7 +45,13 @@ class AuthHelper {
38
45
  SET lastlogon = now()
39
46
  WHERE id = ${user.id}
40
47
  `
41
- this.dbHelper.execute(userUpdateQuery).then(result => resolve(user), err => reject(err))
48
+ this.dbHelper.execute(userUpdateQuery).then(result => {
49
+ console.log('yes')
50
+ resolve(user)
51
+ }, err => {
52
+ console.log('no')
53
+ reject(err)
54
+ })
42
55
  // LogonHistory.create({
43
56
  // userid: user.userid
44
57
  // }, function(err, result) {
@@ -65,11 +78,11 @@ class AuthHelper {
65
78
  return v.toString(16)
66
79
  })
67
80
  }
68
- const email = req.body.email.toLowerCase()
81
+ const email = req.body[this.options.loginType].toLowerCase()
69
82
  const userQuery = `
70
83
  SELECT *
71
84
  FROM users
72
- WHERE email = '${email}'
85
+ WHERE ${this.options.loginType} = '${email}'
73
86
  `
74
87
  this.dbHelper.execute(userQuery).then(result => {
75
88
  if (result.rows.length > 0) {
@@ -77,7 +90,7 @@ class AuthHelper {
77
90
  }
78
91
  else {
79
92
  const newUser = {}
80
- newUser.email = email
93
+ newUser[this.options.loginType] = email
81
94
  if (req.body.optedin === 'on') {
82
95
  newUser.optedin = true
83
96
  }
@@ -107,18 +120,15 @@ class AuthHelper {
107
120
  }
108
121
  })
109
122
  }
110
- isLoggedIn (req, res, next) {
111
- if (req.isAuthenticated) {
112
- if (req.isAuthenticated()) {
113
- next()
114
- }
115
- else {
116
- res.redirect('/login')
117
- }
123
+ isLoggedIn (req, res, next) {
124
+ if (req.session && req.session.user) {
125
+ console.log('in condition D')
126
+ next()
118
127
  }
119
128
  else {
120
- next()
121
- }
129
+ console.log('in condition E')
130
+ res.redirect('/login')
131
+ }
122
132
  }
123
133
  }
124
134
 
@@ -47,10 +47,29 @@ const sql = {
47
47
  "expire" timestamp(6) NOT NULL
48
48
  )
49
49
  WITH (OIDS=FALSE);
50
-
51
- ALTER TABLE "sessions" ADD CONSTRAINT "sessions_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;
52
-
53
- CREATE INDEX "IDX_sessions_expire" ON "sessions" ("expire");
50
+
51
+ ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;
52
+
53
+ CREATE INDEX "IDX_session_expire" ON "session" ("expire");
54
+ `,
55
+ users: `
56
+ CREATE TABLE users (
57
+ id SERIAL PRIMARY KEY,
58
+ username character varying(128),
59
+ salt character varying(128) UNIQUE,
60
+ pepper character varying(128) UNIQUE,
61
+ created timestamp without time zone DEFAULT now(),
62
+ edited timestamp without time zone,
63
+ email character varying(256),
64
+ role character varying(50) DEFAULT 'User'::character varying,
65
+ lastlogon timestamp without time zone,
66
+ activated boolean DEFAULT false,
67
+ activationcode uuid,
68
+ activationexpiry bigint,
69
+ optedin boolean DEFAULT false,
70
+ language character varying(5) DEFAULT 'en'::character varying,
71
+ referredby character varying(128)
72
+ );
54
73
  `
55
74
  }
56
75
 
@@ -193,12 +212,20 @@ class PGHelper {
193
212
  }
194
213
  let list = input.split(';').map(d => {
195
214
  let parts = d.split(':')
196
- if (parts[1].indexOf('%') !== -1) {
197
- return `${entity ? entity + '.' : ''}${parts[0]} LIKE '${parts[1]}'`
198
- }
215
+ if (parts.length === 2) {
216
+ if (parts[1].indexOf('%') !== -1) {
217
+ return `${entity ? entity + '.' : ''}${parts[0]} LIKE '${parts[1]}'`
218
+ }
219
+ else {
220
+ return `${entity ? entity + '.' : ''}${parts[0]} = '${parts[1]}'`
221
+ }
222
+ }
199
223
  else {
200
- return `${entity ? entity + '.' : ''}${parts[0]} = '${parts[1]}'`
201
- }
224
+ parts = d.split('!')
225
+ if (parts.length === 2) {
226
+ return `${entity ? entity + '.' : ''}${parts[0]} <> '${parts[1]}'`
227
+ }
228
+ }
202
229
  })
203
230
  return `
204
231
  ${list.join(' AND ')}
@@ -216,7 +243,9 @@ class PGHelper {
216
243
  checkTables () {
217
244
  this.createContentTable().then(() => {
218
245
  this.createTranslationTable().then(() => {
219
- this.createSessionTable()
246
+ this.createSessionTable().then(() => {
247
+ this.createUserTable()
248
+ })
220
249
  })
221
250
  })
222
251
  }
@@ -276,8 +305,25 @@ class PGHelper {
276
305
  })
277
306
  })
278
307
  }
308
+ createUserTable () {
309
+ return new Promise((resolve, reject) => {
310
+ this.execute(`
311
+ SELECT COUNT(*) AS tableexists FROM information_schema.tables
312
+ WHERE table_name = 'users'
313
+ `).then(result => {
314
+ if (result.rows && result.rows[0] && +result.rows[0].tableexists === 0) {
315
+ this.execute(sql.users).then(() => {
316
+ resolve()
317
+ })
318
+ }
319
+ else {
320
+ resolve()
321
+ }
322
+ })
323
+ })
324
+ }
279
325
  execute (query) {
280
- // console.log(query)
326
+ console.log(query)
281
327
  return new Promise((resolve, reject) => {
282
328
  if (query !== null) {
283
329
  this.client.query(query, (err, queryResponse) => {
@@ -2,14 +2,16 @@ const cookieParser = require('cookie-parser')
2
2
  const cookie = require('cookie')
3
3
 
4
4
  module.exports = {
5
- createSession: function (dbHelper, sId, data) {
5
+ createSession: function (dbHelper, data) {
6
6
  return new Promise((resolve, reject) => {
7
+ const sId = createIdentity()
7
8
  const dataString = JSON.stringify(data)
9
+ const expire = new Date(new Date().getTime() + (24 * 60 * 60 * 1000)).toISOString()
8
10
  const sql = `
9
- INSERT INTO sessions (sId, session)
10
- VALUES ('${sId}', '${dataString}')
11
+ INSERT INTO sessions (sId, sess, expire)
12
+ VALUES ('${sId}', '${dataString}', '${expire}')
11
13
  `
12
- dbHelper.execute(sql).then(result => resolve(), err => reject(err))
14
+ dbHelper.execute(sql).then(result => resolve({sessionId: sId}), err => reject(err))
13
15
  })
14
16
  },
15
17
  saveSession: function (dbHelper, sId, data) {
@@ -17,7 +19,7 @@ module.exports = {
17
19
  const dataString = JSON.stringify(data)
18
20
  const sql = `
19
21
  UPDATE sessions
20
- SET session = '${dataString}'
22
+ SET sess = '${dataString}'
21
23
  WHERE sId = '${sId}'
22
24
  `
23
25
  dbHelper.execute(sql).then(result => resolve(), err => reject(err))
@@ -3,6 +3,7 @@ const router = express.Router()
3
3
  const expressSession = require('express-session')
4
4
  const DBSession = require('connect-pg-simple')(expressSession)
5
5
  const cookieParser = require('cookie-parser')
6
+ const cookie = require('cookie')
6
7
  const sessionHelper = require('../../helpers/v1/sessionHelper')
7
8
 
8
9
  const sql = {
@@ -39,13 +40,13 @@ const sql = {
39
40
  }
40
41
 
41
42
  function AuthRoutes (dbHelper, engine, app, Strategy) {
42
- const AuthHelper = require('../../helpers/v1/authHelper')
43
+ // const AuthHelper = require('../../helpers/v1/authHelper')
43
44
  if (typeof Strategy !== 'undefined') {
44
45
  app.authHelper = new Strategy(dbHelper)
45
46
  }
46
- else {
47
- app.authHelper = new AuthHelper(dbHelper)
48
- }
47
+ // else {
48
+ // app.authHelper = new AuthHelper(dbHelper)
49
+ // }
49
50
  if (dbHelper && !dbHelper.client) {
50
51
  dbHelper.onReadyAuthCallbackFn = readyCallback
51
52
  }
@@ -54,11 +55,32 @@ function AuthRoutes (dbHelper, engine, app, Strategy) {
54
55
  }
55
56
  router.post('/login', (req, res) => {
56
57
  app.authHelper.login(req, res).then(user => {
58
+ console.log('after login')
57
59
  if (!req.session) {
58
60
  req.session = {}
59
61
  }
60
- req.session.user = user
61
- res.json(req.session.user)
62
+ console.log(user)
63
+ req.session.user = user
64
+ if (dbHelper) {
65
+ const sId = sessionHelper.getSessionId(req)
66
+ let method = 'saveSession'
67
+ let params = [dbHelper, sId, req.session]
68
+ if (!sId) {
69
+ method = 'createSession'
70
+ params = [dbHelper, req.session]
71
+ }
72
+ // sessionHelper[method](...params).then((response) => {
73
+ // res.setHeader('Set-Cookie', cookie.serialize(process.env.COOKIE_NAME, String(response.sessionId), {
74
+ // httpOnly: true,
75
+ // sameSite: 'none',
76
+ // secure: true,
77
+ // maxAge: (1000 * 60 * 60 * 24)
78
+ // }))
79
+ res.json(req.session.user)
80
+ // }, err => {
81
+ // res.json({err})
82
+ // })
83
+ }
62
84
  }, err => {
63
85
  console.log('in auth route', err)
64
86
  res.json({err})
@@ -10,12 +10,14 @@ router.post('/checkrecaptcha', function (req, res) {
10
10
  if (req.headers['x-appengine-user-ip']) {
11
11
  body.remoteip = req.headers['x-appengine-user-ip']
12
12
  }
13
- request.post('https://www.google.com/recaptcha/api/siteverify', { form: body }, (err, response, body) => {
13
+ console.log('recaptcha body')
14
+ console.log(body)
15
+ request.post(`https://www.google.com/recaptcha/api/siteverify?secret=${process.env.RECAPTCHA_SECRET}&response=${req.body.grecaptcharesponse}`, body, (err, response, body) => {
14
16
  if (err) {
15
17
  res.json({ err: err })
16
18
  }
17
19
  else {
18
- res.json(response.body)
20
+ res.json(JSON.parse(response.body))
19
21
  }
20
22
  })
21
23
  })
@@ -29,6 +29,7 @@ module.exports = function (options) {
29
29
  app.use(bodyParser.json({limit: '5mb'}))
30
30
  app.use(bodyParser.urlencoded({limit: '5mb', extended: true}))
31
31
  app.use(bodyParser.raw({limit: '5mb'}))
32
+ const AuthHelper = require(`./helpers/${version}/authHelper`)
32
33
  const allowCrossDomain = (req, res, next) => {
33
34
  // console.log(req.url);
34
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']
@@ -38,7 +39,7 @@ module.exports = function (options) {
38
39
  }
39
40
  const origin = req.headers.origin
40
41
  // console.log(allowedOrigins.indexOf(origin))
41
- if (allowedOrigins.indexOf(origin) !== -1) {
42
+ if (allowedOrigins.indexOf(origin) !== -1 || allowedOrigins[0] === '*') {
42
43
  res.header('Access-Control-Allow-Origin', origin)
43
44
  }
44
45
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
@@ -46,6 +47,7 @@ module.exports = function (options) {
46
47
  res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Content-Type, Authorization, X-Requested-With, Set-Cookie')
47
48
  next()
48
49
  }
50
+ // IMPLEMENT SESSION LOGIC HERE
49
51
  app.use(allowCrossDomain)
50
52
  app.get('/health', (req, res) => {
51
53
  res.json('OK')
@@ -59,11 +61,11 @@ module.exports = function (options) {
59
61
  }
60
62
  res.json(env)
61
63
  })
62
- if (options.useRecaptcha === true) {
64
+ if (options.useRecaptcha === true && process.env.RECAPTCHA_SECRET) {
63
65
  app.use('/google', require(`./routes/${version}/recaptcha`))
64
66
  }
65
67
  app.use('/pdf', require(`./routes/${version}/pdf`))
66
- if (options.useDB === true) {
68
+ if (options.useDB === true) {
67
69
  const dbHelper = require(`./helpers/${version}/${options.dbEngine}Helper`)
68
70
  dbHelper.init(options.dbOptions || {}).then(() => {
69
71
  app.set('trust proxy', 1)
@@ -72,7 +74,7 @@ module.exports = function (options) {
72
74
  maxAge: 7 * 24 * 60 * 60 * 1000,
73
75
  httpOnly: false,
74
76
  domain: process.env.COOKIE_DOMAIN || 'localhost',
75
- // secure: process.env.COOKIE_SECURE || true,
77
+ secure: process.env.COOKIE_SECURE === 'true' || process.env.COOKIE_SECURE === true,
76
78
  sameSite: process.env.COOKIE_SAMESITE || 'none',
77
79
  credentials: 'include'
78
80
  }
@@ -122,7 +124,10 @@ module.exports = function (options) {
122
124
  console.log(error)
123
125
  }
124
126
  }
125
- if (options.useAuth === true) {
127
+ if (options.useAuth === true) {
128
+ if (typeof app.authHelper === 'undefined') {
129
+ app.authHelper = new AuthHelper(dbHelper, options.authOptions || {})
130
+ }
126
131
  app.use('/auth', require(`./routes/${version}/auth`)(dbHelper, options.dbEngine, app, options.strategy))
127
132
  }
128
133
  const protectedRoutes = function (req, res, next) {
@@ -131,19 +136,41 @@ module.exports = function (options) {
131
136
  secureRoutes = process.env.SECURE_ROUTES === 'true' || process.env.SECURE_ROUTES === true
132
137
  }
133
138
  if (app.authHelper && app.authHelper.isLoggedIn) {
134
- if (typeof process.env.EXCLUDED_ROUTES === 'undefined') {
135
- app.authHelper.isLoggedIn(req, res, next)
139
+ if (typeof process.env.EXCLUDED_ROUTES === 'undefined') {
140
+ if (secureRoutes === false) {
141
+ next()
142
+ }
143
+ else {
144
+ app.authHelper.isLoggedIn(req, res, next)
145
+ }
136
146
  }
137
147
  else {
138
148
  let excludedRoutes = process.env.EXCLUDED_ROUTES.split(',')
139
- secureRoutes === false && excludedRoutes.indexOf(req.path) !== -1 && app.authHelper.isLoggedIn(req, res, next)
140
- secureRoutes === true && excludedRoutes.indexOf(req.path) === -1 && app.authHelper.isLoggedIn(req, res, next)
149
+ // console.log('secure routes', secureRoutes)
150
+ // console.log('excluded routes', excludedRoutes)
151
+ console.log('path', req.path)
152
+ // console.log('index of', excludedRoutes.indexOf(req.path))
153
+ if (secureRoutes === false && excludedRoutes.indexOf(req.path) !== -1) {
154
+ console.log('in condition A')
155
+ app.authHelper.isLoggedIn(req, res, next)
156
+ }
157
+ else if (secureRoutes === true && excludedRoutes.indexOf(req.path) === -1) {
158
+ console.log('in condition B')
159
+ app.authHelper.isLoggedIn(req, res, next)
160
+ }
161
+ else {
162
+ console.log('in condition C')
163
+ next()
164
+ }
165
+ // secureRoutes === false && excludedRoutes.indexOf(req.path) !== -1 && app.authHelper.isLoggedIn(req, res, next)
166
+ // secureRoutes === true && excludedRoutes.indexOf(req.path) === -1 && app.authHelper.isLoggedIn(req, res, next)
141
167
  }
142
168
  }
143
169
  else {
144
170
  next()
145
171
  }
146
172
  }
173
+ app.use(protectedRoutes)
147
174
  if (options.useAPI === true) {
148
175
  app.use('/api', protectedRoutes, require(`./routes/${version}/api`)(dbHelper))
149
176
  }