@bluedot-innovation/models 10.2.0 → 10.4.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,9 @@
1
+ ## 10.4.0
2
+ - Adds verificationCodeEnabled to project
3
+
4
+ ## 10.3.0
5
+ - Adds service type Users
6
+
1
7
  ## 10.2.0
2
8
  - Adds Rezolve Chat integration to project
3
9
 
@@ -0,0 +1,23 @@
1
+ module.exports = {
2
+ username: 'test@bluedot.io',
3
+ state: 'ACTIVE',
4
+ lastUpdateTime: '2018-02-14T04:12:02.103Z',
5
+ creationTime: '2018-02-14T04:12:02.103Z',
6
+ accountId: '37ac5be3-60ec-4fb7-9f88-a4f6e8895f81',
7
+ projectPermissions: [
8
+ {
9
+ permissionLevel: 'READ_WRITE',
10
+ projectId: '1dc621a1-7980-410b-839b-4bed63600139'
11
+ }
12
+ ],
13
+ type: 'service',
14
+ scope: {
15
+ hello: ['writeOrder']
16
+ },
17
+ keyName: 'Prod API Key',
18
+ createdBy: 'eaba2b56-61d6-4855-a3ea-f409e7fb6788',
19
+ tokenHash: '17CBIUn6jA7H8wLyeZQHX3IPmX5Zd16eMUNXgl1FY/E=',
20
+ isAdmin: false,
21
+ mfaRequired: false,
22
+ identityProvider: 'apiKey'
23
+ }
@@ -0,0 +1,20 @@
1
+ module.exports = {
2
+ requiredFields: ['username', 'accountId'],
3
+ customValidators: [
4
+ {name: 'creationTime', invalidInputs: ['21/07/2017', 'thursday']},
5
+ {name: 'lastUpdateTime', invalidInputs: ['21/07/2017', 'saturday']},
6
+ {name: 'tokenHash', invalidInputs: ['something']}
7
+ ],
8
+ customServiceTypeValidators: [
9
+ {name: 'isAdmin', invalidInputs: [true]},
10
+ {name: 'mfaRequired', invalidInputs: [true]},
11
+ {name: 'identityProvider', invalidInputs: ['internal', 'something-else']}
12
+ ],
13
+ requiredServiceTypeFields: ['keyName', 'tokenHash', 'scope', 'createdBy'],
14
+ requiredUserTypeFields: [
15
+ {name: 'firstName', value: 'Emma' },
16
+ {name: 'lastName', value: 'Goldman'},
17
+ {name: 'email', value: 'emma@goldman.com'}
18
+ ],
19
+ arrayTypeFields: ["projectPermissions"]
20
+ }
@@ -0,0 +1,167 @@
1
+ let mongoose = require('mongoose')
2
+
3
+ let UserModel = require('../../Models').User(mongoose)
4
+ let UserModelBuiltInMongoose = require('../../Models').User()
5
+ let describe = require('mocha').describe
6
+ let it = require('mocha').it
7
+ let rules = require('./apiUser.rules.js')
8
+ let chai = require('chai')
9
+ let assert = chai.assert
10
+ let mocha = require('mocha')
11
+ let beforeEach = mocha.beforeEach
12
+ let helpers = require('../helpers')
13
+ let { FALSY_VALUES } = require('../../constants/tests')
14
+
15
+ let user
16
+
17
+ beforeEach(() => {
18
+ user = require('./apiUser.data.js')
19
+ })
20
+
21
+ describe('service User', () => {
22
+ describe('Valid service User ', () => {
23
+ it('should validate a valid service user', async () => {
24
+ let User = new UserModel(user)
25
+ const res = await User.validate()
26
+ assert.notExists(res)
27
+ })
28
+
29
+ it('should validate a valid service user when initializing the model with an external mongoose instance', async () => {
30
+ let User = new UserModelBuiltInMongoose(user)
31
+ const res = await User.validate()
32
+ assert.notExists(res)
33
+ })
34
+ })
35
+
36
+ describe('Invalid service User', () => {
37
+ describe('recursive property check', () => {
38
+ let requiredFields = rules.requiredFields
39
+ requiredFields.forEach((requiredField) => {
40
+ it(`should throw an error with property '${requiredField}' if '${requiredField}' is not present`, async () => {
41
+ user = JSON.parse(JSON.stringify(user))
42
+ delete user[requiredField]
43
+ let User = new UserModel(user)
44
+ try {
45
+ await User.validate()
46
+ } catch (err) {
47
+ assert.exists(err, 'err object should exist')
48
+ assert.isObject(err.errors)
49
+ assert.nestedProperty(err, `errors.${requiredField}`, `error should have a ${requiredField} property`)
50
+ }
51
+ })
52
+ })
53
+
54
+ const requiredServiceTypeFields = rules.requiredServiceTypeFields
55
+ requiredServiceTypeFields.forEach((requiredField) => {
56
+ it(`should throw an error with property '${requiredField}' if '${requiredField}' is not present for service type`, async () => {
57
+ user = JSON.parse(JSON.stringify(user))
58
+ delete user[requiredField]
59
+ let User = new UserModel(user)
60
+ try {
61
+ await User.validate()
62
+ } catch (err) {
63
+ assert.exists(err, 'err object should exist')
64
+ assert.match(err.message, new RegExp(`Users of type service must have a ${requiredField} property`))
65
+ }
66
+ })
67
+ })
68
+ })
69
+
70
+ it('should not allow service User without type property', async () => {
71
+ user = JSON.parse(JSON.stringify(user))
72
+ delete user.type
73
+ const User = new UserModel(user)
74
+ try {
75
+ await User.validate()
76
+ } catch (err) {
77
+ assert.exists(err, 'err object should exist')
78
+ console.log(err)
79
+ assert.match(err, /Users must has a "type" of either service or user/)
80
+ }
81
+ })
82
+
83
+ it('should not allow service User with empty hello array in scope property', async () => {
84
+ user = JSON.parse(JSON.stringify(user))
85
+ user.scope = {
86
+ hello: []
87
+ }
88
+ const User = new UserModel(user)
89
+ try {
90
+ await User.validate()
91
+ } catch (err) {
92
+ assert.exists(err, 'err object should exist')
93
+ console.log(err)
94
+ assert.match(err, /hello must be an array with 1 value of "writeOrder"/)
95
+ }
96
+ })
97
+
98
+ it('should not allow service User with no hello object in scope property', async () => {
99
+ user = JSON.parse(JSON.stringify(user))
100
+ user.scope = {}
101
+ const User = new UserModel(user)
102
+ try {
103
+ await User.validate()
104
+ } catch (err) {
105
+ assert.exists(err, 'err object should exist')
106
+ assert.match(err, /hello must be an array with 1 value of "writeOrder"/)
107
+ }
108
+ })
109
+ })
110
+
111
+ describe('recursive invalid entry check', () => {
112
+ const { customValidators } = rules
113
+
114
+ customValidators.forEach((customValidator) => {
115
+ customValidator.invalidInputs.forEach((invalidInput) => {
116
+ it(`should throw an error with property '${customValidator.name}' if '${customValidator.name}' is invalid => ${customValidator.name} = ${invalidInput}`, async () => {
117
+ user = JSON.parse(JSON.stringify(user))
118
+ user[customValidator.name] = invalidInput
119
+ let User = new UserModel(user)
120
+ try {
121
+ await User.validate()
122
+ } catch (err) {
123
+ assert.exists(err, 'err object should exist')
124
+ assert.isObject(err.errors)
125
+ assert.nestedProperty(err, `errors.${customValidator.name}`, `error should have a ${customValidator.name} property`)
126
+ }
127
+ })
128
+ })
129
+ })
130
+
131
+ const customServiceTypeValidators = rules.customServiceTypeValidators
132
+
133
+ customServiceTypeValidators.forEach((customValidator) => {
134
+ customValidator.invalidInputs.forEach((invalidInput) => {
135
+ it(`should throw an error with property '${customValidator.name}' if '${customValidator.name}' is invalid => ${customValidator.name} = ${invalidInput}`, async () => {
136
+ user = JSON.parse(JSON.stringify(user))
137
+ user[customValidator.name] = invalidInput
138
+ let User = new UserModel(user)
139
+ try {
140
+ await User.validate()
141
+ } catch (err) {
142
+ assert.exists(err, 'err object should exist')
143
+ assert.match(err, new RegExp(customValidator))
144
+ }
145
+ })
146
+ })
147
+ })
148
+ })
149
+
150
+ describe('user User fields should be rejected for service Users', () => {
151
+ const requiredUserTypeFields = rules.requiredUserTypeFields
152
+
153
+ requiredUserTypeFields.forEach((customValidator) => {
154
+ it(`should throw an error with property '${customValidator.name}' if '${customValidator.name}' is present for service User`, async () => {
155
+ user = JSON.parse(JSON.stringify(user))
156
+ user[customValidator.name] = customValidator.value
157
+ let User = new UserModel(user)
158
+ try {
159
+ await User.validate()
160
+ } catch (err) {
161
+ assert.exists(err, 'err object should exist')
162
+ assert.match(err, new RegExp(`Users of type service must not have a ${customValidator.name} property`))
163
+ }
164
+ })
165
+ })
166
+ })
167
+ })
@@ -124,7 +124,8 @@
124
124
  "hello": {
125
125
  "activeTtl": 604800,
126
126
  "finalTtl": 86400,
127
- "ssoLinkingCode": "HGDUS69SDJJ0"
127
+ "ssoLinkingCode": "HGDUS69SDJJ0",
128
+ "verificationCodeEnabled": true
128
129
  },
