@memberjunction/server 0.9.74 → 0.9.75
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/.eslintignore +4 -4
- package/.eslintrc +24 -24
- package/README.md +141 -141
- package/dist/apolloServer/TransactionPlugin.js +45 -45
- package/dist/apolloServer/index.js +26 -26
- package/dist/auth/exampleNewUserSubClass.js +67 -67
- package/dist/auth/index.js +104 -104
- package/dist/auth/newUsers.js +66 -66
- package/dist/cache.js +10 -10
- package/dist/config.js +61 -61
- package/dist/context.js +101 -101
- package/dist/directives/Public.js +33 -33
- package/dist/directives/index.js +17 -17
- package/dist/entitySubclasses/userViewEntity.server.js +144 -144
- package/dist/index.js +120 -120
- package/dist/orm.js +33 -33
- package/dist/types.js +2 -2
- package/package.json +75 -75
- package/src/apolloServer/TransactionPlugin.ts +54 -54
- package/src/apolloServer/index.ts +33 -33
- package/src/auth/exampleNewUserSubClass.ts +70 -70
- package/src/auth/index.ts +136 -136
- package/src/auth/newUsers.ts +55 -55
- package/src/cache.ts +10 -10
- package/src/config.ts +76 -76
- package/src/context.ts +106 -106
- package/src/directives/Public.ts +42 -42
- package/src/directives/index.ts +1 -1
- package/src/entitySubclasses/userViewEntity.server.ts +156 -156
- package/src/index.ts +111 -111
- package/src/orm.ts +36 -36
- package/src/types.ts +19 -19
|
@@ -1,71 +1,71 @@
|
|
|
1
|
-
import { RegisterClass } from "@memberjunction/global";
|
|
2
|
-
import { Metadata, RunView, LogError } from "@memberjunction/core";
|
|
3
|
-
import { NewUserBase } from "./newUsers";
|
|
4
|
-
import { UserCache } from "@memberjunction/sqlserver-dataprovider";
|
|
5
|
-
import { configInfo } from "../config";
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* This example class subclasses the @NewUserBase class and overrides the createNewUser method to create a new person record and then call the base class to create the user record. In this example there is an entity
|
|
9
|
-
* called "Persons" that is mapped to the User table in the core MemberJunction schema. You can sub-class the NewUserBase to do whatever behavior you want and pre-process, post-process or entirely override the base
|
|
10
|
-
* class behavior.
|
|
11
|
-
*/
|
|
12
|
-
@RegisterClass(NewUserBase, undefined, 1) /*by putting 1 into the priority setting, MJGlobal ClassFactory will use this instead of the base class as that registration had no priority*/
|
|
13
|
-
export class ExampleNewUserSubClass extends NewUserBase {
|
|
14
|
-
public override async createNewUser(firstName: string, lastName: string, email: string) {
|
|
15
|
-
try {
|
|
16
|
-
const md = new Metadata();
|
|
17
|
-
const contextUser = UserCache.Instance.Users.find(u => u.Email.trim().toLowerCase() === configInfo?.userHandling?.contextUserForNewUserCreation?.trim().toLowerCase())
|
|
18
|
-
if(!contextUser) {
|
|
19
|
-
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.`);
|
|
20
|
-
return undefined;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const pEntity = md.Entities.find(e => e.Name === 'Persons'); // look up the entity info for the Persons entity
|
|
24
|
-
if (!pEntity) {
|
|
25
|
-
LogError('Failed to find Persons entity');
|
|
26
|
-
return undefined;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
let personId;
|
|
30
|
-
// this block of code only executes if we have an entity called Persons
|
|
31
|
-
const rv = new RunView();
|
|
32
|
-
const viewResults = await rv.RunView({
|
|
33
|
-
EntityName: 'Persons',
|
|
34
|
-
ExtraFilter: `Email = '${email}'`
|
|
35
|
-
}, contextUser)
|
|
36
|
-
|
|
37
|
-
if (viewResults && viewResults.Success && Array.isArray(viewResults.Results) && viewResults.Results.length > 0) {
|
|
38
|
-
// we have a match so use it
|
|
39
|
-
const row = (viewResults.Results as { ID: number }[])[0]; // we know the rows will have an ID number
|
|
40
|
-
personId = row['ID'];
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
if (!personId) {
|
|
44
|
-
// we don't have a match so create a new person record
|
|
45
|
-
const p = await md.GetEntityObject('Persons', contextUser);
|
|
46
|
-
p.NewRecord(); // assumes we have an entity called Persons that has FirstName/LastName/Email fields
|
|
47
|
-
p.FirstName = firstName;
|
|
48
|
-
p.LastName = lastName;
|
|
49
|
-
p.Email = email;
|
|
50
|
-
p.Status = 'active';
|
|
51
|
-
if (await p.Save()) {
|
|
52
|
-
personId = p.ID;
|
|
53
|
-
}
|
|
54
|
-
else {
|
|
55
|
-
LogError(`Failed to create new person ${firstName} ${lastName} ${email}`)
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// now call the base class to create the user, and pass in our LinkedRecordType and ID
|
|
60
|
-
return super.createNewUser(firstName, lastName, email, 'Other', pEntity?.ID, personId);
|
|
61
|
-
}
|
|
62
|
-
catch (e) {
|
|
63
|
-
LogError(`Error creating new user ${email} ${e}`);
|
|
64
|
-
return undefined;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export function LoadExampleNewUserSubClass() {
|
|
70
|
-
// do nothing, just having this forces the above class to get registered via its @RegisterClass decorator
|
|
1
|
+
import { RegisterClass } from "@memberjunction/global";
|
|
2
|
+
import { Metadata, RunView, LogError } from "@memberjunction/core";
|
|
3
|
+
import { NewUserBase } from "./newUsers";
|
|
4
|
+
import { UserCache } from "@memberjunction/sqlserver-dataprovider";
|
|
5
|
+
import { configInfo } from "../config";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* This example class subclasses the @NewUserBase class and overrides the createNewUser method to create a new person record and then call the base class to create the user record. In this example there is an entity
|
|
9
|
+
* called "Persons" that is mapped to the User table in the core MemberJunction schema. You can sub-class the NewUserBase to do whatever behavior you want and pre-process, post-process or entirely override the base
|
|
10
|
+
* class behavior.
|
|
11
|
+
*/
|
|
12
|
+
@RegisterClass(NewUserBase, undefined, 1) /*by putting 1 into the priority setting, MJGlobal ClassFactory will use this instead of the base class as that registration had no priority*/
|
|
13
|
+
export class ExampleNewUserSubClass extends NewUserBase {
|
|
14
|
+
public override async createNewUser(firstName: string, lastName: string, email: string) {
|
|
15
|
+
try {
|
|
16
|
+
const md = new Metadata();
|
|
17
|
+
const contextUser = UserCache.Instance.Users.find(u => u.Email.trim().toLowerCase() === configInfo?.userHandling?.contextUserForNewUserCreation?.trim().toLowerCase())
|
|
18
|
+
if(!contextUser) {
|
|
19
|
+
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.`);
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const pEntity = md.Entities.find(e => e.Name === 'Persons'); // look up the entity info for the Persons entity
|
|
24
|
+
if (!pEntity) {
|
|
25
|
+
LogError('Failed to find Persons entity');
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let personId;
|
|
30
|
+
// this block of code only executes if we have an entity called Persons
|
|
31
|
+
const rv = new RunView();
|
|
32
|
+
const viewResults = await rv.RunView({
|
|
33
|
+
EntityName: 'Persons',
|
|
34
|
+
ExtraFilter: `Email = '${email}'`
|
|
35
|
+
}, contextUser)
|
|
36
|
+
|
|
37
|
+
if (viewResults && viewResults.Success && Array.isArray(viewResults.Results) && viewResults.Results.length > 0) {
|
|
38
|
+
// we have a match so use it
|
|
39
|
+
const row = (viewResults.Results as { ID: number }[])[0]; // we know the rows will have an ID number
|
|
40
|
+
personId = row['ID'];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (!personId) {
|
|
44
|
+
// we don't have a match so create a new person record
|
|
45
|
+
const p = await md.GetEntityObject('Persons', contextUser);
|
|
46
|
+
p.NewRecord(); // assumes we have an entity called Persons that has FirstName/LastName/Email fields
|
|
47
|
+
p.FirstName = firstName;
|
|
48
|
+
p.LastName = lastName;
|
|
49
|
+
p.Email = email;
|
|
50
|
+
p.Status = 'active';
|
|
51
|
+
if (await p.Save()) {
|
|
52
|
+
personId = p.ID;
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
LogError(`Failed to create new person ${firstName} ${lastName} ${email}`)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// now call the base class to create the user, and pass in our LinkedRecordType and ID
|
|
60
|
+
return super.createNewUser(firstName, lastName, email, 'Other', pEntity?.ID, personId);
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
LogError(`Error creating new user ${email} ${e}`);
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function LoadExampleNewUserSubClass() {
|
|
70
|
+
// do nothing, just having this forces the above class to get registered via its @RegisterClass decorator
|
|
71
71
|
}
|
package/src/auth/index.ts
CHANGED
|
@@ -1,136 +1,136 @@
|
|
|
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
|
-
const missingAzureConfig = !tenantID || !webClientID;
|
|
11
|
-
const missingAuth0Config = !auth0Domain || !auth0WebClientID;
|
|
12
|
-
|
|
13
|
-
class MissingAuthError extends Error {
|
|
14
|
-
constructor() {
|
|
15
|
-
super('Could not find authentication configuration for either MSAL or Auth0 in the server environment variables.');
|
|
16
|
-
this.name = 'MissingAuthError';
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const issuers = {
|
|
21
|
-
azure: `https://login.microsoftonline.com/${tenantID}/v2.0`,
|
|
22
|
-
auth0: `https://${auth0Domain}/`,
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
export const validationOptions = {
|
|
26
|
-
[issuers.auth0]: {
|
|
27
|
-
audience: auth0WebClientID,
|
|
28
|
-
jwksUri: `https://${auth0Domain}/.well-known/jwks.json`,
|
|
29
|
-
},
|
|
30
|
-
[issuers.azure]: {
|
|
31
|
-
audience: webClientID,
|
|
32
|
-
jwksUri: `https://login.microsoftonline.com/${tenantID}/discovery/v2.0/keys`,
|
|
33
|
-
},
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
export class UserPayload {
|
|
37
|
-
aio?: string;
|
|
38
|
-
aud?: string;
|
|
39
|
-
exp?: number;
|
|
40
|
-
iat?: number;
|
|
41
|
-
iss?: string;
|
|
42
|
-
name?: string;
|
|
43
|
-
nbf?: number;
|
|
44
|
-
nonce?: string;
|
|
45
|
-
oid?: string;
|
|
46
|
-
preferred_username?: string;
|
|
47
|
-
rh?: string;
|
|
48
|
-
sub?: string;
|
|
49
|
-
tid?: string;
|
|
50
|
-
uti?: string;
|
|
51
|
-
ver?: string;
|
|
52
|
-
// what about an array of roles???
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export const getSigningKeys = (issuer: string) => (header: JwtHeader, cb: SigningKeyCallback) => {
|
|
56
|
-
const jwksUri = validationOptions[issuer].jwksUri;
|
|
57
|
-
if (missingAuth0Config && missingAzureConfig) {
|
|
58
|
-
throw new MissingAuthError();
|
|
59
|
-
}
|
|
60
|
-
if (missingAuth0Config) {
|
|
61
|
-
console.warn('Auth0 configuration not found in environment variables');
|
|
62
|
-
}
|
|
63
|
-
if (missingAzureConfig) {
|
|
64
|
-
console.warn('MSAL configuration not found in environment variables');
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
jwksClient({ jwksUri })
|
|
68
|
-
.getSigningKey(header.kid)
|
|
69
|
-
.then((key) => {
|
|
70
|
-
cb(null, 'publicKey' in key ? key.publicKey : key.rsaPublicKey);
|
|
71
|
-
})
|
|
72
|
-
.catch((err) => console.error(err));
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
export const verifyUserRecord = async (email?: string, firstName?: string, lastName?: string, requestDomain?: string, dataSource?: DataSource, attemptCacheUpdateIfNeeded: boolean = true): Promise<UserInfo | undefined> => {
|
|
76
|
-
if (!email) return undefined;
|
|
77
|
-
|
|
78
|
-
let user = UserCache.Instance.Users.find((u) => {
|
|
79
|
-
if (!u.Email || u.Email.trim() === '') {
|
|
80
|
-
// this condition should never occur. If it doesn throw a console error including the user id
|
|
81
|
-
// DB requires non-null but this is just an extra check and we could in theory have a blank string in the DB
|
|
82
|
-
console.error(`SYSTEM METADATA ISSUE: User ${u.ID} has no email address`);
|
|
83
|
-
return false;
|
|
84
|
-
}
|
|
85
|
-
else
|
|
86
|
-
return u.Email.toLowerCase().trim() === email.toLowerCase().trim()
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
if (!user) {
|
|
90
|
-
if (configInfo.userHandling.autoCreateNewUsers && firstName && lastName && requestDomain) {
|
|
91
|
-
// check to see if the domain that we have a request coming in from matches one of the domains in the autoCreateNewUsersDomains setting
|
|
92
|
-
const domainMatch: boolean = configInfo.userHandling.newUserAuthorizedDomains.some((domain) => domain.toLowerCase().trim() === requestDomain.toLowerCase().trim());
|
|
93
|
-
if (domainMatch) {
|
|
94
|
-
// we have a domain from the request that matches one of the domains provided by the configuration, so we will create a new user
|
|
95
|
-
console.warn(`User ${email} not found in cache. Attempting to create a new user...`);
|
|
96
|
-
const newUserCreator: NewUserBase = <NewUserBase>MJGlobal.Instance.ClassFactory.CreateInstance(NewUserBase); // this will create the object that handles creating the new user for us
|
|
97
|
-
const newUser = await newUserCreator.createNewUser(firstName, lastName, email);
|
|
98
|
-
if (newUser) {
|
|
99
|
-
// 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
|
|
100
|
-
// to init it, including passing in the role list for the user.
|
|
101
|
-
const initData: any = newUser.GetAll();
|
|
102
|
-
initData.UserRoles = configInfo.userHandling.newUserRoles.map((role) => { return { UserID: initData.ID, RoleName: role } });
|
|
103
|
-
user = new UserInfo(Metadata.Provider, initData);
|
|
104
|
-
UserCache.Instance.Users.push(user);
|
|
105
|
-
console.warn(` >>> New user ${email} created successfully!`);
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
else {
|
|
109
|
-
console.warn(`User ${email} not found in cache. Request domain '${requestDomain}' does not match any of the domains in the newUserAuthorizedDomains setting. NOT creating a new user.`);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
if(!user && configInfo.userHandling.updateCacheWhenNotFound && dataSource && attemptCacheUpdateIfNeeded) {
|
|
113
|
-
// 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
|
|
114
|
-
console.warn(`User ${email} not found in cache. Updating cache in attempt to find the user...`);
|
|
115
|
-
|
|
116
|
-
const startTime: number = Date.now();
|
|
117
|
-
await UserCache.Instance.Refresh(dataSource);
|
|
118
|
-
const endTime: number = Date.now();
|
|
119
|
-
const elapsed: number = endTime - startTime;
|
|
120
|
-
|
|
121
|
-
// if elapsed time is less than the delay setting, wait for the additional time to achieve the full delay
|
|
122
|
-
// the below also makes sure we never go more than a 30 second total delay
|
|
123
|
-
const delay = configInfo.userHandling.updateCacheWhenNotFoundDelay ? (configInfo.userHandling.updateCacheWhenNotFoundDelay < 30000 ? configInfo.userHandling.updateCacheWhenNotFoundDelay : 30000) : 0;
|
|
124
|
-
if (elapsed < delay)
|
|
125
|
-
await new Promise(resolve => setTimeout(resolve, delay - elapsed));
|
|
126
|
-
|
|
127
|
-
const finalTime: number = Date.now();
|
|
128
|
-
const finalElapsed: number = finalTime - startTime;
|
|
129
|
-
|
|
130
|
-
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()`);
|
|
131
|
-
return verifyUserRecord(email, firstName, lastName, requestDomain, dataSource, false) // try one more time but do not update cache next time if not found
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
return user;
|
|
136
|
-
};
|
|
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
|
+
const missingAzureConfig = !tenantID || !webClientID;
|
|
11
|
+
const missingAuth0Config = !auth0Domain || !auth0WebClientID;
|
|
12
|
+
|
|
13
|
+
class MissingAuthError extends Error {
|
|
14
|
+
constructor() {
|
|
15
|
+
super('Could not find authentication configuration for either MSAL or Auth0 in the server environment variables.');
|
|
16
|
+
this.name = 'MissingAuthError';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const issuers = {
|
|
21
|
+
azure: `https://login.microsoftonline.com/${tenantID}/v2.0`,
|
|
22
|
+
auth0: `https://${auth0Domain}/`,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export const validationOptions = {
|
|
26
|
+
[issuers.auth0]: {
|
|
27
|
+
audience: auth0WebClientID,
|
|
28
|
+
jwksUri: `https://${auth0Domain}/.well-known/jwks.json`,
|
|
29
|
+
},
|
|
30
|
+
[issuers.azure]: {
|
|
31
|
+
audience: webClientID,
|
|
32
|
+
jwksUri: `https://login.microsoftonline.com/${tenantID}/discovery/v2.0/keys`,
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export class UserPayload {
|
|
37
|
+
aio?: string;
|
|
38
|
+
aud?: string;
|
|
39
|
+
exp?: number;
|
|
40
|
+
iat?: number;
|
|
41
|
+
iss?: string;
|
|
42
|
+
name?: string;
|
|
43
|
+
nbf?: number;
|
|
44
|
+
nonce?: string;
|
|
45
|
+
oid?: string;
|
|
46
|
+
preferred_username?: string;
|
|
47
|
+
rh?: string;
|
|
48
|
+
sub?: string;
|
|
49
|
+
tid?: string;
|
|
50
|
+
uti?: string;
|
|
51
|
+
ver?: string;
|
|
52
|
+
// what about an array of roles???
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const getSigningKeys = (issuer: string) => (header: JwtHeader, cb: SigningKeyCallback) => {
|
|
56
|
+
const jwksUri = validationOptions[issuer].jwksUri;
|
|
57
|
+
if (missingAuth0Config && missingAzureConfig) {
|
|
58
|
+
throw new MissingAuthError();
|
|
59
|
+
}
|
|
60
|
+
if (missingAuth0Config) {
|
|
61
|
+
console.warn('Auth0 configuration not found in environment variables');
|
|
62
|
+
}
|
|
63
|
+
if (missingAzureConfig) {
|
|
64
|
+
console.warn('MSAL configuration not found in environment variables');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
jwksClient({ jwksUri })
|
|
68
|
+
.getSigningKey(header.kid)
|
|
69
|
+
.then((key) => {
|
|
70
|
+
cb(null, 'publicKey' in key ? key.publicKey : key.rsaPublicKey);
|
|
71
|
+
})
|
|
72
|
+
.catch((err) => console.error(err));
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export const verifyUserRecord = async (email?: string, firstName?: string, lastName?: string, requestDomain?: string, dataSource?: DataSource, attemptCacheUpdateIfNeeded: boolean = true): Promise<UserInfo | undefined> => {
|
|
76
|
+
if (!email) return undefined;
|
|
77
|
+
|
|
78
|
+
let user = UserCache.Instance.Users.find((u) => {
|
|
79
|
+
if (!u.Email || u.Email.trim() === '') {
|
|
80
|
+
// this condition should never occur. If it doesn throw a console error including the user id
|
|
81
|
+
// DB requires non-null but this is just an extra check and we could in theory have a blank string in the DB
|
|
82
|
+
console.error(`SYSTEM METADATA ISSUE: User ${u.ID} has no email address`);
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
else
|
|
86
|
+
return u.Email.toLowerCase().trim() === email.toLowerCase().trim()
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
if (!user) {
|
|
90
|
+
if (configInfo.userHandling.autoCreateNewUsers && firstName && lastName && requestDomain) {
|
|
91
|
+
// check to see if the domain that we have a request coming in from matches one of the domains in the autoCreateNewUsersDomains setting
|
|
92
|
+
const domainMatch: boolean = configInfo.userHandling.newUserAuthorizedDomains.some((domain) => domain.toLowerCase().trim() === requestDomain.toLowerCase().trim());
|
|
93
|
+
if (domainMatch) {
|
|
94
|
+
// we have a domain from the request that matches one of the domains provided by the configuration, so we will create a new user
|
|
95
|
+
console.warn(`User ${email} not found in cache. Attempting to create a new user...`);
|
|
96
|
+
const newUserCreator: NewUserBase = <NewUserBase>MJGlobal.Instance.ClassFactory.CreateInstance(NewUserBase); // this will create the object that handles creating the new user for us
|
|
97
|
+
const newUser = await newUserCreator.createNewUser(firstName, lastName, email);
|
|
98
|
+
if (newUser) {
|
|
99
|
+
// 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
|
|
100
|
+
// to init it, including passing in the role list for the user.
|
|
101
|
+
const initData: any = newUser.GetAll();
|
|
102
|
+
initData.UserRoles = configInfo.userHandling.newUserRoles.map((role) => { return { UserID: initData.ID, RoleName: role } });
|
|
103
|
+
user = new UserInfo(Metadata.Provider, initData);
|
|
104
|
+
UserCache.Instance.Users.push(user);
|
|
105
|
+
console.warn(` >>> New user ${email} created successfully!`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
console.warn(`User ${email} not found in cache. Request domain '${requestDomain}' does not match any of the domains in the newUserAuthorizedDomains setting. NOT creating a new user.`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if(!user && configInfo.userHandling.updateCacheWhenNotFound && dataSource && attemptCacheUpdateIfNeeded) {
|
|
113
|
+
// 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
|
|
114
|
+
console.warn(`User ${email} not found in cache. Updating cache in attempt to find the user...`);
|
|
115
|
+
|
|
116
|
+
const startTime: number = Date.now();
|
|
117
|
+
await UserCache.Instance.Refresh(dataSource);
|
|
118
|
+
const endTime: number = Date.now();
|
|
119
|
+
const elapsed: number = endTime - startTime;
|
|
120
|
+
|
|
121
|
+
// if elapsed time is less than the delay setting, wait for the additional time to achieve the full delay
|
|
122
|
+
// the below also makes sure we never go more than a 30 second total delay
|
|
123
|
+
const delay = configInfo.userHandling.updateCacheWhenNotFoundDelay ? (configInfo.userHandling.updateCacheWhenNotFoundDelay < 30000 ? configInfo.userHandling.updateCacheWhenNotFoundDelay : 30000) : 0;
|
|
124
|
+
if (elapsed < delay)
|
|
125
|
+
await new Promise(resolve => setTimeout(resolve, delay - elapsed));
|
|
126
|
+
|
|
127
|
+
const finalTime: number = Date.now();
|
|
128
|
+
const finalElapsed: number = finalTime - startTime;
|
|
129
|
+
|
|
130
|
+
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()`);
|
|
131
|
+
return verifyUserRecord(email, firstName, lastName, requestDomain, dataSource, false) // try one more time but do not update cache next time if not found
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return user;
|
|
136
|
+
};
|
package/src/auth/newUsers.ts
CHANGED
|
@@ -1,56 +1,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
|
-
|
|
6
|
-
@RegisterClass(NewUserBase)
|
|
7
|
-
export class NewUserBase {
|
|
8
|
-
public async createNewUser(firstName: string, lastName: string, email: string, linkedRecordType: string = 'None', linkedEntityId?: number, linkedEntityRecordId?: number) {
|
|
9
|
-
try {
|
|
10
|
-
const md = new Metadata();
|
|
11
|
-
const contextUser = UserCache.Instance.Users.find(u => u.Email.trim().toLowerCase() === configInfo?.userHandling?.contextUserForNewUserCreation?.trim().toLowerCase())
|
|
12
|
-
if (!contextUser) {
|
|
13
|
-
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.`);
|
|
14
|
-
return undefined;
|
|
15
|
-
}
|
|
16
|
-
const u = await md.GetEntityObject('Users', contextUser) // To-Do - change this to be a different defined user for the user creation process
|
|
17
|
-
u.NewRecord();
|
|
18
|
-
u.Name = email;
|
|
19
|
-
u.IsActive = true;
|
|
20
|
-
u.FirstName = firstName;
|
|
21
|
-
u.LastName = lastName;
|
|
22
|
-
u.Email = email;
|
|
23
|
-
u.Type = 'User';
|
|
24
|
-
u.LinkedRecordType = linkedRecordType;
|
|
25
|
-
if (linkedEntityId)
|
|
26
|
-
u.LinkedEntityID = linkedEntityId;
|
|
27
|
-
if (linkedEntityRecordId)
|
|
28
|
-
u.LinkedEntityRecordID = linkedEntityRecordId;
|
|
29
|
-
|
|
30
|
-
if (await u.Save()) {
|
|
31
|
-
// user created, now create however many roles we need to create for this user based on the config settings
|
|
32
|
-
const ur = await md.GetEntityObject('User Roles', contextUser);
|
|
33
|
-
let bSuccess: boolean = true;
|
|
34
|
-
for (const role of configInfo.userHandling.newUserRoles) {
|
|
35
|
-
ur.NewRecord();
|
|
36
|
-
ur.UserID = u.ID;
|
|
37
|
-
ur.RoleName = role;
|
|
38
|
-
bSuccess = bSuccess && await ur.Save();
|
|
39
|
-
}
|
|
40
|
-
if (!bSuccess) {
|
|
41
|
-
LogError(`Failed to create roles for newly created user ${firstName} ${lastName} ${email}`);
|
|
42
|
-
return undefined;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
else {
|
|
46
|
-
LogError(`Failed to create new user ${firstName} ${lastName} ${email}`);
|
|
47
|
-
return undefined;
|
|
48
|
-
}
|
|
49
|
-
return u;
|
|
50
|
-
}
|
|
51
|
-
catch (e) {
|
|
52
|
-
LogError(e);
|
|
53
|
-
return undefined;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
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
|
+
|
|
6
|
+
@RegisterClass(NewUserBase)
|
|
7
|
+
export class NewUserBase {
|
|
8
|
+
public async createNewUser(firstName: string, lastName: string, email: string, linkedRecordType: string = 'None', linkedEntityId?: number, linkedEntityRecordId?: number) {
|
|
9
|
+
try {
|
|
10
|
+
const md = new Metadata();
|
|
11
|
+
const contextUser = UserCache.Instance.Users.find(u => u.Email.trim().toLowerCase() === configInfo?.userHandling?.contextUserForNewUserCreation?.trim().toLowerCase())
|
|
12
|
+
if (!contextUser) {
|
|
13
|
+
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.`);
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
const u = await md.GetEntityObject('Users', contextUser) // To-Do - change this to be a different defined user for the user creation process
|
|
17
|
+
u.NewRecord();
|
|
18
|
+
u.Name = email;
|
|
19
|
+
u.IsActive = true;
|
|
20
|
+
u.FirstName = firstName;
|
|
21
|
+
u.LastName = lastName;
|
|
22
|
+
u.Email = email;
|
|
23
|
+
u.Type = 'User';
|
|
24
|
+
u.LinkedRecordType = linkedRecordType;
|
|
25
|
+
if (linkedEntityId)
|
|
26
|
+
u.LinkedEntityID = linkedEntityId;
|
|
27
|
+
if (linkedEntityRecordId)
|
|
28
|
+
u.LinkedEntityRecordID = linkedEntityRecordId;
|
|
29
|
+
|
|
30
|
+
if (await u.Save()) {
|
|
31
|
+
// user created, now create however many roles we need to create for this user based on the config settings
|
|
32
|
+
const ur = await md.GetEntityObject('User Roles', contextUser);
|
|
33
|
+
let bSuccess: boolean = true;
|
|
34
|
+
for (const role of configInfo.userHandling.newUserRoles) {
|
|
35
|
+
ur.NewRecord();
|
|
36
|
+
ur.UserID = u.ID;
|
|
37
|
+
ur.RoleName = role;
|
|
38
|
+
bSuccess = bSuccess && await ur.Save();
|
|
39
|
+
}
|
|
40
|
+
if (!bSuccess) {
|
|
41
|
+
LogError(`Failed to create roles for newly created user ${firstName} ${lastName} ${email}`);
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
LogError(`Failed to create new user ${firstName} ${lastName} ${email}`);
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
return u;
|
|
50
|
+
}
|
|
51
|
+
catch (e) {
|
|
52
|
+
LogError(e);
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
56
|
}
|
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
|
+
|