|
| 1 | +/** |
| 2 | + * This sample demonstrates how to configure the library for the Jira REST API. |
| 3 | + * @see {@link https://developer.atlassian.com/cloud/jira/platform/jira-rest-api-oauth-authentication/} |
| 4 | + */ |
| 5 | + |
| 6 | +var SITE = 'https://something.atlassian.net'; |
| 7 | +var CONSUMER_KEY = '...'; |
| 8 | +// The private key must be in the PKCS#8 PEM format. |
| 9 | +var PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n'; |
| 10 | + |
| 11 | +/** |
| 12 | + * Authorizes and makes a request to the Xero API. |
| 13 | + */ |
| 14 | +function run() { |
| 15 | + var service = getService(); |
| 16 | + if (service.hasAccess()) { |
| 17 | + var url = SITE + '/rest/api/3/myself'; |
| 18 | + var response = service.fetch(url, { |
| 19 | + headers: { |
| 20 | + Accept: 'application/json' |
| 21 | + } |
| 22 | + }); |
| 23 | + var result = JSON.parse(response.getContentText()); |
| 24 | + Logger.log(JSON.stringify(result, null, 2)); |
| 25 | + } else { |
| 26 | + var authorizationUrl = service.authorize(); |
| 27 | + Logger.log('Open the following URL and re-run the script: %s', |
| 28 | + authorizationUrl); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Reset the authorization state, so that it can be re-tested. |
| 34 | + */ |
| 35 | +function reset() { |
| 36 | + getService().reset(); |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Configures the service. |
| 41 | + */ |
| 42 | +function getService() { |
| 43 | + return OAuth1.createService('Jira') |
| 44 | + // Set the endpoint URLs. |
| 45 | + .setRequestTokenUrl(SITE + '/plugins/servlet/oauth/request-token') |
| 46 | + .setAuthorizationUrl(SITE + '/plugins/servlet/oauth/authorize') |
| 47 | + .setAccessTokenUrl(SITE + '/plugins/servlet/oauth/access-token') |
| 48 | + |
| 49 | + // Set the consumer key and secret. |
| 50 | + .setConsumerKey(CONSUMER_KEY) |
| 51 | + .setConsumerSecret(PRIVATE_KEY) |
| 52 | + |
| 53 | + // Set the OAuth signature method. |
| 54 | + .setSignatureMethod('RSA-SHA1') |
| 55 | + |
| 56 | + // Set the method to POST, as required by Atlassian. |
| 57 | + .setMethod('post') |
| 58 | + |
| 59 | + // Set the name of the callback function in the script referenced |
| 60 | + // above that should be invoked to complete the OAuth flow. |
| 61 | + .setCallbackFunction('authCallback') |
| 62 | + |
| 63 | + // Set the property store where authorized tokens should be persisted. |
| 64 | + .setPropertyStore(PropertiesService.getUserProperties()); |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Handles the OAuth callback. |
| 69 | + */ |
| 70 | +function authCallback(request) { |
| 71 | + var service = getService(); |
| 72 | + var authorized = service.handleCallback(request); |
| 73 | + if (authorized) { |
| 74 | + return HtmlService.createHtmlOutput('Success!'); |
| 75 | + } else { |
| 76 | + return HtmlService.createHtmlOutput('Denied'); |
| 77 | + } |
| 78 | +} |
0 commit comments