-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.js
329 lines (292 loc) · 11.3 KB
/
config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/**
* This file config.js, loads the Learning Pass's configuration.
*
* Copyright 2022 Andrew Nisbet, Edmonton Public Library
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const logger = require('./logger');
const utils = require('./lib/util');
const process = require('process');
// Check the .env for test partner keys and settings for the startup environment.
const dotenv = require('dotenv');
dotenv.config();
// Read the configuration from JSON in the ./config/config.json file.
const configFile = './config/config.json';
// The environment object of helper functions.
const environment = {};
// Staging environment object.
const defaultServerSettings = {
'httpPort' : 3000,
'httpsPort' : 3001,
'envName' : 'staging'
};
// Default partner settings for testing purposes.
const testPartners = [{
"name" : "default",
"key" : "QJnc2JQLICWASpVj6eIR",
"strictChecks" : false,
"config" : "./config/default.json"
}];
/**
* These are the canonical set and spelling of field names
* Learning Pass understands.
*
* Theoretically, you could change these to another language as
* long as they match those in the config.json, default.json and
* any partner.json files.
*
*/
environment._fields = [
"firstName","lastName", "middleName", "dob","gender","email", "careOf",
"phone","street","city","province","country","postalCode",
"barcode","pin","type","expiry","branch","status","notes"
];
/**
* Validates that the fields marked required match field
* names in the Learning Pass specification.
*
* @param {*} partnerConfigs - 'required' fields read from JSON.
* @returns true if at least all the partner's required fields
* match spelling and case of fields of JSON data inbound
* from partner.
*/
const validatePartnerConfigs = function(partnerConfigs){
let errors = [];
// Test for special sub-objects.
let requiredList = partnerConfigs.required;
if (utils.hasArrayData(requiredList)) {
requiredList.forEach(pField => {
if (environment._fields.indexOf(pField) < 0){
errors.push(pField);
}
});
} else {
errors.push(`the "required" list is empty.`);
}
// Optional may be a list and if it is, check for spelling
if (utils.hasArrayData(partnerConfigs.optional)){
let optionalList = partnerConfigs.optional;
optionalList.forEach(pField => {
if (environment._fields.indexOf(pField) < 0){
errors.push(pField);
}
});
}
return errors;
};
/**
* Load all the server configs from the configFile.
*/
(function(){
let config;
try {
config = require(configFile);
} catch (error) {
// Happens if the file is missing.
logger.error(`Error in ${configFile}.`);
}
if (config){
// Read in version from JSON and if it does not exist report '0.0' which could be diagnostic.
environment.version = typeof(config.version) === 'string' || typeof(config.version) === 'number' ? config.version : "0.0";
// Test if the server should be in loopback mode for situations like outages.
environment.loopbackMode = typeof(config.loopbackMode) === 'boolean' ? config.loopbackMode : false;
// Test if the server should be in loopback mode for situations like outages.
environment.testMode = typeof(config.testMode) === 'boolean' ? config.testMode : false;
// Load the server settings.
// Read in the server configuration object, and have a default standing by if there isn't one.
let envName = utils.hasStringData(process.env.NODE_ENV) ? process.env.NODE_ENV.toLowerCase() : "staging";
environment.serverConfig = utils.hasDictData(config[envName]) ? config[envName] : defaultServerSettings;
logger.info(`Server starting as '${environment.serverConfig.envName}'.`);
// Load the default customer settings from the config.json
if (utils.hasDictData(config.customerSettings)){
let libraryName = config.customerSettings.library;
if (utils.hasStringData(libraryName)){
logger.info(`Using customer settings for ${libraryName}`);
environment.customerSettings = config.customerSettings;
} else {
throw new Error(`Error: ${configFile}'s 'customerSettings' must contain a 'library' entry.`)
}
} else {
throw new Error(`Error config.json: ${configFile} is missing "customerSettings".`);
}
if (environment.testMode){
// Test if the default had to be used because partner array is missing.
environment.partners = testPartners;
logger.debug(`TEST_MODE: using default partner settings for testing.`);
logger.debug(`TEST_MODE: See documentation for more information.`);
} else {
// Load the partner preferences. If the server is in loopback mode server should return message, but if in testMode load
// the defaultPartners defined above.
// Find configs for partners, and if there isn't any listed, suggest using loopback mode and throw exception.
// environment.partners = typeof(config[names.partners]) == 'object' ? config[names.partners] : {};
environment.partners = config.partners;
}
// Create a dictionary with { key : {"./config/partner.json"}}
// Find the apiKey
// Find the partner's configuration.json.
environment.partners.forEach(partner => {
if (!utils.hasStringData(partner.key)) {
logger.error(`Error: cannot find partner api key for ${partner.name}! They will not be able to create new accounts.`);
}
try {
let partnerConfigs = require(partner.config);
// check the required fields definition.
let anyErrors = validatePartnerConfigs(partnerConfigs);
if (anyErrors.length > 0){
logger.error(`**Error: '${partner.config}' has errors: "${anyErrors}".`);
} else {
// Check and add the 'strictChecks' flag is set for the partner and if so
// set the flag, but by default it should be true.
partnerConfigs.strictChecks = partner.strictChecks == false ? false : true;
if (! partnerConfigs.strictChecks) {
logger.info(` - *WARNING: '${partner.name}' is not using strict data checking!`);
}
// Save the partner's config.json data as their api key, value pair.
environment[partner.key] = partnerConfigs;
logger.info(` - '${partner.name}' configs loaded successfully.`);
}
} catch (err) {
logger.error(`Error in ${configFile}.`,err);
}
});
logger.info(`Finished loading valid partner configurations.`);
// Test that the partners' required and optional fields contain valid names that match environment._fields.
} else {
logger.error(`Error config may be missing or contain errors.`);
}
})();
/**
* Returns the version number of the json config file
* or '0.0' if one is not in the json config file.
*/
environment.getVersion = function(){
return environment.version;
};
/**
* Returns the server configs or an empty object if none were read
* from the config.json.
*/
environment.getServerConfig = function(){
// if (typeof(environment.serverConfig) == 'object'){
if (utils.hasDictData(environment.serverConfig)){
return environment.serverConfig;
} else {
logger.error(`Error server configs not set.`);
return {};
}
};
/**
* Returns the configs for a given partner's API key.
* @param {*} apiKey api key for a given customer.
*/
environment.getPartnerConfig = function(apiKey){
if (!utils.hasStringData(apiKey)) {
logger.error(`Error no api key was submitted.`);
return {};
} else {
if (utils.hasDictData(environment[apiKey])){
return environment[apiKey];
} else {
logger.error(`Error: invalid API key.`);
return {};
}
}
};
/**
* Returns all the default customer configurations required
* to complete a well-formed flat file, as dictated by
* library policy.
*/
environment.getDefaultCustomerSettings = function(){
if (utils.hasDictData(environment.customerSettings)){
return environment.customerSettings;
} else {
logger.error(`Error customer default configs not set.`);
return {};
}
};
/**
*
* @returns the http port for the environment set by process.env.NODE_ENV.
*/
environment.getHttpPort = function() {
return environment.serverConfig.httpPort;
}
/**
*
* @returns the https port for the environment set by process.env.NODE_ENV.
*/
environment.getHttpsPort = function() {
return environment.serverConfig.httpsPort;
}
/**
* Returns true if the 'loopbackMode' key-value pair exists in the config.json
* and is set to true, and false otherwise.
*/
environment.useLoopbackMode = function(){
return environment.loopbackMode;
}
/**
* The config file can contain a 'certs' entry in "staging" : { "directories" : { "certs" : "../https" } }.
* As of release 1.0 it is preferrable to use .env and use the following instead.
* LPASS_SSL_PRIVATE_KEY=/etc/ssl/private/some.key
* LPASS_SSL_CERTIFICATE=/etc/ssl/certs/some.crt
*
* @returns determines where to find the certs directory for the environment
* as set by process.env.NODE_ENV.
* @deprecated
*/
environment.getCertsDir = function() {
return environment.serverConfig.directories.certs;
}
/**
* Returns the certificate file name found in process.env.LPASS_SSL_CERTIFICATE
* @returns the name and path of the SSL certificate for the LPass domain.
* set in process.env.LPASS_SSL_CERTIFICATE.
*/
environment.getSSLCertificate = function() {
return process.env.LPASS_SSL_CERTIFICATE;
}
/**
* Returns the private key file name found in process.env.LPASS_SSL_PRIVATE_KEY
* @returns the name and path of the SSL private key for the LPass domain.
* set in process.env.LPASS_SSL_PRIVATE_KEY.
*/
environment.getSSLKey = function() {
return process.env.LPASS_SSL_PRIVATE_KEY;
}
/**
* Determines where to write flat files.
*
* @returns the flat directory depending on the installation
* environment set by process.env.NODE_ENV.
*/
environment.getFlatDir = function() {
return environment.serverConfig.directories.flat;
}
/**
* @returns true if the 'testMode' key-value pair exists in the config.json
* and is set to true, and false otherwise.
*/
environment.useTestMode = function(){
return environment.testMode;
}
/**
* @returns the configured environment name.
*/
environment.getEnvName = function(){
return environment.serverConfig.envName;
}
module.exports = environment;