@memberjunction/server 1.0.6 → 1.0.7

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.
Files changed (62) hide show
  1. package/.eslintignore +4 -4
  2. package/.eslintrc +24 -24
  3. package/CHANGELOG.json +92 -0
  4. package/CHANGELOG.md +25 -0
  5. package/README.md +141 -141
  6. package/dist/config.d.ts +3 -0
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +4 -1
  9. package/dist/config.js.map +1 -1
  10. package/dist/entitySubclasses/entityPermissions.server.d.ts +23 -0
  11. package/dist/entitySubclasses/entityPermissions.server.d.ts.map +1 -0
  12. package/dist/entitySubclasses/entityPermissions.server.js +99 -0
  13. package/dist/entitySubclasses/entityPermissions.server.js.map +1 -0
  14. package/dist/entitySubclasses/userViewEntity.server.js +17 -17
  15. package/dist/generated/generated.d.ts.map +1 -1
  16. package/dist/generated/generated.js.map +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/resolvers/AskSkipResolver.js +10 -10
  22. package/dist/resolvers/FileCategoryResolver.js +2 -2
  23. package/dist/resolvers/ReportResolver.js +4 -4
  24. package/package.json +80 -80
  25. package/src/apolloServer/TransactionPlugin.ts +57 -57
  26. package/src/apolloServer/index.ts +33 -33
  27. package/src/auth/exampleNewUserSubClass.ts +73 -73
  28. package/src/auth/index.ts +151 -151
  29. package/src/auth/newUsers.ts +56 -56
  30. package/src/auth/tokenExpiredError.ts +12 -12
  31. package/src/cache.ts +10 -10
  32. package/src/config.ts +89 -84
  33. package/src/context.ts +119 -119
  34. package/src/directives/Public.ts +42 -42
  35. package/src/directives/index.ts +1 -1
  36. package/src/entitySubclasses/entityPermissions.server.ts +111 -0
  37. package/src/entitySubclasses/userViewEntity.server.ts +187 -187
  38. package/src/generated/generated.ts +2573 -2573
  39. package/src/generic/PushStatusResolver.ts +40 -40
  40. package/src/generic/ResolverBase.ts +331 -331
  41. package/src/generic/RunViewResolver.ts +350 -350
  42. package/src/index.ts +133 -137
  43. package/src/orm.ts +36 -36
  44. package/src/resolvers/AskSkipResolver.ts +782 -782
  45. package/src/resolvers/ColorResolver.ts +72 -72
  46. package/src/resolvers/DatasetResolver.ts +115 -115
  47. package/src/resolvers/EntityRecordNameResolver.ts +77 -77
  48. package/src/resolvers/EntityResolver.ts +37 -37
  49. package/src/resolvers/FileCategoryResolver.ts +38 -38
  50. package/src/resolvers/FileResolver.ts +110 -110
  51. package/src/resolvers/MergeRecordsResolver.ts +198 -198
  52. package/src/resolvers/PotentialDuplicateRecordResolver.ts +59 -59
  53. package/src/resolvers/QueryResolver.ts +42 -42
  54. package/src/resolvers/ReportResolver.ts +131 -131
  55. package/src/resolvers/UserFavoriteResolver.ts +102 -102
  56. package/src/resolvers/UserResolver.ts +29 -29
  57. package/src/resolvers/UserViewResolver.ts +64 -64
  58. package/src/types.ts +19 -19
  59. package/src/util.ts +106 -106
  60. package/tsconfig.json +31 -31
  61. package/typedoc.json +4 -4
  62. package/build.log.json +0 -47
