This repository has been archived by the owner on May 12, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
MA_SetupAuthWizardPage.page
422 lines (354 loc) · 22.7 KB
/
MA_SetupAuthWizardPage.page
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
<!--
Author: Doug Ayers
Website: https://douglascayers.com
GitHub: https://github.com/sfdx-mass-action-scheduler/sfdx-mass-action-scheduler
License: BSD 3-Clause License
-->
<apex:page controller="MA_SetupAuthWizardPageController">
<apex:slds />
<apex:includeScript value="{!URLFOR($Resource.jsforce)}"/>
<apex:includeScript value="{!URLFOR($Resource.jquery)}"/>
<script>$j = jQuery.noConflict();</script>
<div class="slds-scope">
<apex:form id="theForm" styleClass="slds-p-around_large">
<apex:pageMessages />
<div id="spinner" class="slds-hide">
<div class="slds-spinner_container" style="position:fixed">
<div role="status" class="slds-spinner slds-spinner_medium slds-spinner_brand">
<span class="slds-assistive-text">Loading</span>
<div class="slds-spinner__dot-a"></div>
<div class="slds-spinner__dot-b"></div>
</div>
</div>
</div>
<div class="slds-page-header slds-m-bottom_large">
<div class="slds-grid">
<div class="slds-col slds-has-flexi-truncate">
<div class="slds-media slds-no-space slds-grow">
<div class="slds-media__body">
<nav>
<ol class="slds-breadcrumb slds-line-height_reset">
<li class="slds-breadcrumb__item">
<span>Mass Action Scheduler</span>
</li>
</ol>
</nav>
<h1 class="slds-page-header__title slds-m-right_small slds-align-middle slds-truncate">
Authentication Setup Wizard
</h1>
</div>
</div>
</div>
<div class="slds-col slds-no-flex slds-grid slds-align-top">
<div class="slds-button-group" role="group">
<!--<apex:commandButton value=" Create Metadata " onclick="createMetadata(); return false;" styleClass="slds-button slds-button_neutral"/>-->
</div>
</div>
</div>
</div>
<div class="slds-card slds-p-around_card-wrapper-spacing">
<div class="slds-grid">
<div class="slds-col slds-shrink-none">
<apex:image value="{!URLFOR($Resource.MA_SalesforceSecurityLogo)}"/>
</div>
<div class="slds-col slds-m-horizontal_large slds-p-top_small">
<div class="slds-text-heading_medium">1. Usage</div>
<p class="slds-p-bottom_medium">
Mass Action Scheduler uses the <a href="https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_what_is_rest_api.htm" target="_blank" rel="noopener noreferrer">Salesforce REST API</a>
to provide you a robust configuration wizard as well as
to invoke your Flows, Processes, Quick Actions, Apex, and Workflow Rules per your defined schedules.
</p>
<div class="slds-text-heading_medium">2. Security Requirements</div>
<p class="slds-p-bottom_medium">
For security purposes, Salesforce requires Lightning Components to
<a href="https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_authentication.htm" target="_blank" rel="noopener noreferrer">authenticate</a> to the Salesforce REST API
through <a href="https://help.salesforce.com/articleView?id=remoteaccess_authenticate.htm&type=5" target="_blank" rel="noopener noreferrer">OAuth</a>
via <a href="https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_api_calls.htm" target="_blank" rel="noopener noreferrer">Apex</a>.
As a Salesforce Admin, you satisfy these requirements by declaratively creating a
<a href="https://help.salesforce.com/articleView?id=connected_app_overview.htm&type=5" target="_blank" rel="noopener noreferrer">Connected App</a>,
<a href="https://help.salesforce.com/articleView?id=sso_provider_sfdc.htm&type=5" target="_blank" rel="noopener noreferrer">Auth. Provider</a>, and
<a href="https://help.salesforce.com/articleView?id=named_credentials_about.htm&type=5" target="_blank" rel="noopener noreferrer">Named Credential</a>.
These metadata components also ensure that custom apps, like Mass Action Scheduler, never actually receive or know your Salesforce password
and that you have explicitly authorized the app to perform Salesforce operations on your behalf. For example, to run a flow at 5am while you are sleeping 🙂
</p>
<div class="slds-text-heading_medium">3a. Manual Setup</div>
<p class="slds-p-bottom_medium">
The manual setup of the Connected App, Auth. Provider, and Named Credential is several clicks and copying and pasting very long and specific values between forms.
This is the primary complaint and barrier to adoption of the Mass Action Scheduler app.
Therefore, the automated setup option is recommended and provided as a convenience.
However, if desired, you can create these items manually by following the instructions on the <a href="https://github.com/sfdx-mass-action-scheduler/sfdx-mass-action-scheduler/wiki/Specify-the-Running-User-via-Named-Credentials">project wiki page</a>.
</p>
<div class="slds-text-heading_medium">3b. Automated Setup</div>
<p class="slds-p-bottom_medium">
This setup wizard will automatically configure the
<a href="https://help.salesforce.com/articleView?id=connected_app_overview.htm&type=5" target="_blank" rel="noopener noreferrer">Connected App</a>,
<a href="https://help.salesforce.com/articleView?id=sso_provider_sfdc.htm&type=5" target="_blank" rel="noopener noreferrer">Auth. Provider</a>, and
<a href="https://help.salesforce.com/articleView?id=named_credentials_about.htm&type=5" target="_blank" rel="noopener noreferrer">Named Credential</a>
metadata required for Mass Action Scheduler to access the Salesforce REST API.
The metadata will be created with the names <b>Mass_Action</b>.
</p>
<p class="slds-p-bottom_medium">
<apex:commandButton value=" Create Connected App, Auth. Provider, and Named Credential " onclick="createMetadata(); return false;" styleClass="slds-button slds-button_brand"/>
</p>
<p class="slds-p-bottom_medium">
<div id="message-template" class="slds-hide">
<div class="slds-notify_container slds-is-relative">
<div class="slds-notify slds-notify_toast slds-theme_error slds-theme_alert-texture" role="alert">
<span class="slds-assistive-text">error</span>
<div class="slds-notify__content">
<h2 class="slds-text-heading_small "><span class="message-content">test</span></h2>
</div>
<button class="slds-button slds-notify__close slds-button_icon-inverse" title="Close" onclick="clearMessages(); return false;">
X
<span class="slds-assistive-text">Close</span>
</button>
</div>
</div>
</div>
<div id="messages"><!-- populated by javascript --></div>
</p>
<div class="slds-text-heading_medium">4. Post Setup</div>
<p class="slds-p-bottom_medium">
<ol class="slds-list_ordered" style="list-style-type: lower-alpha;">
<li class="slds-var-m-vertical_small">
<b>Wait 10 minutes</b> for the Connected App to become available to the Salesforce login servers, otherwise you will get error <span class="slds-text-color_error">invalid_client_id</span> in step 4b.
</li>
<li class="slds-var-m-vertical_small">
In Setup, go to the <a href="/lightning/setup/NamedCredential/home" target="_blank" rel="noopener noreferrer">Named Credential</a> record,
click <b>Edit</b>, ensure the <b>Start Authentication Flow on Save</b> checkbox is selected, then click <b>Save</b>.
</li>
<li class="slds-var-m-vertical_small">
Salesforce will prompt you to log in with the user credentials you want Mass Action Scheduler app to use.
On the login page, click <b>Use Custom Domain</b> and enter <span id="post-setup-custom-domain">your org's My Domain</span>.
</li>
<li class="slds-var-m-vertical_small">
Upon logging in Salesforce will prompt you to authorize Mass Action Scheduler app to perform requests on your behalf.
At no time will Mass Action Scheduler app be provided your <i>actual</i> Salesforce password, which is a purpose of these security requirements.
</li>
</ol>
Once you have done this final step, then you are ready to create your own <a href="{!URLFOR( $Action.Mass_Action_Configuration__c.New )}">Mass Action Configurations</a> to
declaratively schedule Process Builder, Flows, Quick Actions, Email Alerts, Workflow Rules, and Apex to process records from Reports and List Views.
</p>
<hr/>
<div class="slds-text-heading_medium">Troubleshooting Automated Setup Errors</div>
<p class="slds-p-bottom_medium">
<div class="slds-text-heading_small slds-text-color_error">error: duplicate value found</div>
<p class="slds-p-bottom_small">
This error means a Connected App or Named Credential already exists with the unique name <b>Mass_Action</b>.
This may occur if you have already created the metadata manually or have already used the automated setup.
</p>
<div class="slds-text-heading_small slds-text-color_error">error=This URL Suffix already exists or has been previously used</div>
<p class="slds-p-bottom_small">
This error means an Auth. Provider already exists with the unique name <b>Mass_Action</b>.
This may occur if you have already created the metadata manually or have already used the automated setup.
</p>
<div class="slds-text-heading_small slds-text-color_error">error=invalid_client_id</div>
<p class="slds-p-bottom_small">
This error can occur when you save the newly created Named Credential to complete the authentication flow
and Salesforce has not completed syncing the changes to the login servers.
Wait 10 minutes then try again. If the issue continues, then delete and re-create the
Connected App, Auth. Provider, and Named Credential.
</p>
<div class="slds-text-heading_small slds-text-color_error">Problem Logging In: No CSRF cookie</div>
<p class="slds-p-bottom_small">
In step 4c, when you re-save the Named Credential to provide your credentials, you might get an error
on the first attempt about <b>CSRF: No CSRF cookie</b>. Make sure you enter your Custom Domain on the
Salesforce login page. Re-navigate back to the Named Credential in Setup menu and try again.
</p>
</p>
</div>
</div>
</div>
</apex:form>
</div>
<script>
var conn = new jsforce.Connection({
accessToken : '{!$Api.Session_Id}',
version : '54.0'
});
// When creating a connected app, the consumer key and secret must be plain text.
// http://releasenotes.docs.salesforce.com/en-us/spring19/release-notes/rn_identity_client_secret_resize.htm
const consumerKey = getRandomLetters( 85 );
const consumerSecret = getRandomString( 64, true, false, true, false );
function createMetadata() {
$j( '#spinner' ).removeClass( 'slds-hide' );
clearMessages();
Promise.resolve()
.then( function() {
let label = 'Mass Action';
let fullName = 'Mass_Action';
let orgDomainURL = '{!orgDomainURL}';
let myDomain = '{!myDomain}';
// update instructions with exact domain the user should enter to remove guesswork
$j( '#post-setup-custom-domain' ).html( `<code>${myDomain}</code>` );
return conn.metadata.create( 'ConnectedApp', buildConnectedApp( label, fullName, orgDomainURL, consumerKey, consumerSecret ) )
.then( function( result ) {
validateMetadataSaveResult( 'ConnectedApp', result );
showMessage( 'Connected App created with name "' + fullName + '"', 'SUCCESS' );
return conn.metadata.create( 'AuthProvider', buildAuthProvider( label, fullName, orgDomainURL, consumerKey, consumerSecret ) );
})
.then( function( result ) {
validateMetadataSaveResult( 'AuthProvider', result );
showMessage( 'Auth. Provider created with URL Suffix "' + fullName + '"', 'SUCCESS' );
return conn.metadata.create( 'NamedCredential', buildNamedCredential( label, fullName, orgDomainURL ) );
})
.then( function( result ) {
validateMetadataSaveResult( 'NamedCredential', result );
showMessage( 'Named Credential created with name "' + fullName + '"', 'SUCCESS' );
return conn.query( 'SELECT Id FROM NamedCredential WHERE DeveloperName = \'' + fullName + '\' LIMIT 1' );
})
.then( function( result ) {
console.log( result );
showMessage( 'Wait <b>10 minutes</b> then complete authentication flow by <a href="/lightning/setup/NamedCredential/page?address=%2F' + result.records[0].Id + '%2Fe" target="_blank" rel="noopener noreferrer">re-saving the Named Credential</a>', 'WARNING' );
});
})
.catch( function( err ) {
console.error( err );
showMessage( err.message, 'ERROR' );
})
.then( function() {
$j( '#spinner' ).addClass( 'slds-hide' );
});
}
function buildConnectedApp( label, fullName, orgDomainURL, consumerKey, consumerSecret ) {
return {
fullName : fullName,
label : label,
description : 'Auto-generated for Mass Action Scheduler using the app\'s Authentication Setup Wizard.',
contactEmail : '{!$User.Email}',
oauthConfig : {
callbackUrl : orgDomainURL + '/services/authcallback/' + fullName,
consumerKey : consumerKey,
consumerSecret : consumerSecret,
scopes : [
'Full',
'RefreshToken'
]
}
};
}
function buildAuthProvider( label, fullName, orgDomainURL, consumerKey, consumerSecret ) {
return {
fullName : fullName,
friendlyName : label,
includeOrgIdInIdentifier : true,
providerType : 'Salesforce',
consumerKey : consumerKey,
consumerSecret : consumerSecret
};
}
function buildNamedCredential( label, fullName, orgDomainURL ) {
return {
fullName : fullName,
label : label,
authProvider : fullName,
endpoint : orgDomainURL,
oauthScope : 'full refresh_token',
principalType : 'NamedUser',
protocol : 'Oauth',
allowMergeFieldsInHeader : true,
allowMergeFieldsInBody : true
};
}
/**
* Validates the metadata save result.
* If success is false, then throws error.
*
* @param type the metadata type (e.g. NamedCredential, CustomObject)
* @param result the save result
*/
function validateMetadataSaveResult( type, result ) {
console.log( 'validating metadata save result: type=' + type + ', fullName=' + result.fullName );
console.log( result );
if ( !result.success ) {
var message = 'type=' + type + ', name=' + result.fullName + ', error=' + result.errors.message;
throw new Error( message );
}
}
/**
* Shows a dismissable message notification at top of page.
*
* @param message text to display
* @param severity SUCCESS, ERROR
*/
function showMessage( message, severity ) {
var newMessage = $j( '#message-template' ).children().clone();
$j( newMessage ).find( 'div[role="alert"]' )
.removeClass( 'slds-theme_error' )
.removeClass( 'slds-theme_success' )
.addClass( 'slds-theme_' + severity.toLowerCase() );
$j( newMessage ).removeClass( 'slds-hide' );
$j( newMessage ).find( '.message-content' ).html( message );
$j( newMessage ).find( '.slds-assistive-text' ).text( severity );
$j( '#messages' ).append( newMessage );
}
function clearMessages() {
$j( '#messages' ).empty();
}
// ----------------------------------------------------------
function getRandomLetters( num ) {
return getRandomString( num, true, true, false, false );
}
function getRandomNumbers( num ) {
return getRandomString( num, false, false, true, false );
}
/**
* Generates a random string.
*
* @param num number of characters to generate
* @param includeUpperCase A-Z
* @param includeLowerCase a-z
* @param includeDigits 0-9
* @param includeSymbols !@#$%^&*()
* @returns {string}
*/
function getRandomString( num, includeUpperCase, includeLowerCase, includeDigits, includeSymbols ) {
var CHARS = '';
if ( includeUpperCase ) {
CHARS += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
if ( includeLowerCase ) {
CHARS += 'abcdefghijklmnopqrstuvwxyz';
}
if ( includeDigits ) {
CHARS += '0123456789';
}
if ( includeSymbols ) {
CHARS += '!@#$%^&*()';
}
var randomNumbers = new Uint32Array( num );
window.crypto.getRandomValues( randomNumbers ); // fills array with random values
var text = '';
randomNumbers.forEach( function( number ) {
var idx = ( number % CHARS.length );
text += CHARS.substring( idx, idx + 1 );
});
return text;
}
</script>
</apex:page>
<!--
BSD 3-Clause License
Copyright (c) 2017-2023, Doug Ayers, douglascayers.com
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->