129
130
  "reportConfigurations": [
130
131
  {
@@ -17,5 +17,6 @@ module.exports = {
17
17
  }
18
18
  ],
19
19
  mfaRequired: true,
20
- identityProvider: "test-azure-idp-dev1"
20
+ identityProvider: "test-azure-idp-dev1",
21
+ type: 'user'
21
22
  }
@@ -1,5 +1,5 @@
1
1
  module.exports = {
2
- requiredFields: ['username', 'firstName', 'lastName', 'isAdmin', 'accountId'],
2
+ requiredFields: ['username', 'isAdmin', 'accountId'],
3
3
  customValidators: [
4
4
  {name: 'phoneNumber', invalidInputs: ['409203492039284232034398','1','1234']},
5
5
  {name: 'firstName', invalidInputs: ['F']},
@@ -7,5 +7,12 @@ module.exports = {
7
7
  {name: 'creationTime', invalidInputs: ['21/07/2017', 'thursday']},
8
8
  {name: 'lastUpdateTime', invalidInputs: ['21/07/2017', 'saturday']}
9
9
  ],
10
+ requiredUserTypeFields: ['firstName', 'lastName', 'email'],
11
+ requiredServiceTypeFields: [
12
+ {name: 'keyName', value: 'some name' },
13
+ {name: 'tokenHash', value: '17CBIUn6jA7H8wLyeZQHX3IPmX5Zd16eMUNXgl1FY/E='},
14
+ {name: 'scope', value: { hello: ['writeOrder']}},
15
+ {name: 'createdBy', value: 'eaba2b56-61d6-4855-a3ea-f409e7fb6788'}
16
+ ],
10
17
  arrayTypeFields: ["projectPermissions"]
11
18
  }
@@ -37,6 +37,7 @@ describe('User', () => {
37
37
  delete user.mfaRequired
38
38
 
39
39
  const User = new UserModel(user)
40
+ console.log('user', User)
40
41
  assert(User.mfaRequired === false)
41
42
  const res = await User.validate()
42
43
  assert.notExists(res)
@@ -65,11 +66,28 @@ describe('User', () => {
65
66
  await User.validate()
66
67
  } catch (err) {
67
68
  assert.exists(err, 'err object should exist')
69
+ console.log(err)
68
70
  assert.isObject(err.errors)
69
71
  assert.nestedProperty(err, `errors.${requiredField}`, `error should have a ${requiredField} property`)
70
72
  }
71
73
  })
72
74
  })