package/src/auth/index.ts CHANGED
@@ -1,151 +1,151 @@
1
- import { JwtHeader, SigningKeyCallback } from 'jsonwebtoken';
2
- import jwksClient from 'jwks-rsa';
3
- import { auth0Domain, auth0WebClientID, configInfo, tenantID, webClientID } from '../config';
4
- import { UserCache } from '@memberjunction/sqlserver-dataprovider';
5
- import { DataSource } from 'typeorm';
6
- import { Metadata, UserInfo } from '@memberjunction/core';
7
- import { NewUserBase } from './newUsers';
8
- import { MJGlobal } from '@memberjunction/global';
9
-
10
- export * from './tokenExpiredError';
11
-
12
- const missingAzureConfig = !tenantID || !webClientID;
13
- const missingAuth0Config = !auth0Domain || !auth0WebClientID;
14
-
15
- class MissingAuthError extends Error {
16
- constructor() {
17
- super('Could not find authentication configuration for either MSAL or Auth0 in the server environment variables.');
18
- this.name = 'MissingAuthError';
19
- }
20
- }
21
-
22
- const issuers = {
23
- azure: `https://login.microsoftonline.com/${tenantID}/v2.0`,
24
- auth0: `https://${auth0Domain}/`,
25
- };
26
-
27
- export const validationOptions = {
28
- [issuers.auth0]: {
29
- audience: auth0WebClientID,
30
- jwksUri: `https://${auth0Domain}/.well-known/jwks.json`,
31
- },
32
- [issuers.azure]: {
33
- audience: webClientID,
34
- jwksUri: `https://login.microsoftonline.com/${tenantID}/discovery/v2.0/keys`,
35
- },
36
- };
37
-
38
- export class UserPayload {
39
- aio?: string;
40
- aud?: string;
41
- exp?: number;
42
- iat?: number;
43
- iss?: string;
44
- name?: string;
45
- nbf?: number;
46
- nonce?: string;
47
- oid?: string;
48
- preferred_username?: string;
49
- rh?: string;
50
- sub?: string;
51
- tid?: string;
52
- uti?: string;
53
- ver?: string;
54
- // what about an array of roles???
55
- }
56
-
57
- export const getSigningKeys = (issuer: string) => (header: JwtHeader, cb: SigningKeyCallback) => {
58
- if (!validationOptions[issuer]) {
59
- throw new Error(`No validation options found for issuer ${issuer}`);
60
- }
61
-
62
- const jwksUri = validationOptions[issuer].jwksUri;
63
- if (missingAuth0Config && missingAzureConfig) {
64
- throw new MissingAuthError();
65
- }
66
- if (missingAuth0Config) {
67
- console.warn('Auth0 configuration not found in environment variables');
68
- }
69
- if (missingAzureConfig) {
70
- console.warn('MSAL configuration not found in environment variables');
71
- }
72
-
73
- jwksClient({ jwksUri })
74
- .getSigningKey(header.kid)
75
- .then((key) => {
76
- cb(null, 'publicKey' in key ? key.publicKey : key.rsaPublicKey);
77
- })
78
- .catch((err) => console.error(err));
79
- };
80
-
81
- export const verifyUserRecord = async (email?: string, firstName?: string, lastName?: string, requestDomain?: string, dataSource?: DataSource, attemptCacheUpdateIfNeeded: boolean = true): Promise<UserInfo | undefined> => {
82
- if (!email) return undefined;
83
-
84
- let user = UserCache.Instance.Users.find((u) => {
85
- if (!u.Email || u.Email.trim() === '') {
86
- // this condition should never occur. If it doesn throw a console error including the user id
87
- // DB requires non-null but this is just an extra check and we could in theory have a blank string in the DB
88
- console.error(`SYSTEM METADATA ISSUE: User ${u.ID} has no email address`);
89
- return false;
90
- }
91
- else
92
- return u.Email.toLowerCase().trim() === email.toLowerCase().trim()
93
- });
94
-
95
- if (!user) {
96
- if (configInfo.userHandling.autoCreateNewUsers && firstName && lastName && (requestDomain || configInfo.userHandling.newUserLimitedToAuthorizedDomains === false)) {
97
- // check to see if the domain that we have a request coming in from matches one of the domains in the autoCreateNewUsersDomains setting
98
- let passesDomainCheck: boolean = configInfo.userHandling.newUserLimitedToAuthorizedDomains === false /*in this first condition, we are set up to NOT care about domain */
99
- if (!passesDomainCheck && requestDomain) {
100
- /*in this second condition, we check the domain against authorized domains*/
101
- passesDomainCheck = configInfo.userHandling.newUserAuthorizedDomains.some((pattern) => {
102
- // Convert wildcard domain patterns to regular expressions
103
- const regex = new RegExp('^' + pattern.toLowerCase().trim().replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
104
- return regex.test(requestDomain?.toLowerCase().trim());
105
- });
106
- }
107
-
108
- if (passesDomainCheck) {
109
- // we have a domain from the request that matches one of the domains provided by the configuration, so we will create a new user
110
- console.warn(`User ${email} not found in cache. Attempting to create a new user...`);
111
- const newUserCreator: NewUserBase = <NewUserBase>MJGlobal.Instance.ClassFactory.CreateInstance(NewUserBase); // this will create the object that handles creating the new user for us
112
- const newUser = await newUserCreator.createNewUser(firstName, lastName, email);
113
- if (newUser) {
114
- // new user worked! we already have the stuff we need for the cache, so no need to go to the DB now, just create a new UserInfo object and use the return value from the createNewUser method
115
- // to init it, including passing in the role list for the user.
116
- const initData: any = newUser.GetAll();
117
- initData.UserRoles = configInfo.userHandling.newUserRoles.map((role) => { return { UserID: initData.ID, RoleName: role } });
118
- user = new UserInfo(Metadata.Provider, initData);
119
- UserCache.Instance.Users.push(user);
120
- console.warn(` >>> New user ${email} created successfully!`);
121
- }
122
- }
123
- else {
124
- console.warn(`User ${email} not found in cache. Request domain '${requestDomain}' does not match any of the domains in the newUserAuthorizedDomains setting. To ignore domain, make sure you set the newUserLimitedToAuthorizedDomains setting to false. In this case we are NOT creating a new user.`);
125
- }
126
- }
127
- if(!user && configInfo.userHandling.updateCacheWhenNotFound && dataSource && attemptCacheUpdateIfNeeded) {
128
- // if we get here that means in the above, if we were attempting to create a new user, it did not work, or it wasn't attempted and we have a config that asks us to auto update the cache
129
- console.warn(`User ${email} not found in cache. Updating cache in attempt to find the user...`);
130
-
131
- const startTime: number = Date.now();
132
- await UserCache.Instance.Refresh(dataSource);
133
- const endTime: number = Date.now();
134
- const elapsed: number = endTime - startTime;
135
-
136
- // if elapsed time is less than the delay setting, wait for the additional time to achieve the full delay
137
- // the below also makes sure we never go more than a 30 second total delay
138
- const delay = configInfo.userHandling.updateCacheWhenNotFoundDelay ? (configInfo.userHandling.updateCacheWhenNotFoundDelay < 30000 ? configInfo.userHandling.updateCacheWhenNotFoundDelay : 30000) : 0;
139
- if (elapsed < delay)
140
- await new Promise(resolve => setTimeout(resolve, delay - elapsed));
141
-
142
- const finalTime: number = Date.now();
143
- const finalElapsed: number = finalTime - startTime;
144
-
145
- console.log(` UserCache updated in ${elapsed}ms, total elapsed time of ${finalElapsed}ms including delay of ${delay}ms (if needed). Attempting to find the user again via recursive call to verifyUserRecord()`);
146
- return verifyUserRecord(email, firstName, lastName, requestDomain, dataSource, false) // try one more time but do not update cache next time if not found
147
- }
148
- }
149
-
150
- return user;
151
- };
1
+ import { JwtHeader, SigningKeyCallback } from 'jsonwebtoken';
2
+ import jwksClient from 'jwks-rsa';
3
+ import { auth0Domain, auth0WebClientID, configInfo, tenantID, webClientID } from '../config';
4
+ import { UserCache } from '@memberjunction/sqlserver-dataprovider';
5
+ import { DataSource } from 'typeorm';
6
+ import { Metadata, UserInfo } from '@memberjunction/core';
7
+ import { NewUserBase } from './newUsers';
8
+ import { MJGlobal } from '@memberjunction/global';
9
+
10
+ export * from './tokenExpiredError';
11
+
12
+ const missingAzureConfig = !tenantID || !webClientID;
13
+ const missingAuth0Config = !auth0Domain || !auth0WebClientID;
14
+
15
+ class MissingAuthError extends Error {
16
+ constructor() {
17
+ super('Could not find authentication configuration for either MSAL or Auth0 in the server environment variables.');
18
+ this.name = 'MissingAuthError';
19
+ }
20
+ }
21
+
22
+ const issuers = {
23
+ azure: `https://login.microsoftonline.com/${tenantID}/v2.0`,
24
+ auth0: `https://${auth0Domain}/`,
25
+ };
26
+
27
+ export const validationOptions = {
28
+ [issuers.auth0]: {
29
+ audience: auth0WebClientID,
30
+ jwksUri: `https://${auth0Domain}/.well-known/jwks.json`,
31
+ },
32
+ [issuers.azure]: {
33
+ audience: webClientID,
34
+ jwksUri: `https://login.microsoftonline.com/${tenantID}/discovery/v2.0/keys`,
35
+ },
36
+ };
37
+
38
+ export class UserPayload {
39
+ aio?: string;
40
+ aud?: string;
41
+ exp?: number;
42
+ iat?: number;
43
+ iss?: string;
44
+ name?: string;
45
+ nbf?: number;
46
+ nonce?: string;
47
+ oid?: string;
48
+ preferred_username?: string;
49
+ rh?: string;
50
+ sub?: string;
51
+ tid?: string;
52
+ uti?: string;
53
+ ver?: string;
54
+ // what about an array of roles???
55
+ }
56
+
57
+ export const getSigningKeys = (issuer: string) => (header: JwtHeader, cb: SigningKeyCallback) => {
58
+ if (!validationOptions[issuer]) {
59
+ throw new Error(`No validation options found for issuer ${issuer}`);
60
+ }
61
+
62
+ const jwksUri = validationOptions[issuer].jwksUri;
63
+ if (missingAuth0Config && missingAzureConfig) {
64
+ throw new MissingAuthError();
65
+ }
66
+ if (missingAuth0Config) {
67
+ console.warn('Auth0 configuration not found in environment variables');
68
+ }
69
+ if (missingAzureConfig) {
70
+ console.warn('MSAL configuration not found in environment variables');
71
+ }
72
+
73
+ jwksClient({ jwksUri })
74
+ .getSigningKey(header.kid)
75
+ .then((key) => {
76
+ cb(null, 'publicKey' in key ? key.publicKey : key.rsaPublicKey);
77
+ })
78
+ .catch((err) => console.error(err));
79
+ };
80
+
81
+ export const verifyUserRecord = async (email?: string, firstName?: string, lastName?: string, requestDomain?: string, dataSource?: DataSource, attemptCacheUpdateIfNeeded: boolean = true): Promise<UserInfo | undefined> => {
82
+ if (!email) return undefined;
83
+
84
+ let user = UserCache.Instance.Users.find((u) => {
85
+ if (!u.Email || u.Email.trim() === '') {
86
+ // this condition should never occur. If it doesn throw a console error including the user id
87
+ // DB requires non-null but this is just an extra check and we could in theory have a blank string in the DB
88
+ console.error(`SYSTEM METADATA ISSUE: User ${u.ID} has no email address`);
89
+ return false;
90
+ }
91
+ else
92
+ return u.Email.toLowerCase().trim() === email.toLowerCase().trim()
93
+ });
94
+
95
+ if (!user) {
96
+ if (configInfo.userHandling.autoCreateNewUsers && firstName && lastName && (requestDomain || configInfo.userHandling.newUserLimitedToAuthorizedDomains === false)) {
97
+ // check to see if the domain that we have a request coming in from matches one of the domains in the autoCreateNewUsersDomains setting
98
+ let passesDomainCheck: boolean = configInfo.userHandling.newUserLimitedToAuthorizedDomains === false /*in this first condition, we are set up to NOT care about domain */
99
+ if (!passesDomainCheck && requestDomain) {
100
+ /*in this second condition, we check the domain against authorized domains*/
101
+ passesDomainCheck = configInfo.userHandling.newUserAuthorizedDomains.some((pattern) => {
102
+ // Convert wildcard domain patterns to regular expressions
103
+ const regex = new RegExp('^' + pattern.toLowerCase().trim().replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
104
+ return regex.test(requestDomain?.toLowerCase().trim());
105
+ });
106
+ }
107
+
108
+ if (passesDomainCheck) {
109
+ // we have a domain from the request that matches one of the domains provided by the configuration, so we will create a new user
110
+ console.warn(`User ${email} not found in cache. Attempting to create a new user...`);
111
+ const newUserCreator: NewUserBase = <NewUserBase>MJGlobal.Instance.ClassFactory.CreateInstance(NewUserBase); // this will create the object that handles creating the new user for us
112
+ const newUser = await newUserCreator.createNewUser(firstName, lastName, email);
113
+ if (newUser) {
114
+ // new user worked! we already have the stuff we need for the cache, so no need to go to the DB now, just create a new UserInfo object and use the return value from the createNewUser method
115
+ // to init it, including passing in the role list for the user.
116
+ const initData: any = newUser.GetAll();
117
+ initData.UserRoles = configInfo.userHandling.newUserRoles.map((role) => { return { UserID: initData.ID, RoleName: role } });
118
+ user = new UserInfo(Metadata.Provider, initData);
119
+ UserCache.Instance.Users.push(user);
120
+ console.warn(` >>> New user ${email} created successfully!`);
121
+ }
122
+ }
123
+ else {
124
+ console.warn(`User ${email} not found in cache. Request domain '${requestDomain}' does not match any of the domains in the newUserAuthorizedDomains setting. To ignore domain, make sure you set the newUserLimitedToAuthorizedDomains setting to false. In this case we are NOT creating a new user.`);
125
+ }
126
+ }
127
+ if(!user && configInfo.userHandling.updateCacheWhenNotFound && dataSource && attemptCacheUpdateIfNeeded) {
128
+ // if we get here that means in the above, if we were attempting to create a new user, it did not work, or it wasn't attempted and we have a config that asks us to auto update the cache
129
+ console.warn(`User ${email} not found in cache. Updating cache in attempt to find the user...`);
130
+
131
+ const startTime: number = Date.now();
132
+ await UserCache.Instance.Refresh(dataSource);
133
+ const endTime: number = Date.now();
134
+ const elapsed: number = endTime - startTime;
135
+
136
+ // if elapsed time is less than the delay setting, wait for the additional time to achieve the full delay
137
+ // the below also makes sure we never go more than a 30 second total delay
138
+ const delay = configInfo.userHandling.updateCacheWhenNotFoundDelay ? (configInfo.userHandling.updateCacheWhenNotFoundDelay < 30000 ? configInfo.userHandling.updateCacheWhenNotFoundDelay : 30000) : 0;
139
+ if (elapsed < delay)
140
+ await new Promise(resolve => setTimeout(resolve, delay - elapsed));
141
+
142
+ const finalTime: number = Date.now();
143
+ const finalElapsed: number = finalTime - startTime;
144
+
145
+ console.log(` UserCache updated in ${elapsed}ms, total elapsed time of ${finalElapsed}ms including delay of ${delay}ms (if needed). Attempting to find the user again via recursive call to verifyUserRecord()`);
146
+ return verifyUserRecord(email, firstName, lastName, requestDomain, dataSource, false) // try one more time but do not update cache next time if not found
147
+ }
148
+ }
149
+
150
+ return user;
151
+ };
@@ -1,57 +1,57 @@
1
- import { LogError, Metadata } from "@memberjunction/core";
2
- import { RegisterClass } from "@memberjunction/global";
3
- import { UserCache } from "@memberjunction/sqlserver-dataprovider";
4
- import { configInfo } from "../config";
5
- import { UserEntity, UserRoleEntity } from "@memberjunction/core-entities";
6
-
7
- @RegisterClass(NewUserBase)
8
- export class NewUserBase {
9
- public async createNewUser(firstName: string, lastName: string, email: string, linkedRecordType: string = 'None', linkedEntityId?: number, linkedEntityRecordId?: number) {
10
- try {
11
- const md = new Metadata();
12
- const contextUser = UserCache.Instance.Users.find(u => u.Email.trim().toLowerCase() === configInfo?.userHandling?.contextUserForNewUserCreation?.trim().toLowerCase())
13
- if (!contextUser) {
14
- LogError(`Failed to load context user ${configInfo?.userHandling?.contextUserForNewUserCreation}, if you've not specified this on your config.json you must do so. This is the user that is contextually used for creating a new user record dynamically.`);
15
- return undefined;
16
- }
17
- const u = <UserEntity>await md.GetEntityObject('Users', contextUser) // To-Do - change this to be a different defined user for the user creation process
18
- u.NewRecord();
19
- u.Name = email;
20
- u.IsActive = true;
21
- u.FirstName = firstName;
22
- u.LastName = lastName;
23
- u.Email = email;
24
- u.Type = 'User';
25
- u.LinkedRecordType = linkedRecordType;
26
- if (linkedEntityId)
27
- u.LinkedEntityID = linkedEntityId;
28
- if (linkedEntityRecordId)
29
- u.LinkedEntityRecordID = linkedEntityRecordId;
30
-
31
- if (await u.Save()) {
32
- // user created, now create however many roles we need to create for this user based on the config settings
33
- const ur = <UserRoleEntity>await md.GetEntityObject('User Roles', contextUser);
34
- let bSuccess: boolean = true;
35
- for (const role of configInfo.userHandling.newUserRoles) {
36
- ur.NewRecord();
37
- ur.UserID = u.ID;
38
- ur.RoleName = role;
39
- bSuccess = bSuccess && await ur.Save();
40
- }
41
- if (!bSuccess) {
42
- LogError(`Failed to create roles for newly created user ${firstName} ${lastName} ${email}`);
43
- return undefined;
44
- }
45
- }
46
- else {
47
- LogError(`Failed to create new user ${firstName} ${lastName} ${email}`);
48
- return undefined;
49
- }
50
- return u;
51
- }
52
- catch (e) {
53
- LogError(e);
54
- return undefined;
55
- }
56
- }
1
+ import { LogError, Metadata } from "@memberjunction/core";
2
+ import { RegisterClass } from "@memberjunction/global";
3
+ import { UserCache } from "@memberjunction/sqlserver-dataprovider";
4
+ import { configInfo } from "../config";
5
+ import { UserEntity, UserRoleEntity } from "@memberjunction/core-entities";
6
+
7
+ @RegisterClass(NewUserBase)
8
+ export class NewUserBase {
9
+ public async createNewUser(firstName: string, lastName: string, email: string, linkedRecordType: string = 'None', linkedEntityId?: number, linkedEntityRecordId?: number) {
10
+ try {
11
+ const md = new Metadata();
12
+ const contextUser = UserCache.Instance.Users.find(u => u.Email.trim().toLowerCase() === configInfo?.userHandling?.contextUserForNewUserCreation?.trim().toLowerCase())
13
+ if (!contextUser) {
14
+ LogError(`Failed to load context user ${configInfo?.userHandling?.contextUserForNewUserCreation}, if you've not specified this on your config.json you must do so. This is the user that is contextually used for creating a new user record dynamically.`);
15
+ return undefined;
16
+ }
17
+ const u = <UserEntity>await md.GetEntityObject('Users', contextUser) // To-Do - change this to be a different defined user for the user creation process
18
+ u.NewRecord();
19
+ u.Name = email;
20
+ u.IsActive = true;
21
+ u.FirstName = firstName;
22
+ u.LastName = lastName;
23
+ u.Email = email;
24
+ u.Type = 'User';
25
+ u.LinkedRecordType = linkedRecordType;
26
+ if (linkedEntityId)
27
+ u.LinkedEntityID = linkedEntityId;
28
+ if (linkedEntityRecordId)
29
+ u.LinkedEntityRecordID = linkedEntityRecordId;
30
+
31
+ if (await u.Save()) {
32
+ // user created, now create however many roles we need to create for this user based on the config settings
33
+ const ur = <UserRoleEntity>await md.GetEntityObject('User Roles', contextUser);
34
+ let bSuccess: boolean = true;
35
+ for (const role of configInfo.userHandling.newUserRoles) {
36
+ ur.NewRecord();
37
+ ur.UserID = u.ID;
38
+ ur.RoleName = role;
39
+ bSuccess = bSuccess && await ur.Save();
40
+ }
41
+ if (!bSuccess) {
42
+ LogError(`Failed to create roles for newly created user ${firstName} ${lastName} ${email}`);
43
+ return undefined;
44
+ }
45
+ }
46
+ else {
47
+ LogError(`Failed to create new user ${firstName} ${lastName} ${email}`);
48
+ return undefined;
49
+ }
50
+ return u;
51
+ }
52
+ catch (e) {
53
+ LogError(e);
54
+ return undefined;
55
+ }
56
+ }
57
57
  }
@@ -1,12 +1,12 @@
1
- import { GraphQLError } from 'graphql';
2
-
3
- export class TokenExpiredError extends GraphQLError {
4
- constructor(expiryDate: Date, message = 'The provided token has expired. Please authenticate again.') {
5
- super(message, {
6
- extensions: {
7
- code: 'JWT_EXPIRED',
8
- expiryDate: expiryDate.toISOString(),
9
- },
10
- });
11
- }
12
- }
1
+ import { GraphQLError } from 'graphql';
2
+
3
+ export class TokenExpiredError extends GraphQLError {
4
+ constructor(expiryDate: Date, message = 'The provided token has expired. Please authenticate again.') {
5
+ super(message, {
6
+ extensions: {
7
+ code: 'JWT_EXPIRED',
8
+ expiryDate: expiryDate.toISOString(),
9
+ },
10
+ });
11
+ }
12
+ }
package/src/cache.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { LRUCache } from 'lru-cache';
2
-
3
- const oneHourMs = 60 * 60 * 1000;
4
-
5
- export const authCache = new LRUCache({
6
- max: 50000,
7
- ttl: oneHourMs,
8
- ttlAutopurge: false,
9
- });
10
-
1
+ import { LRUCache } from 'lru-cache';
2
+
3
+ const oneHourMs = 60 * 60 * 1000;
4
+
5
+ export const authCache = new LRUCache({
6
+ max: 50000,
7
+ ttl: oneHourMs,
8
+ ttlAutopurge: false,
9
+ });
10
+
package/src/config.ts CHANGED
@@ -1,84 +1,89 @@
1
- import env from 'env-var';
2
- import fs from 'fs';
3
- import path from 'path';
4
- import { z } from 'zod';
5
-
6
- export const nodeEnv = env.get('NODE_ENV').asString();
7
-
8
- export const dbHost = env.get('DB_HOST').required().asString();
9
- export const dbPort = env.get('DB_PORT').default('1433').asPortNumber();
10
- export const dbUsername = env.get('DB_USERNAME').required().asString();
11
- export const dbPassword = env.get('DB_PASSWORD').required().asString();
12
- export const dbDatabase = env.get('DB_DATABASE').required().asString();
13
- export const dbInstanceName = env.get('DB_INSTANCE_NAME').asString();
14
- export const dbTrustServerCertificate = env.get('DB_TRUST_SERVER_CERTIFICATE').asBool();
15
-
16
- export const graphqlPort = env.get('PORT').default('4000').asPortNumber();
17
- export const graphqlRootPath = env.get('ROOT_PATH').default('/').asString();
18
-
19
- export const webClientID = env.get('WEB_CLIENT_ID').asString();
20
- export const tenantID = env.get('TENANT_ID').asString();
21
-
22
- export const enableIntrospection = env.get('ENABLE_INTROSPECTION').default('false').asBool();
23
- export const websiteRunFromPackage = env.get('WEBSITE_RUN_FROM_PACKAGE').asIntPositive();
24
- export const userEmailMap = env.get('USER_EMAIL_MAP').default('{}').asJsonObject() as Record<string, string>;
25
-
26
- export const ___skipAPIurl = env.get('ASK_SKIP_API_URL').asString();
27
- export const ___skipAPIOrgId = env.get('ASK_SKIP_ORGANIZATION_ID').asString();
28
-
29
- export const auth0Domain = env.get('AUTH0_DOMAIN').asString();
30
- export const auth0WebClientID = env.get('AUTH0_CLIENT_ID').asString();
31
- export const auth0ClientSecret = env.get('AUTH0_CLIENT_SECRET').asString();
32
-
33
- export const mj_core_schema = env.get('MJ_CORE_SCHEMA').asString();
34
-
35
- export const configFile = env.get('CONFIG_FILE').asString();
36
-
37
- const userHandlingInfoSchema = z.object({
38
- autoCreateNewUsers: z.boolean().optional().default(false),
39
- newUserLimitedToAuthorizedDomains: z.boolean().optional().default(false),
40
- newUserAuthorizedDomains: z.array(z.string()).optional().default([]),
41
- newUserRoles: z.array(z.string()).optional().default([]),
42
- updateCacheWhenNotFound: z.boolean().optional().default(false),
43
- updateCacheWhenNotFoundDelay: z.number().optional().default(30000),
44
- contextUserForNewUserCreation: z.string().optional().default(''),
45
- });
46
-
47
- const databaseSettingsInfoSchema = z.object({
48
- connectionTimeout: z.number(),
49
- requestTimeout: z.number(),
50
- metadataCacheRefreshInterval: z.number(),
51
- });
52
-
53
- const viewingSystemInfoSchema = z.object({
54
- enableSmartFilters: z.boolean().optional(),
55
- });
56
-
57
- const askSkipInfoSchema = z.object({
58
- organizationInfo: z.string().optional(),
59
- });
60
-
61
- const configInfoSchema = z.object({
62
- userHandling: userHandlingInfoSchema,
63
- databaseSettings: databaseSettingsInfoSchema,
64
- viewingSystem: viewingSystemInfoSchema.optional(),
65
- askSkip: askSkipInfoSchema.optional(),
66
- });
67
-
68
- export type UserHandlingInfo = z.infer<typeof userHandlingInfoSchema>;
69
- export type DatabaseSettingsInfo = z.infer<typeof databaseSettingsInfoSchema>;
70
- export type ViewingSystemSettingsInfo = z.infer<typeof viewingSystemInfoSchema>;
71
- export type ConfigInfo = z.infer<typeof configInfoSchema>;
72
-
73
- export const configInfo: ConfigInfo = loadConfig();
74
-
75
- export function loadConfig() {
76
- const configPath = configFile ?? path.resolve('config.json');
77
-
78
- if (!fs.existsSync(configPath)) {
79
- throw new Error(`Config file ${configPath} does not exist.`);
80
- }
81
-
82
- const configData = fs.readFileSync(configPath, 'utf-8');
83
- return configInfoSchema.parse(JSON.parse(configData));
84
- }
1
+ import env from 'env-var';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { z } from 'zod';
5
+
6
+ export const nodeEnv = env.get('NODE_ENV').asString();
7
+
8
+ export const dbHost = env.get('DB_HOST').required().asString();
9
+ export const dbPort = env.get('DB_PORT').default('1433').asPortNumber();
10
+ export const dbUsername = env.get('DB_USERNAME').required().asString();
11
+ export const dbPassword = env.get('DB_PASSWORD').required().asString();
12
+ export const dbDatabase = env.get('DB_DATABASE').required().asString();
13
+ export const dbInstanceName = env.get('DB_INSTANCE_NAME').asString();
14
+ export const dbTrustServerCertificate = env.get('DB_TRUST_SERVER_CERTIFICATE').asBool();
15
+
16
+ export const graphqlPort = env.get('PORT').default('4000').asPortNumber();
17
+
18
+ export const ___codeGenAPIURL = env.get('CODEGEN_API_URL').asString();
19
+ export const ___codeGenAPIPort = env.get('CODEGEN_API_PORT').default('3999').asPortNumber();
20
+ export const ___codeGenAPISubmissionDelay = env.get('CODEGEN_API_SUBMISSION_DELAY').default(5000).asIntPositive();
21
+
22
+ export const graphqlRootPath = env.get('ROOT_PATH').default('/').asString();
23
+
24
+ export const webClientID = env.get('WEB_CLIENT_ID').asString();
25
+ export const tenantID = env.get('TENANT_ID').asString();
26
+
27
+ export const enableIntrospection = env.get('ENABLE_INTROSPECTION').default('false').asBool();
28
+ export const websiteRunFromPackage = env.get('WEBSITE_RUN_FROM_PACKAGE').asIntPositive();
29
+ export const userEmailMap = env.get('USER_EMAIL_MAP').default('{}').asJsonObject() as Record<string, string>;
30
+
31
+ export const ___skipAPIurl = env.get('ASK_SKIP_API_URL').asString();
32
+ export const ___skipAPIOrgId = env.get('ASK_SKIP_ORGANIZATION_ID').asString();
33
+
34
+ export const auth0Domain = env.get('AUTH0_DOMAIN').asString();
35
+ export const auth0WebClientID = env.get('AUTH0_CLIENT_ID').asString();
36
+ export const auth0ClientSecret = env.get('AUTH0_CLIENT_SECRET').asString();
37
+
38
+ export const mj_core_schema = env.get('MJ_CORE_SCHEMA').asString();
39
+
40
+ export const configFile = env.get('CONFIG_FILE').asString();
41
+
42
+ const userHandlingInfoSchema = z.object({
43
+ autoCreateNewUsers: z.boolean().optional().default(false),
44
+ newUserLimitedToAuthorizedDomains: z.boolean().optional().default(false),
45
+ newUserAuthorizedDomains: z.array(z.string()).optional().default([]),
46
+ newUserRoles: z.array(z.string()).optional().default([]),
47
+ updateCacheWhenNotFound: z.boolean().optional().default(false),
48
+ updateCacheWhenNotFoundDelay: z.number().optional().default(30000),
49
+ contextUserForNewUserCreation: z.string().optional().default(''),
50
+ });
51
+
52
+ const databaseSettingsInfoSchema = z.object({
53
+ connectionTimeout: z.number(),
54
+ requestTimeout: z.number(),
55
+ metadataCacheRefreshInterval: z.number(),
56
+ });
57
+
58
+ const viewingSystemInfoSchema = z.object({
59
+ enableSmartFilters: z.boolean().optional(),
60
+ });
61
+
62
+ const askSkipInfoSchema = z.object({
63
+ organizationInfo: z.string().optional(),
64
+ });
65
+
66
+ const configInfoSchema = z.object({
67
+ userHandling: userHandlingInfoSchema,
68
+ databaseSettings: databaseSettingsInfoSchema,
69
+ viewingSystem: viewingSystemInfoSchema.optional(),
70
+ askSkip: askSkipInfoSchema.optional(),
71
+ });
72
+
73
+ export type UserHandlingInfo = z.infer<typeof userHandlingInfoSchema>;
74
+ export type DatabaseSettingsInfo = z.infer<typeof databaseSettingsInfoSchema>;
75
+ export type ViewingSystemSettingsInfo = z.infer<typeof viewingSystemInfoSchema>;
76
+ export type ConfigInfo = z.infer<typeof configInfoSchema>;
77
+
78
+ export const configInfo: ConfigInfo = loadConfig();
79
+
80
+ export function loadConfig() {
81
+ const configPath = configFile ?? path.resolve('config.json');
82
+
83
+ if (!fs.existsSync(configPath)) {
84
+ throw new Error(`Config file ${configPath} does not exist.`);
85
+ }
86
+
87
+ const configData = fs.readFileSync(configPath, 'utf-8');
88
+ return configInfoSchema.parse(JSON.parse(configData));
89
+ }