|
| 1 | +(function() { |
| 2 | + |
| 3 | + // Configuration via system properties |
| 4 | + var warningDays = parseInt(gs.getProperty('api.token.expiry.warning.days', '7'), 10); // Days before expiry to warn |
| 5 | + var emailRecipients = gs.getProperty('api.token.expiry.email.recipients', 'admin@example.com'); // Comma-separated emails |
| 6 | + |
| 7 | + // Current time and warning threshold time |
| 8 | + var now = new GlideDateTime(); |
| 9 | + var warningDate = new GlideDateTime(); |
| 10 | + warningDate.addDays(warningDays); |
| 11 | + |
| 12 | + // Query oauth_credential records with expires_on between now and warningDate |
| 13 | + var gr = new GlideRecord('oauth_credential'); |
| 14 | + gr.addQuery('expires_on', '>=', now); |
| 15 | + gr.addQuery('expires_on', '<=', warningDate); |
| 16 | + gr.addQuery('active', '=', true); // Only active tokens |
| 17 | + gr.orderBy('expires_on'); |
| 18 | + gr.query(); |
| 19 | + |
| 20 | + if (!gr.hasNext()) { |
| 21 | + gs.info('No OAuth credentials nearing expiry within ' + warningDays + ' days.'); |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + // Build notification email body |
| 26 | + var emailBody = '<h3>API Token Expiry Warning</h3>'; |
| 27 | + emailBody += '<p>The following OAuth credentials are set to expire within ' + warningDays + ' days:</p>'; |
| 28 | + emailBody += '<table border="1" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">'; |
| 29 | + emailBody += '<tr><th>Name</th><th>User</th><th>Client ID</th><th>Expires On</th></tr>'; |
| 30 | + |
| 31 | + while (gr.next()) { |
| 32 | + emailBody += '<tr>'; |
| 33 | + emailBody += '<td>' + gr.getDisplayValue('name') + '</td>'; |
| 34 | + emailBody += '<td>' + gr.getDisplayValue('user') + '</td>'; |
| 35 | + emailBody += '<td>' + gr.getValue('client_id') + '</td>'; |
| 36 | + emailBody += '<td>' + gr.getDisplayValue('expires_on') + '</td>'; |
| 37 | + emailBody += '</tr>'; |
| 38 | + } |
| 39 | + emailBody += '</table>'; |
| 40 | + emailBody += '<p>Please review and renew tokens to avoid integration failures.</p>'; |
| 41 | + |
| 42 | + // Send the email |
| 43 | + var mail = new GlideEmailOutbound(); |
| 44 | + mail.setFrom('no-reply@yourdomain.com'); |
| 45 | + mail.setSubject('[ServiceNow] OAuth API Token Expiry Warning'); |
| 46 | + mail.setTo(emailRecipients); |
| 47 | + mail.setBody(emailBody); |
| 48 | + mail.setContentType('text/html'); |
| 49 | + mail.send(); |
| 50 | + |
| 51 | + gs.info('OAuth token expiry warning email sent to: ' + emailRecipients); |
| 52 | + |
| 53 | +})(); |
0 commit comments