75
+
76
+ const requiredUserTypeFields = rules.requiredUserTypeFields
77
+ requiredUserTypeFields.forEach((requiredField) => {
78
+ it(`should throw an error with property '${requiredField}' if '${requiredField}' is not present for user type`, async () => {
79
+ user = JSON.parse(JSON.stringify(user))
80
+ delete user[requiredField]
81
+ let User = new UserModel(user)
82
+ try {
83
+ await User.validate()
84
+ } catch (err) {
85
+ assert.exists(err, 'err object should exist')
86
+ console.log(err)
87
+ assert.match(err.message, new RegExp(`Users of type user must have a ${requiredField} property`))
88
+ }
89
+ })
90
+ })
73
91
  })
74
92
 
75
93
  it('should not allow mfaRequired to be set to null', async () => {
@@ -84,6 +102,31 @@ describe('User', () => {
84
102
  assert.nestedProperty(err, `errors.mfaRequired`, `error should have a mfaRequired property`)
85
103
  }
86
104
  })
105
+
106
+ it('should not allow user without type property', async () => {
107
+ user = JSON.parse(JSON.stringify(user))
108
+ delete user.type
109
+ const User = new UserModel(user)
110
+ try {
111
+ await User.validate()
112
+ } catch (err) {
113
+ assert.exists(err, 'err object should exist')
114
+ console.log(err)
115
+ assert.match(err, /Users must has a "type" of either service or user/)
116
+ }
117
+ })
118
+
119
+ it('should not allow user of invalid type', async () => {
120
+ user = JSON.parse(JSON.stringify(user))
121
+ user.type = 'invalid'
122
+ const User = new UserModel(user)
123
+ try {
124
+ await User.validate()
125
+ } catch (err) {
126
+ assert.exists(err, 'err object should exist')
127
+ assert.match(err, /`invalid` is not a valid enum value for path `type`/)
128
+ }
129
+ })
87
130
  })
88
131
 
89
132
  describe('recursive invalid entry check', () => {
@@ -107,6 +150,24 @@ describe('User', () => {
107
150
  })
108
151
  })
109
152
 
153
+ describe('service User fields should be rejected for user Users', () => {
154
+ const requiredServiceTypeFields = rules.requiredServiceTypeFields
155
+
156
+ requiredServiceTypeFields.forEach((customValidator) => {
157
+ it(`should throw an error with property '${customValidator.name}' if '${customValidator.name}' is present for user User`, async () => {
158
+ user = JSON.parse(JSON.stringify(user))
159
+ user[customValidator.name] = customValidator.value
160
+ let User = new UserModel(user)
161
+ try {
162
+ await User.validate()
163
+ } catch (err) {
164
+ assert.exists(err, 'err object should exist')
165
+ assert.match(err, new RegExp(`Users of type user must not have a ${customValidator.name} property`))
166
+ }
167
+ })
168
+ })
169
+ })
170
+
110
171
  describe('projectPermissions:', () => {
111
172
  it('should fail if projectId is invalid', async () => {
112
173
  user = JSON.parse(JSON.stringify(user))
package/models/User.js CHANGED
@@ -9,8 +9,11 @@ const patcher = require('@bluedot-innovation/mongoose-json-patch')
9
9
  const helpers = require('../helpers')
10
10
  const ProjectPermission = require('../schemas/ProjectPermission')
11
11
  const uuidv4 = require('uuid/v4')
12
+ const ApiUserScopeSchema = require("../schemas/ApiUserScope");
12
13
 
13
- let UserSchema = new mongoose.Schema({
14
+ const options = { discriminatorKey: 'type', collection: 'user'}
15
+
16
+ const UserSchema = new mongoose.Schema({
14
17
  _id: {type: String, default: uuidv4},
15
18
  username: {
16
19
  type: String,
@@ -18,35 +21,51 @@ let UserSchema = new mongoose.Schema({
18
21
  maxlength: 100,
19
22
  unique: true
20
23
  },
21
- email: {
24
+ state: {type: String, default: StateEnum.ACTIVE},
25
+ creationTime: {type: Date, default: Date.now},
26
+ lastUpdateTime: {type: Date, default: Date.now},
27
+ projectPermissions: {type: [ProjectPermission], validate: helpers.validateNotNull},
28
+ accountId: {
22
29
  type: String,
23
30
  required: true,
31
+ validator: helpers.validateUUIDv4
32
+ },
33
+ type: { type: String, enum: ['user', 'service'], required: true },
34
+ mfaRequired: {type: Boolean, default: false, required: true},
35
+ identityProvider: {type: String, default: "internal", required: true},
36
+ isAdmin: {type: Boolean, required: true},
37
+ // Below are user specific properties
38
+ email: {
39
+ type: String,
24
40
  validate: {
25
41
  validator: helpers.validateEmail,
26
42
  message: '{VALUE} is not a valid email'
27
43
  }
28
44
  },
29
- firstName: {type: String, required: true, minlength:2, maxlength:120},
30
- lastName: {type: String, required: true, minlength:2, maxlength:120},
45
+ firstName: {type: String, minlength:2, maxlength:120},
46
+ lastName: {type: String, minlength:2, maxlength:120},
31
47
  phoneNumber: {type: String, minlength:8, maxlength: 20, validate: helpers.validateNotNull},
32
- state: {type: String, default: StateEnum.ACTIVE},
33
- creationTime: {type: Date, default: Date.now},
34
- lastUpdateTime: {type: Date, default: Date.now},
35
- isAdmin: {type: Boolean, required: true},
36
48
  secret: String,
37
- projectPermissions: {type: [ProjectPermission], validate: helpers.validateNotNull},
38
- accountId: {
49
+ superAdmin: Boolean,
50
+ // Below are API Key (service type) specific properties
51
+ keyName: {
39
52
  type: String,
40
- required: true,
41
- validator: helpers.validateUUIDv4
53
+ maxlength: 100,
54
+ minLength: 2
42
55
  },
43
- superAdmin: Boolean,
44
- mfaRequired: {type: Boolean, default: false, required: true},
45
- identityProvider: {type: String, default: "internal", required: true}
46
- },
47
- {collection: 'user'})
48
-
49
- UserSchema.plugin(patcher)
56
+ scope: {
57
+ type: ApiUserScopeSchema,
58
+ },
59
+ tokenHash: {
60
+ type: String,
61
+ minLength: 44,
62
+ maxLength: 44
63
+ },
64
+ createdBy: {
65
+ type: String,
66
+ validator: helpers.validateUUIDv4
67
+ }
68
+ }, options)
50
69
 
51
70
  UserSchema.pre('validate', function(next) {
52
71
  Promise.all([
@@ -60,6 +79,49 @@ UserSchema.pre('validate', function(next) {
60
79
  }).catch(console.log);
61
80
  })
62
81
 
82
+ UserSchema.pre('validate', function(next) {
83
+ const userRequiredFields = ['email', 'firstName', 'lastName']
84
+ const serviceRequiredFields = ['keyName', 'scope', 'tokenHash', 'createdBy']
85
+ if(!this.type){
86
+ next(new Error('Users must has a "type" of either service or user'))
87
+ }
88
+ if(this.type === 'user'){
89
+ userRequiredFields.forEach(property => {
90
+ if(!this[property]){
91
+ next(new Error(`Users of type user must have a ${property} property`))
92
+ }
93
+ })
94
+ serviceRequiredFields.forEach(property => {
95
+ if(this[property]){
96
+ next(new Error(`Users of type user must not have a ${property} property`))
97
+ }
98
+ })
99
+ }else if(this.type === 'service'){
100
+ serviceRequiredFields.forEach(property => {
101
+ if(!this[property]){
102
+ next(new Error(`Users of type service must have a ${property} property`))
103
+ }
104
+ })
105
+ userRequiredFields.forEach(property => {
106
+ if(this[property]){
107
+ next(new Error(`Users of type service must not have a ${property} property`))
108
+ }
109
+ })
110
+ const propertiesMustBeFalse = ['isAdmin', 'mfaRequired']
111
+ propertiesMustBeFalse.forEach(property => {
112
+ if(typeof this[property] !== 'boolean' || this[property] !== false){
113
+ next(new Error(`${property} must be false for service Users`))
114
+ }
115
+ })
116
+ if(this['identityProvider'] !== 'apiKey'){
117
+ next(new Error('service Users must have identityProvider set to apiKey'))
118
+ }
119
+ }
120
+ next()
121
+ })
122
+
123
+ UserSchema.plugin(patcher)
124
+
63
125
  // optional mongoose
64
126
  let model = (mongooseInstance) => {
65
127
  let User
@@ -68,7 +130,6 @@ let model = (mongooseInstance) => {
68
130
  } else {
69
131
  User = mongoose.model('User', UserSchema)
70
132
  }
71
-
72
133
  return User
73
134
  }
74
135
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bluedot-innovation/models",
3
- "version": "10.2.0",
3
+ "version": "10.4.0",
4
4
  "main": "Models.js",
5
5
  "scripts": {
6
6
  "lint": "./node_modules/.bin/eslint -c .eslintrc.js ./models/*.js ./__tests__/**/*.js ./__tests__/**/**/*.js ./schemas/*.js",
@@ -0,0 +1,9 @@
1
+ let mongoose = require('mongoose')
2
+
3
+ let ApiUserScopeSchema = new mongoose.Schema({
4
+ hello: {type: [{ type: String, enum: ['writeOrder'] }], required: true , validate: [(value) => Array.isArray(value) && value.length === 1, 'scope.hello must be an array with 1 value of "writeOrder"']}
5
+ }, {
6
+ _id: false
7
+ })
8
+
9
+ module.exports = ApiUserScopeSchema
@@ -4,7 +4,8 @@ const helpers = require('../helpers')
4
4
  let ProjectHelloSchema = new mongoose.Schema({
5
5
  activeTtl: {type: Number, min: 0, max: 1209600, validate: { validator: Number.isInteger, msg: 'hello.activeTtl should be an integer number' }},
6
6
  finalTtl: {type: Number, min: 0, max: 1209600, validate: { validator: Number.isInteger, msg: 'hello.finalTtl should be an integer number' }},
7
- ssoLinkingCode: {type: String, validate: {validator: helpers.validateSsoLinkingCode, msg: 'SSO linking code must be a 12 character capital alphanumeric text'}}
7
+ ssoLinkingCode: {type: String, validate: {validator: helpers.validateSsoLinkingCode, msg: 'SSO linking code must be a 12 character capital alphanumeric text'}},
8
+ verificationCodeEnabled: { type: Boolean }
8
9
  }, {
9
10
  _id: false
10
11
  })