├── .github ├── snippet-bot.yml ├── dependabot.yml ├── linters │ ├── .htmlhintrc │ ├── .yaml-lint.yml │ └── sun_checks.xml ├── CODEOWNERS ├── workflows │ ├── test.yml │ ├── update-dist.yml │ ├── lint.yml │ ├── release-please.yml │ └── automation.yml └── sync-repo-settings.yaml ├── .gitignore ├── CODEOWNERS ├── .clasp.json ├── src ├── appsscript.json ├── OAuth1.gs ├── MemoryProperties.gs ├── Utilities.gs ├── Signer.gs └── Service.gs ├── SECURITY.md ├── gulpfile.js ├── samples ├── Yelp.gs ├── Semantics3.gs ├── XeroPrivate.gs ├── Xing.gs ├── Trello.gs ├── TripIt.gs ├── KhanAcademy.gs ├── Twitter.gs ├── QuickBooks.gs ├── Jira.gs ├── Goodreads.gs ├── Etsy.gs └── XeroPublic.gs ├── package.json ├── README.md ├── LICENSE └── dist └── OAuth1.gs /.github/snippet-bot.yml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @erickoledadevrel 2 | -------------------------------------------------------------------------------- /.clasp.json: -------------------------------------------------------------------------------- 1 | { 2 | "scriptId": "1CXDCY5sqT9ph64fFwSzVtXnbjpSfWdRymafDrtIZ7Z_hwysTY7IIhi7s", 3 | "rootDir": "src/", 4 | "fileExtension": "gs" 5 | } 6 | 7 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "npm" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | commit-message: 8 | prefix: "chore(deps):" 9 | -------------------------------------------------------------------------------- /src/appsscript.json: -------------------------------------------------------------------------------- 1 | { 2 | "timeZone": "America/New_York", 3 | "dependencies": { 4 | "libraries": [{ 5 | "userSymbol": "Underscore", 6 | "libraryId": "1I21uLOwDKdyF3_W_hvh6WXiIKWJWno8yG9lB8lf1VBnZFQ6jAAhyNTRG", 7 | "version": "24" 8 | }] 9 | }, 10 | "exceptionLogging": "STACKDRIVER" 11 | } 12 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Report a security issue 2 | 3 | To report a security issue, please use [https://g.co/vulnz](https://g.co/vulnz). We use 4 | [https://g.co/vulnz](https://g.co/vulnz) for our intake, and do coordination and disclosure here on 5 | GitHub (including using GitHub Security Advisory). The Google Security Team will 6 | respond within 5 working days of your report on [https://g.co/vulnz](https://g.co/vulnz). 7 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | import gulp from 'gulp'; 2 | import concat from 'gulp-concat'; 3 | import expose from 'gulp-expose'; 4 | import stripLine from 'gulp-strip-line'; 5 | import gulpif from 'gulp-if'; 6 | import {deleteAsync} from 'del'; 7 | import jshint from 'gulp-jshint'; 8 | import stylish from 'jshint-stylish'; 9 | 10 | gulp.task('clean', () => deleteAsync(['dist/*'])); 11 | 12 | gulp.task('lint', () => gulp.src('src/*.gs') 13 | .pipe(jshint()) 14 | .pipe(jshint.reporter(stylish)) 15 | ); 16 | 17 | gulp.task('dist', gulp.series('clean', 'lint', () => gulp.src('src/*.gs') 18 | .pipe(gulpif(/OAuth1\.gs$/, 19 | stripLine('var _ ='))) 20 | .pipe(concat('OAuth1.gs')) 21 | .pipe(expose('this', 'OAuth1')) 22 | .pipe(gulp.dest('dist')) 23 | )); 24 | 25 | -------------------------------------------------------------------------------- /.github/linters/.htmlhintrc: -------------------------------------------------------------------------------- 1 | { 2 | "tagname-lowercase": true, 3 | "attr-lowercase": true, 4 | "attr-value-double-quotes": true, 5 | "attr-value-not-empty": false, 6 | "attr-no-duplication": true, 7 | "doctype-first": false, 8 | "tag-pair": true, 9 | "tag-self-close": false, 10 | "spec-char-escape": false, 11 | "id-unique": true, 12 | "src-not-empty": true, 13 | "title-require": false, 14 | "alt-require": true, 15 | "doctype-html5": true, 16 | "id-class-value": false, 17 | "style-disabled": false, 18 | "inline-style-disabled": false, 19 | "inline-script-disabled": false, 20 | "space-tab-mixed-disabled": "space", 21 | "id-class-ad-disabled": false, 22 | "href-abs-or-rel": false, 23 | "attr-unsafe-chars": true, 24 | "head-script-disabled": false 25 | } 26 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners 16 | 17 | .github/ @googleworkspace/workspace-devrel-dpe 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | --- 15 | name: Test 16 | on: [push, pull_request, workflow_dispatch] 17 | jobs: 18 | test: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v2 22 | - run: | 23 | echo "No tests"; 24 | exit 0; 25 | -------------------------------------------------------------------------------- /samples/Yelp.gs: -------------------------------------------------------------------------------- 1 | var CONSUMER_KEY = '...'; 2 | var CONSUMER_SECRET = '...'; 3 | var TOKEN = '...'; 4 | var TOKEN_SECRET = '...'; 5 | 6 | /** 7 | * Authorizes and makes a request to the Yelp API. 8 | */ 9 | function run() { 10 | var service = getService_(); 11 | var url = 'https://api.yelp.com/v2/search?term=food&location=San+Francisco'; 12 | var response = service.fetch(url); 13 | var result = JSON.parse(response.getContentText()); 14 | Logger.log(JSON.stringify(result, null, 2)); 15 | } 16 | 17 | /** 18 | * Configures the service. 19 | */ 20 | function getService_() { 21 | return OAuth1.createService('Yelp') 22 | // Set the consumer key and secret. 23 | .setConsumerKey(CONSUMER_KEY) 24 | .setConsumerSecret(CONSUMER_SECRET) 25 | 26 | // Manually set the token and secret, as provided by the Yelp developer 27 | // console. 28 | .setAccessToken(TOKEN, TOKEN_SECRET); 29 | } 30 | -------------------------------------------------------------------------------- /samples/Semantics3.gs: -------------------------------------------------------------------------------- 1 | var API_KEY = '...'; 2 | var API_SECRET = '...'; 3 | 4 | /** 5 | * Authorizes and makes a request to the Semantics3 API. 6 | */ 7 | function run() { 8 | var service = getService_(); 9 | var query = encodeURIComponent(JSON.stringify({ 10 | search: 'iPhone' 11 | })); 12 | var url = 'https://api.semantics3.com/v1/products?q=' + query; 13 | var response = service.fetch(url); 14 | var result = JSON.parse(response.getContentText()); 15 | Logger.log(JSON.stringify(result, null, 2)); 16 | } 17 | 18 | /** 19 | * Configures the service. 20 | */ 21 | function getService_() { 22 | return OAuth1.createService('Semantics3') 23 | // Set the consumer key and secret. 24 | .setConsumerKey(API_KEY) 25 | .setConsumerSecret(API_SECRET) 26 | 27 | // Manually set the token and secret to the empty string, since the API 28 | // uses 1-legged OAuth. 29 | .setAccessToken('', ''); 30 | } 31 | -------------------------------------------------------------------------------- /.github/workflows/update-dist.yml: -------------------------------------------------------------------------------- 1 | on: [pull_request] 2 | name: Update dist folder 3 | jobs: 4 | update-dist-src: 5 | if: "${{ contains(github.event.pull_request.labels.*.name, 'autorelease: pending') }}" 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | with: 10 | ref: ${{ github.event.pull_request.head.ref }} 11 | token: ${{ secrets.GOOGLEWORKSPACE_BOT_TOKEN }} 12 | - uses: actions/setup-node@v1 13 | with: 14 | node-version: 16 15 | - name: Install dependencies 16 | run: npm ci 17 | - name: Generate dist 18 | run: npm run dist 19 | - uses: stefanzweifel/git-auto-commit-action@v4 20 | with: 21 | commit_message: "chore: Update dist/ directory" 22 | commit_user_name: Google Workspace Bot 23 | commit_user_email: googleworkspace-bot@google.com 24 | commit_author: Google Workspace Bot 25 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | --- 15 | name: Lint 16 | on: [push, pull_request, workflow_dispatch] 17 | jobs: 18 | lint: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v2 22 | - uses: actions/setup-node@v1 23 | with: 24 | node-version: 16 25 | - name: Install dependencies 26 | run: npm ci 27 | - name: Lint files 28 | run: npm run lint 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "apps-script-oauth1", 3 | "version": "1.18.0", 4 | "description": "OAuth1 for Apps Script is a library for Google Apps Script that provides the ability to create and authorize OAuth1 tokens. ", 5 | "repository": { 6 | "type": "git", 7 | "url": "git://github.com/googlesamples/apps-script-oauth1.git" 8 | }, 9 | "author": "Eric Koleda ", 10 | "license": "Apache-2.0", 11 | "bugs": { 12 | "url": "https://github.com/googlesamples/apps-script-oauth1/issues" 13 | }, 14 | "homepage": "https://github.com/googlesamples/apps-script-oauth1", 15 | "type": "module", 16 | "devDependencies": { 17 | "del": "^7.0.0", 18 | "gulp": "^4.0.2", 19 | "gulp-bump": "^3.2.0", 20 | "gulp-clean": "^0.4.0", 21 | "gulp-concat": "^2.6.0", 22 | "gulp-expose": "0.0.7", 23 | "gulp-if": "^3.0.0", 24 | "gulp-jshint": "^2.1.0", 25 | "gulp-strip-line": "0.0.1", 26 | "jshint-stylish": "^2.0.1" 27 | }, 28 | "scripts": { 29 | "postversion": "gulp dist", 30 | "dist": "gulp dist", 31 | "lint": "gulp lint" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | name: release-please 6 | jobs: 7 | release-please: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: google-github-actions/release-please-action@v3 11 | id: release 12 | with: 13 | token: ${{secrets.GOOGLEWORKSPACE_BOT_TOKEN}} 14 | release-type: node 15 | package-name: release-please-action 16 | - uses: actions/checkout@v2 17 | if: ${{ steps.release.outputs.release_created }} 18 | - uses: actions/setup-node@v1 19 | if: ${{ steps.release.outputs.release_created }} 20 | with: 21 | node-version: 16 22 | - name: Write test credentials 23 | if: ${{ steps.release.outputs.release_created }} 24 | run: | 25 | echo "${CLASP_CREDENTIALS}" > "${HOME}/.clasprc.json" 26 | env: 27 | CLASP_CREDENTIALS: ${{secrets.LIBRARIES_OWNER_CLASP_TOKEN}} 28 | - name: Depoy scripts 29 | if: ${{ steps.release.outputs.release_created }} 30 | run: | 31 | npx @google/clasp push 32 | MESSAGE=$(git log -1 --pretty=%B) npx @google/clasp version ${MESSAGE} 33 | -------------------------------------------------------------------------------- /.github/sync-repo-settings.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # .github/sync-repo-settings.yaml 16 | # See https://github.com/googleapis/repo-automation-bots/tree/main/packages/sync-repo-settings for app options. 17 | rebaseMergeAllowed: true 18 | squashMergeAllowed: true 19 | mergeCommitAllowed: false 20 | deleteBranchOnMerge: true 21 | branchProtectionRules: 22 | - pattern: main 23 | isAdminEnforced: false 24 | requiresStrictStatusChecks: false 25 | requiredStatusCheckContexts: 26 | # .github/workflows/test.yml with a job called "test" 27 | - "test" 28 | # .github/workflows/lint.yml with a job called "lint" 29 | - "lint" 30 | # Google bots below 31 | - "cla/google" 32 | - "snippet-bot check" 33 | - "header-check" 34 | - "conventionalcommits.org" 35 | requiredApprovingReviewCount: 1 36 | requiresCodeOwnerReviews: true 37 | permissionRules: 38 | - team: workspace-devrel-dpe 39 | permission: admin 40 | - team: workspace-devrel 41 | permission: push 42 | -------------------------------------------------------------------------------- /.github/linters/.yaml-lint.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ########################################### 3 | # These are the rules used for # 4 | # linting all the yaml files in the stack # 5 | # NOTE: # 6 | # You can disable line with: # 7 | # # yamllint disable-line # 8 | ########################################### 9 | rules: 10 | braces: 11 | level: warning 12 | min-spaces-inside: 0 13 | max-spaces-inside: 0 14 | min-spaces-inside-empty: 1 15 | max-spaces-inside-empty: 5 16 | brackets: 17 | level: warning 18 | min-spaces-inside: 0 19 | max-spaces-inside: 0 20 | min-spaces-inside-empty: 1 21 | max-spaces-inside-empty: 5 22 | colons: 23 | level: warning 24 | max-spaces-before: 0 25 | max-spaces-after: 1 26 | commas: 27 | level: warning 28 | max-spaces-before: 0 29 | min-spaces-after: 1 30 | max-spaces-after: 1 31 | comments: disable 32 | comments-indentation: disable 33 | document-end: disable 34 | document-start: 35 | level: warning 36 | present: true 37 | empty-lines: 38 | level: warning 39 | max: 2 40 | max-start: 0 41 | max-end: 0 42 | hyphens: 43 | level: warning 44 | max-spaces-after: 1 45 | indentation: 46 | level: warning 47 | spaces: consistent 48 | indent-sequences: true 49 | check-multi-line-strings: false 50 | key-duplicates: enable 51 | line-length: 52 | level: warning 53 | max: 120 54 | allow-non-breakable-words: true 55 | allow-non-breakable-inline-mappings: true 56 | new-line-at-end-of-file: disable 57 | new-lines: 58 | type: unix 59 | trailing-spaces: disable -------------------------------------------------------------------------------- /samples/XeroPrivate.gs: -------------------------------------------------------------------------------- 1 | /* 2 | * DEPRECATED - Xero has deprecated OAuth1 support. Please use OAuth2 instead. 3 | * https://github.com/googleworkspace/apps-script-oauth2/blob/master/samples/Xero.gs 4 | */ 5 | 6 | /** 7 | * This sample demonstrates how to configure the library for the Xero API when 8 | * using a private application. Although the Xero documentation calls it a 9 | * "2 legged" flow it is really a 1-legged flow. Public Xero applications use 10 | * a 3-legged flow not shown here. 11 | * @see {@link https://developer.xero.com/documentation/auth-and-limits/private-applications} 12 | */ 13 | 14 | var CONSUMER_KEY = '...'; 15 | // The private key must be in the PKCS#8 PEM format. 16 | var PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n'; 17 | 18 | /** 19 | * Authorizes and makes a request to the Xero API. 20 | */ 21 | function run() { 22 | var service = getService_(); 23 | var url = 'https://api.xero.com/api.xro/2.0/Organisations'; 24 | var response = service.fetch(url, { 25 | headers: { 26 | Accept: 'application/json' 27 | } 28 | }); 29 | var result = JSON.parse(response.getContentText()); 30 | Logger.log(JSON.stringify(result, null, 2)); 31 | } 32 | 33 | /** 34 | * Reset the authorization state, so that it can be re-tested. 35 | */ 36 | function reset() { 37 | getService_().reset(); 38 | } 39 | 40 | /** 41 | * Configures the service. 42 | */ 43 | function getService_() { 44 | return OAuth1.createService('Xero') 45 | // Set the consumer key and secret. 46 | .setConsumerKey(CONSUMER_KEY) 47 | .setConsumerSecret(PRIVATE_KEY) 48 | 49 | // Manually set the token to be the consumer key. 50 | .setAccessToken(CONSUMER_KEY) 51 | 52 | // Set the OAuth signature method. 53 | .setSignatureMethod('RSA-SHA1'); 54 | } 55 | -------------------------------------------------------------------------------- /src/OAuth1.gs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /** 16 | * @fileoverview Contains the methods exposed by the library, and performs any 17 | * required setup. 18 | */ 19 | 20 | /** 21 | * Creates a new OAuth1 service with the name specified. It's usually best to 22 | * create and configure your service once at the start of your script, and then 23 | * reference it during the different phases of the authorization flow. 24 | * @param {string} serviceName The name of the service. 25 | * @return {Service_} The service object. 26 | */ 27 | function createService(serviceName) { 28 | return new Service_(serviceName); 29 | } 30 | 31 | /** 32 | * Returns the callback URL that will be used for a given script. Often this URL 33 | * needs to be entered into a configuration screen of your OAuth provider. 34 | * @param {string} scriptId The ID of your script, which can be found in the 35 | * Script Editor UI under "File > Project properties". 36 | * @return {string} The callback URL. 37 | */ 38 | function getCallbackUrl(scriptId) { 39 | return Utilities.formatString( 40 | 'https://script.google.com/macros/d/%s/usercallback', scriptId); 41 | } 42 | 43 | if (typeof module != 'undefined') { 44 | module.exports = { 45 | createService: createService, 46 | getCallbackUrl: getCallbackUrl, 47 | MemoryProperties: MemoryProperties 48 | }; 49 | } 50 | -------------------------------------------------------------------------------- /samples/Xing.gs: -------------------------------------------------------------------------------- 1 | var CONSUMER_KEY = '...'; 2 | var CONSUMER_SECRET = '...'; 3 | 4 | /** 5 | * Authorizes and makes a request to the Xing API. 6 | */ 7 | function run() { 8 | var service = getService_(); 9 | if (service.hasAccess()) { 10 | var url = 'https://api.xing.com/v1/users/me'; 11 | var response = service.fetch(url); 12 | var result = JSON.parse(response.getContentText()); 13 | Logger.log(JSON.stringify(result, null, 2)); 14 | } else { 15 | var authorizationUrl = service.authorize(); 16 | Logger.log('Open the following URL and re-run the script: %s', 17 | authorizationUrl); 18 | } 19 | } 20 | 21 | /** 22 | * Reset the authorization state, so that it can be re-tested. 23 | */ 24 | function reset() { 25 | var service = getService_(); 26 | service.reset(); 27 | } 28 | 29 | /** 30 | * Configures the service. 31 | */ 32 | function getService_() { 33 | return OAuth1.createService('Xing') 34 | // Set the endpoint URLs. 35 | .setRequestTokenUrl('https://api.xing.com/v1/request_token') 36 | .setAuthorizationUrl('https://api.xing.com/v1/authorize') 37 | .setAccessTokenUrl('https://api.xing.com/v1/access_token') 38 | 39 | // Set the consumer key and secret. 40 | .setConsumerKey(CONSUMER_KEY) 41 | .setConsumerSecret(CONSUMER_SECRET) 42 | 43 | // Set the name of the callback function in the script referenced 44 | // above that should be invoked to complete the OAuth flow. 45 | .setCallbackFunction('authCallback') 46 | 47 | // Set the property store where authorized tokens should be persisted. 48 | .setPropertyStore(PropertiesService.getUserProperties()); 49 | } 50 | 51 | /** 52 | * Handles the OAuth2 callback. 53 | */ 54 | function authCallback(request) { 55 | var service = getService_(); 56 | var authorized = service.handleCallback(request); 57 | if (authorized) { 58 | return HtmlService.createHtmlOutput('Success!'); 59 | } else { 60 | return HtmlService.createHtmlOutput('Denied'); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /samples/Trello.gs: -------------------------------------------------------------------------------- 1 | var CONSUMER_KEY = '...'; 2 | var CONSUMER_SECRET = '...'; 3 | 4 | /** 5 | * Authorizes and makes a request to the Trello API. 6 | */ 7 | function run() { 8 | var service = getService_(); 9 | if (service.hasAccess()) { 10 | var url = 'https://api.trello.com/1/members/me/boards'; 11 | var response = service.fetch(url); 12 | var result = JSON.parse(response.getContentText()); 13 | Logger.log(JSON.stringify(result, null, 2)); 14 | } else { 15 | var authorizationUrl = service.authorize(); 16 | Logger.log('Open the following URL and re-run the script: %s', 17 | authorizationUrl); 18 | } 19 | } 20 | 21 | /** 22 | * Reset the authorization state, so that it can be re-tested. 23 | */ 24 | function reset() { 25 | var service = getService_(); 26 | service.reset(); 27 | } 28 | 29 | /** 30 | * Configures the service. 31 | */ 32 | function getService_() { 33 | return OAuth1.createService('Trello') 34 | // Set the endpoint URLs. 35 | .setRequestTokenUrl('https://trello.com/1/OAuthGetRequestToken') 36 | .setAuthorizationUrl('https://trello.com/1/OAuthAuthorizeToken') 37 | .setAccessTokenUrl('https://trello.com/1/OAuthGetAccessToken') 38 | 39 | // Set the consumer key and secret. 40 | .setConsumerKey(CONSUMER_KEY) 41 | .setConsumerSecret(CONSUMER_SECRET) 42 | 43 | // Set the name of the callback function in the script referenced 44 | // above that should be invoked to complete the OAuth flow. 45 | .setCallbackFunction('authCallback') 46 | 47 | // Set the property store where authorized tokens should be persisted. 48 | .setPropertyStore(PropertiesService.getUserProperties()); 49 | } 50 | 51 | /** 52 | * Handles the OAuth2 callback. 53 | */ 54 | function authCallback(request) { 55 | var service = getService_(); 56 | var authorized = service.handleCallback(request); 57 | if (authorized) { 58 | return HtmlService.createHtmlOutput('Success!'); 59 | } else { 60 | return HtmlService.createHtmlOutput('Denied'); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/MemoryProperties.gs: -------------------------------------------------------------------------------- 1 | /** 2 | * Creates a new MemoryProperties, an implementation of the Properties 3 | * interface that stores values in memory. 4 | * @constructor 5 | */ 6 | var MemoryProperties = function() { 7 | this.properties = {}; 8 | }; 9 | 10 | /** 11 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#deleteallproperties} 12 | */ 13 | MemoryProperties.prototype.deleteAllProperties = function() { 14 | this.properties = {}; 15 | }; 16 | 17 | /** 18 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#deletepropertykey} 19 | */ 20 | MemoryProperties.prototype.deleteProperty = function(key) { 21 | delete this.properties[key]; 22 | }; 23 | 24 | /** 25 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#getkeys} 26 | */ 27 | MemoryProperties.prototype.getKeys = function() { 28 | return Object.keys(this.properties); 29 | }; 30 | 31 | /** 32 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#getproperties} 33 | */ 34 | MemoryProperties.prototype.getProperties = function() { 35 | return extend_({}, this.properties); 36 | }; 37 | 38 | /** 39 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#getproperty} 40 | */ 41 | MemoryProperties.prototype.getProperty = function(key) { 42 | return this.properties[key]; 43 | }; 44 | 45 | /** 46 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#setpropertiesproperties-deleteallothers} 47 | */ 48 | MemoryProperties.prototype.setProperties = function(properties, opt_deleteAllOthers) { 49 | if (opt_deleteAllOthers) { 50 | this.deleteAllProperties(); 51 | } 52 | Object.keys(properties).forEach(function(key) { 53 | this.setProperty(key, properties[key]); 54 | }); 55 | }; 56 | 57 | /** 58 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#setpropertykey-value} 59 | */ 60 | MemoryProperties.prototype.setProperty = function(key, value) { 61 | this.properties[key] = String(value); 62 | }; 63 | -------------------------------------------------------------------------------- /samples/TripIt.gs: -------------------------------------------------------------------------------- 1 | var CONSUMER_KEY = '...'; 2 | var CONSUMER_SECRET = '...'; 3 | 4 | /** 5 | * Authorizes and makes a request to the TripIt API. 6 | */ 7 | function run() { 8 | var service = getService_(); 9 | if (service.hasAccess()) { 10 | var url = 'https://api.tripit.com/v1/get/profile?format=json'; 11 | var response = service.fetch(url); 12 | var result = JSON.parse(response.getContentText()); 13 | Logger.log(JSON.stringify(result, null, 2)); 14 | } else { 15 | var authorizationUrl = service.authorize(); 16 | Logger.log('Open the following URL and re-run the script: %s', 17 | authorizationUrl); 18 | } 19 | } 20 | 21 | /** 22 | * Reset the authorization state, so that it can be re-tested. 23 | */ 24 | function reset() { 25 | var service = getService_(); 26 | service.reset(); 27 | } 28 | 29 | /** 30 | * Configures the service. 31 | */ 32 | function getService_() { 33 | return OAuth1.createService('TripIt') 34 | // Set the endpoint URLs. 35 | .setRequestTokenUrl('https://api.tripit.com/oauth/request_token') 36 | .setAuthorizationUrl('https://www.tripit.com/oauth/authorize') 37 | .setAccessTokenUrl('https://api.tripit.com/oauth/access_token') 38 | 39 | // Set the consumer key and secret. 40 | .setConsumerKey(CONSUMER_KEY) 41 | .setConsumerSecret(CONSUMER_SECRET) 42 | 43 | // Set the name of the callback function in the script referenced 44 | // above that should be invoked to complete the OAuth flow. 45 | .setCallbackFunction('authCallback') 46 | 47 | // Set the property store where authorized tokens should be persisted. 48 | .setPropertyStore(PropertiesService.getUserProperties()) 49 | 50 | // Set the OAuth version (default: 1.0a) 51 | .setOAuthVersion('1.0'); 52 | } 53 | 54 | /** 55 | * Handles the OAuth callback. 56 | */ 57 | function authCallback(request) { 58 | var service = getService_(); 59 | var authorized = service.handleCallback(request); 60 | if (authorized) { 61 | return HtmlService.createHtmlOutput('Success!'); 62 | } else { 63 | return HtmlService.createHtmlOutput('Denied'); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /samples/KhanAcademy.gs: -------------------------------------------------------------------------------- 1 | var CONSUMER_KEY = '...'; 2 | var CONSUMER_SECRET = '...'; 3 | 4 | /** 5 | * Authorizes and makes a request to the TripIt API. 6 | */ 7 | function run() { 8 | var service = getService_(); 9 | if (service.hasAccess()) { 10 | var url = 'https://api.khanacademy.org/api/v1/user'; 11 | var response = service.fetch(url); 12 | var result = JSON.parse(response.getContentText()); 13 | Logger.log(JSON.stringify(result, null, 2)); 14 | } else { 15 | var authorizationUrl = service.authorize(); 16 | Logger.log('Open the following URL and re-run the script: %s', 17 | authorizationUrl); 18 | } 19 | } 20 | 21 | /** 22 | * Reset the authorization state, so that it can be re-tested. 23 | */ 24 | function reset() { 25 | var service = getService_(); 26 | service.reset(); 27 | } 28 | 29 | /** 30 | * Configures the service. 31 | */ 32 | function getService_() { 33 | return OAuth1.createService('TripIt') 34 | // Set the endpoint URLs. 35 | .setRequestTokenUrl('https://www.khanacademy.org/api/auth2/request_token') 36 | .setAuthorizationUrl('https://www.khanacademy.org/api/auth2/authorize') 37 | .setAccessTokenUrl('https://www.khanacademy.org/api/auth2/access_token') 38 | 39 | // Set the consumer key and secret. 40 | .setConsumerKey(CONSUMER_KEY) 41 | .setConsumerSecret(CONSUMER_SECRET) 42 | 43 | // Set the name of the callback function in the script referenced 44 | // above that should be invoked to complete the OAuth flow. 45 | .setCallbackFunction('authCallback') 46 | 47 | // Set the property store where authorized tokens should be persisted. 48 | .setPropertyStore(PropertiesService.getUserProperties()) 49 | 50 | // Specify that the OAuth parameters should be passed as query parameters. 51 | .setParamLocation('uri-query'); 52 | } 53 | 54 | /** 55 | * Handles the OAuth2 callback. 56 | */ 57 | function authCallback(request) { 58 | var service = getService_(); 59 | var authorized = service.handleCallback(request); 60 | if (authorized) { 61 | return HtmlService.createHtmlOutput('Success!'); 62 | } else { 63 | return HtmlService.createHtmlOutput('Denied'); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /samples/Twitter.gs: -------------------------------------------------------------------------------- 1 | var CONSUMER_KEY = '...'; 2 | var CONSUMER_SECRET = '...'; 3 | 4 | /** 5 | * Authorizes and makes a request to the Twitter API. 6 | */ 7 | function run() { 8 | var service = getService_(); 9 | if (service.hasAccess()) { 10 | var url = 'https://api.twitter.com/1.1/statuses/update.json'; 11 | var payload = { 12 | status: 'It\'s a tweet!' 13 | }; 14 | var response = service.fetch(url, { 15 | method: 'post', 16 | payload: payload 17 | }); 18 | var result = JSON.parse(response.getContentText()); 19 | Logger.log(JSON.stringify(result, null, 2)); 20 | } else { 21 | var authorizationUrl = service.authorize(); 22 | Logger.log('Open the following URL and re-run the script: %s', 23 | authorizationUrl); 24 | } 25 | } 26 | 27 | /** 28 | * Reset the authorization state, so that it can be re-tested. 29 | */ 30 | function reset() { 31 | var service = getService_(); 32 | service.reset(); 33 | } 34 | 35 | /** 36 | * Configures the service. 37 | */ 38 | function getService_() { 39 | return OAuth1.createService('Twitter') 40 | // Set the endpoint URLs. 41 | .setAccessTokenUrl('https://api.twitter.com/oauth/access_token') 42 | .setRequestTokenUrl('https://api.twitter.com/oauth/request_token') 43 | .setAuthorizationUrl('https://api.twitter.com/oauth/authorize') 44 | 45 | // Set the consumer key and secret. 46 | .setConsumerKey(CONSUMER_KEY) 47 | .setConsumerSecret(CONSUMER_SECRET) 48 | 49 | // Set the name of the callback function in the script referenced 50 | // above that should be invoked to complete the OAuth flow. 51 | .setCallbackFunction('authCallback') 52 | 53 | // Using a cache will reduce the need to read from 54 | // the property store and may increase performance. 55 | .setCache(CacheService.getUserCache()) 56 | 57 | // Set the property store where authorized tokens should be persisted. 58 | .setPropertyStore(PropertiesService.getUserProperties()); 59 | } 60 | 61 | /** 62 | * Handles the OAuth callback. 63 | */ 64 | function authCallback(request) { 65 | var service = getService_(); 66 | var authorized = service.handleCallback(request); 67 | if (authorized) { 68 | return HtmlService.createHtmlOutput('Success!'); 69 | } else { 70 | return HtmlService.createHtmlOutput('Denied'); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /samples/QuickBooks.gs: -------------------------------------------------------------------------------- 1 | var CONSUMER_KEY = '...'; 2 | var CONSUMER_SECRET = '...'; 3 | 4 | /** 5 | * Authorizes and makes a request to the QuickBooks API. Assumes the use of a 6 | * sandbox company. 7 | */ 8 | function run() { 9 | var service = getService_(); 10 | if (service.hasAccess()) { 11 | var companyId = PropertiesService.getUserProperties() 12 | .getProperty('QuickBooks.companyId'); 13 | var url = 'https://sandbox-quickbooks.api.intuit.com/v3/company/' + 14 | companyId + '/companyinfo/' + companyId; 15 | var response = service.fetch(url, { 16 | headers: { 17 | 'Accept': 'application/json' 18 | } 19 | }); 20 | var result = JSON.parse(response.getContentText()); 21 | Logger.log(JSON.stringify(result, null, 2)); 22 | } else { 23 | var authorizationUrl = service.authorize(); 24 | Logger.log('Open the following URL and re-run the script: %s', 25 | authorizationUrl); 26 | } 27 | } 28 | 29 | /** 30 | * Reset the authorization state, so that it can be re-tested. 31 | */ 32 | function reset() { 33 | var service = getService_(); 34 | service.reset(); 35 | } 36 | 37 | /** 38 | * Configures the service. 39 | */ 40 | function getService_() { 41 | return OAuth1.createService('QuickBooks') 42 | // Set the endpoint URLs. 43 | .setAccessTokenUrl('https://oauth.intuit.com/oauth/v1/get_access_token') 44 | .setRequestTokenUrl('https://oauth.intuit.com/oauth/v1/get_request_token') 45 | .setAuthorizationUrl('https://appcenter.intuit.com/Connect/Begin') 46 | 47 | // Set the consumer key and secret. 48 | .setConsumerKey(CONSUMER_KEY) 49 | .setConsumerSecret(CONSUMER_SECRET) 50 | 51 | // Set the name of the callback function in the script referenced 52 | // above that should be invoked to complete the OAuth flow. 53 | .setCallbackFunction('authCallback') 54 | 55 | // Set the property store where authorized tokens should be persisted. 56 | .setPropertyStore(PropertiesService.getUserProperties()); 57 | } 58 | 59 | /** 60 | * Handles the OAuth callback. 61 | */ 62 | function authCallback(request) { 63 | var service = getService_(); 64 | var authorized = service.handleCallback(request); 65 | if (authorized) { 66 | PropertiesService.getUserProperties() 67 | .setProperty('QuickBooks.companyId', request.parameter.realmId); 68 | return HtmlService.createHtmlOutput('Success!'); 69 | } else { 70 | return HtmlService.createHtmlOutput('Denied'); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /samples/Jira.gs: -------------------------------------------------------------------------------- 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 | } 79 | -------------------------------------------------------------------------------- /samples/Goodreads.gs: -------------------------------------------------------------------------------- 1 | /* 2 | * This script must be published as a web app (Publish > Deploy as web app) in 3 | * order to function. The web app URL is used instead of the normal callback 4 | * URL to work around a bug in the Goodreads API's OAuth implementation 5 | * (https://goo.gl/cRfdph). 6 | */ 7 | 8 | var CONSUMER_KEY = '...'; 9 | var CONSUMER_SECRET = '...'; 10 | 11 | /** 12 | * Authorizes and makes a request to the Goodreads API. 13 | */ 14 | function run() { 15 | var service = getService_(); 16 | if (service.hasAccess()) { 17 | var url = 'https://www.goodreads.com/api/auth_user'; 18 | var response = service.fetch(url); 19 | var result = response.getContentText(); 20 | Logger.log(result); 21 | } else { 22 | var authorizationUrl = service.authorize(); 23 | Logger.log('Open the following URL and re-run the script: %s', 24 | authorizationUrl); 25 | } 26 | } 27 | 28 | /** 29 | * Reset the authorization state, so that it can be re-tested. 30 | */ 31 | function reset() { 32 | var service = getService_(); 33 | service.reset(); 34 | } 35 | 36 | /** 37 | * Configures the service. 38 | */ 39 | function getService_() { 40 | var service = OAuth1.createService('Goodreads') 41 | // Set the endpoint URLs. 42 | .setAccessTokenUrl('https://www.goodreads.com/oauth/access_token') 43 | .setRequestTokenUrl('https://www.goodreads.com/oauth/request_token') 44 | .setAuthorizationUrl('https://www.goodreads.com/oauth/authorize') 45 | 46 | // Set the consumer key and secret. 47 | .setConsumerKey(CONSUMER_KEY) 48 | .setConsumerSecret(CONSUMER_SECRET) 49 | 50 | // Set the name of the callback function in the script referenced 51 | // above that should be invoked to complete the OAuth flow. 52 | .setCallbackFunction('authCallback') 53 | 54 | // Set the property store where authorized tokens should be persisted. 55 | .setPropertyStore(PropertiesService.getUserProperties()) 56 | 57 | // Set the OAuth version (default: 1.0a) 58 | .setOAuthVersion('1.0'); 59 | 60 | // Override the callback URL method to use the web app URL instead. 61 | service.getCallbackUrl = function() { 62 | return ScriptApp.getService_().getUrl(); 63 | }; 64 | 65 | return service; 66 | } 67 | 68 | /** 69 | * Handles GET requests to the web app. 70 | */ 71 | function doGet(request) { 72 | // Determine if the request is part of an OAuth callback. 73 | if (request.parameter.oauth_token) { 74 | var service = getService_(); 75 | var authorized = service.handleCallback(request); 76 | if (authorized) { 77 | return HtmlService.createHtmlOutput('Success!'); 78 | } else { 79 | return HtmlService.createHtmlOutput('Denied'); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /samples/Etsy.gs: -------------------------------------------------------------------------------- 1 | /* 2 | * This script must be published as a web app (Publish > Deploy as web app) in 3 | * order to function. The web app URL is used instead of the normal callback 4 | * URL to work around a limitation in the Etsy API's OAuth implementation 5 | * (callback URLs are limited to 255 characters). 6 | */ 7 | 8 | var CONSUMER_KEY = '...'; 9 | var CONSUMER_SECRET = '...'; 10 | 11 | /** 12 | * Authorizes and makes a request to the Etsy API. 13 | */ 14 | function run() { 15 | var service = getService_(); 16 | if (service.hasAccess()) { 17 | var url = 'https://openapi.etsy.com/v2/users/__SELF__/profile'; 18 | var response = service.fetch(url); 19 | var result = JSON.parse(response.getContentText()); 20 | Logger.log(JSON.stringify(result, null, 2)); 21 | } else { 22 | service.authorize(); 23 | // Retrieve the authorization URL from the "login_url" field of the request 24 | // token. 25 | var authorizationUrl = service.getToken_().login_url; 26 | Logger.log('Open the following URL and re-run the script: %s', 27 | authorizationUrl); 28 | } 29 | } 30 | 31 | /** 32 | * Reset the authorization state, so that it can be re-tested. 33 | */ 34 | function reset() { 35 | var service = getService_(); 36 | service.reset(); 37 | } 38 | 39 | /** 40 | * Configures the service. 41 | */ 42 | function getService_() { 43 | var service = OAuth1.createService('Etsy') 44 | // Set the endpoint URLs. 45 | // Pass the desired scopes in the request token URL. 46 | .setRequestTokenUrl('https://openapi.etsy.com/v2/oauth/request_token?scope=profile_r') 47 | // The authorization URL isn't used, since Etsy sends it back in the 48 | // "login_url" field of the request token. 49 | .setAuthorizationUrl('N/A') 50 | .setAccessTokenUrl('https://openapi.etsy.com/v2/oauth/access_token') 51 | 52 | // Set the consumer key and secret. 53 | .setConsumerKey(CONSUMER_KEY) 54 | .setConsumerSecret(CONSUMER_SECRET) 55 | 56 | // Set the name of the callback function in the script referenced 57 | // above that should be invoked to complete the OAuth flow. 58 | .setCallbackFunction('authCallback') 59 | 60 | // Set the property store where authorized tokens should be persisted. 61 | .setPropertyStore(PropertiesService.getUserProperties()); 62 | 63 | // Override the callback URL method to use the web app URL instead. 64 | service.getCallbackUrl = function() { 65 | return ScriptApp.getService_().getUrl(); 66 | }; 67 | 68 | return service; 69 | } 70 | 71 | /** 72 | * Handles GET requests to the web app. 73 | */ 74 | function doGet(request) { 75 | // Determine if the request is part of an OAuth callback. 76 | if (request.parameter.oauth_token) { 77 | var service = getService_(); 78 | var authorized = service.handleCallback(request); 79 | if (authorized) { 80 | return HtmlService.createHtmlOutput('Success!'); 81 | } else { 82 | return HtmlService.createHtmlOutput('Denied'); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /.github/workflows/automation.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | --- 15 | name: Automation 16 | on: [ push, pull_request, workflow_dispatch ] 17 | jobs: 18 | dependabot: 19 | runs-on: ubuntu-latest 20 | if: ${{ github.actor == 'dependabot[bot]' && github.event_name == 'pull_request' }} 21 | env: 22 | PR_URL: ${{github.event.pull_request.html_url}} 23 | GITHUB_TOKEN: ${{secrets.GOOGLEWORKSPACE_BOT_TOKEN}} 24 | steps: 25 | - name: approve 26 | run: gh pr review --approve "$PR_URL" 27 | - name: merge 28 | run: gh pr merge --auto --squash --delete-branch "$PR_URL" 29 | default-branch-migration: 30 | # this job helps with migrating the default branch to main 31 | # it pushes main to master if master exists and main is the default branch 32 | # it pushes master to main if master is the default branch 33 | runs-on: ubuntu-latest 34 | if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' }} 35 | steps: 36 | - uses: actions/checkout@v2 37 | with: 38 | fetch-depth: 0 39 | # required otherwise GitHub blocks infinite loops in pushes originating in an action 40 | token: ${{ secrets.GOOGLEWORKSPACE_BOT_TOKEN }} 41 | - name: Set env 42 | run: | 43 | # set DEFAULT BRANCH 44 | echo "DEFAULT_BRANCH=$(gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name')" >> "$GITHUB_ENV"; 45 | 46 | # set HAS_MASTER_BRANCH 47 | if [ -n "$(git ls-remote --heads origin master)" ]; then 48 | echo "HAS_MASTER_BRANCH=true" >> "$GITHUB_ENV" 49 | else 50 | echo "HAS_MASTER_BRANCH=false" >> "$GITHUB_ENV" 51 | fi 52 | env: 53 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 54 | - name: configure git 55 | run: | 56 | git config --global user.name 'googleworkspace-bot' 57 | git config --global user.email 'googleworkspace-bot@google.com' 58 | - if: ${{ env.DEFAULT_BRANCH == 'main' && env.HAS_MASTER_BRANCH == 'true' }} 59 | name: Update master branch from main 60 | run: | 61 | git checkout -B master 62 | git reset --hard origin/main 63 | git push origin master 64 | - if: ${{ env.DEFAULT_BRANCH == 'master'}} 65 | name: Update main branch from master 66 | run: | 67 | git checkout -B main 68 | git reset --hard origin/master 69 | git push origin main 70 | -------------------------------------------------------------------------------- /src/Utilities.gs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /** 16 | * @fileoverview Contains utility methods used by the library. 17 | */ 18 | 19 | /** 20 | * Builds a complete URL from a base URL and a map of URL parameters. 21 | * @param {string} url The base URL. 22 | * @param {Object.} params The URL parameters and values. 23 | * @returns {string} The complete URL. 24 | * @private 25 | */ 26 | function buildUrl_(url, params) { 27 | var paramString = Object.keys(params).map(function(key) { 28 | return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); 29 | }).join('&'); 30 | return url + (url.indexOf('?') >= 0 ? '&' : '?') + paramString; 31 | } 32 | 33 | /** 34 | * Validates that all of the values in the object are non-empty. If an empty 35 | * value is found, and error is thrown using the key as the name. 36 | * @param {Object.} params The values to validate. 37 | * @private 38 | */ 39 | function validate_(params) { 40 | Object.keys(params).forEach(function(name) { 41 | var value = params[name]; 42 | if (!value) { 43 | throw new Error(name + ' is required.'); 44 | } 45 | }); 46 | } 47 | 48 | /** 49 | * Polyfill for Object.assign, which isn't available on the legacy runtime. 50 | * Not assigning to Object to avoid overwriting behavior in the parent 51 | * script(s). 52 | * @param {Object} target The target object to apply the sources’ properties to, 53 | * which is returned after it is modified. 54 | * @param {...Object} sources The source object(s) containing the properties you 55 | * want to apply. 56 | * @returns {Object} The target object. 57 | * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill} 58 | * @license Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ 59 | */ 60 | function assign_(target, varArgs) { 61 | if (typeof Object.assign === 'function') { 62 | return Object.assign.apply(null, arguments); 63 | } 64 | if (target === null || target === undefined) { 65 | throw new TypeError('Cannot convert undefined or null to object'); 66 | } 67 | var to = Object(target); 68 | for (var index = 1; index < arguments.length; index++) { 69 | var nextSource = arguments[index]; 70 | 71 | if (nextSource !== null && nextSource !== undefined) { 72 | for (var nextKey in nextSource) { 73 | // Avoid bugs when hasOwnProperty is shadowed 74 | if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { 75 | to[nextKey] = nextSource[nextKey]; 76 | } 77 | } 78 | } 79 | } 80 | return to; 81 | } 82 | 83 | /** 84 | * Gets the time in seconds, rounded down to the nearest second. 85 | * @param {Date} date The Date object to convert. 86 | * @returns {Number} The number of seconds since the epoch. 87 | * @private 88 | */ 89 | function getTimeInSeconds_(date) { 90 | return Math.floor(date.getTime() / 1000); 91 | } 92 | -------------------------------------------------------------------------------- /samples/XeroPublic.gs: -------------------------------------------------------------------------------- 1 | /* 2 | * DEPRECATED - Xero has deprecated OAuth1 support. Please use OAuth2 instead. 3 | * https://github.com/googleworkspace/apps-script-oauth2/blob/master/samples/Xero.gs 4 | */ 5 | 6 | /* 7 | * Xero public applications guide: 8 | * https://developer.xero.com/documentation/auth-and-limits/public-applications 9 | * 10 | * This script must be published as a web app (Publish > Deploy as web app) in 11 | * order to function. The web app URL is used instead of the normal callback 12 | * URL to work around a limitation in the Xero API's OAuth implementation 13 | * (callback URLs are limited to 250 characters). Make sure to republish the 14 | * web app after updating the code. 15 | */ 16 | 17 | var CONSUMER_KEY = '...'; 18 | var CONSUMER_SECRET = '...'; 19 | 20 | /** 21 | * Authorizes and makes a request to the Xero API. 22 | */ 23 | function run() { 24 | var service = getService_(); 25 | if (service.hasAccess()) { 26 | var url = 'https://api.xero.com/api.xro/2.0/Organisations'; 27 | var response = service.fetch(url, { 28 | headers: { 29 | Accept: 'application/json' 30 | } 31 | }); 32 | var result = JSON.parse(response.getContentText()); 33 | Logger.log(JSON.stringify(result, null, 2)); 34 | } else { 35 | var authorizationUrl = service.authorize(); 36 | Logger.log('Open the following URL and re-run the script: %s', 37 | authorizationUrl); 38 | } 39 | } 40 | 41 | /** 42 | * Reset the authorization state, so that it can be re-tested. 43 | */ 44 | function reset() { 45 | var service = getService_(); 46 | service.reset(); 47 | } 48 | 49 | /** 50 | * Configures the service. 51 | */ 52 | function getService_() { 53 | var service = OAuth1.createService('Xero') 54 | // Set the endpoint URLs. 55 | .setRequestTokenUrl('https://api.xero.com/oauth/RequestToken') 56 | .setAuthorizationUrl('https://api.xero.com/oauth/Authorize') 57 | .setAccessTokenUrl('https://api.xero.com/oauth/AccessToken') 58 | 59 | // Set the consumer key and secret. 60 | .setConsumerKey(CONSUMER_KEY) 61 | .setConsumerSecret(CONSUMER_SECRET) 62 | 63 | // Set the name of the callback function in the script referenced 64 | // above that should be invoked to complete the OAuth flow. 65 | .setCallbackFunction('authCallback') 66 | 67 | // Set the property store where authorized tokens should be persisted. 68 | .setPropertyStore(PropertiesService.getUserProperties()); 69 | 70 | // Override the callback URL method to use the web app URL instead. 71 | service.getCallbackUrl = function() { 72 | return ScriptApp.getService_().getUrl(); 73 | }; 74 | 75 | // Override the parseToken_ method to record the time granted. 76 | var originalParseToken = service.parseToken_; 77 | service.parseToken_ = function(content) { 78 | var token = originalParseToken.apply(this, [content]); 79 | token.granted_time = Math.floor((new Date()).getTime() / 1000); 80 | return token; 81 | } 82 | 83 | // Override the hasAccess method to handle token expiration. 84 | var orginalHasAccess = service.hasAccess; 85 | service.hasAccess = function() { 86 | // First do the normal check. 87 | if (!orginalHasAccess.apply(this)) return false; 88 | 89 | // Check to see if the access token has expired 90 | // (or will expire in the next 60 seconds). 91 | var token = this.getToken_(); 92 | var expiresTime = token.granted_time + Number(token.oauth_expires_in); 93 | var now = Math.floor((new Date()).getTime() / 1000); 94 | return (expiresTime - now) > 60; 95 | } 96 | 97 | return service; 98 | } 99 | 100 | /** 101 | * Handles GET requests to the web app. 102 | */ 103 | function doGet(request) { 104 | // Determine if the request is part of an OAuth callback. 105 | if (request.parameter.oauth_token) { 106 | var service = getService_(); 107 | var authorized = service.handleCallback(request); 108 | if (authorized) { 109 | return HtmlService.createHtmlOutput('Success!'); 110 | } else { 111 | return HtmlService.createHtmlOutput('Denied'); 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OAuth1 for Apps Script 2 | 3 | OAuth1 for Apps Script is a library for Google Apps Script that provides the 4 | ability to create and authorize OAuth1 tokens. This library uses Apps Script's 5 | new [StateTokenBuilder](https://developers.google.com/apps-script/reference/script/state-token-builder) 6 | and `/usercallback` endpoint to handle the redirects. 7 | 8 | *Note:* OAuth1 for Google APIs is 9 | [deprecated](https://developers.google.com/accounts/docs/OAuth) and scheduled 10 | to be shut down on April 20, 2015. For accessing Google APIs, use the 11 | [Apps Script OAuth2 library instead](https://github.com/googlesamples/apps-script-oauth2). 12 | 13 | ## Setup 14 | 15 | This library is already published as an Apps Script, making it easy to include 16 | in your project. To add it to your script, do the following in the Apps Script 17 | code editor: 18 | 19 | 1. Click on the menu item "Resources > Libraries..." 20 | 2. In the "Find a Library" text box, enter the script ID 21 | `1CXDCY5sqT9ph64fFwSzVtXnbjpSfWdRymafDrtIZ7Z_hwysTY7IIhi7s` and click the 22 | "Select" button. 23 | 3. Choose a version in the dropdown box (usually best to pick the latest 24 | version). 25 | 4. Click the "Save" button. 26 | 27 | Alternatively, you can copy and paste the files in the [`/dist`](dist) directory 28 | directly into your script project. 29 | 30 | 31 | ## Callback URL 32 | 33 | Before you can start authenticating against an OAuth1 provider, you usually need 34 | to register your application and retrieve the consumer key and secret. Often 35 | these registration screens require you to enter a "Callback URL", which is the 36 | URL that users will be redirected to after they've authorized the token. For 37 | this library (and the Apps Script functionality in general) the URL will always 38 | be in the following format: 39 | 40 | https://script.google.com/macros/d/{SCRIPT ID}/usercallback 41 | 42 | Where `{SCRIPT ID}` is the ID of the script that is using this library. You 43 | can find your script's ID in the Apps Script code editor by clicking on the menu 44 | item "File > Project properties". 45 | 46 | Alternatively you can call the service's `getCallbackUrl()` method to view the 47 | exact URL that the service will use when performing the OAuth flow: 48 | 49 | ```js 50 | /** 51 | * Logs the callback URL to register. 52 | */ 53 | function logCallbackUrl() { 54 | var service = getService_(); 55 | Logger.log(service.getCallbackUrl()); 56 | } 57 | ``` 58 | 59 | ## Usage 60 | 61 | Using the library to generate an OAuth1 token has the following basic steps. 62 | 63 | ### 1. Create the OAuth1 service 64 | 65 | The Service class contains the configuration information for a given 66 | OAuth1 provider, including it's endpoints, consumer keys and secrets, etc. This 67 | information is not persisted to any data store, so you'll need to create this 68 | object each time you want to use it. The example below shows how to create a 69 | service for the Twitter API. 70 | 71 | Ensure the method is private (has an underscore at the end of the name) to 72 | prevent clients from being able to call the method to read your client ID and 73 | secret. 74 | 75 | ```js 76 | function getTwitterService_() { 77 | // Create a new service with the given name. The name will be used when 78 | // persisting the authorized token, so ensure it is unique within the 79 | // scope of the property store. 80 | return OAuth1.createService('twitter') 81 | // Set the endpoint URLs. 82 | .setAccessTokenUrl('https://api.twitter.com/oauth/access_token') 83 | .setRequestTokenUrl('https://api.twitter.com/oauth/request_token') 84 | .setAuthorizationUrl('https://api.twitter.com/oauth/authorize') 85 | // Set the consumer key and secret. 86 | .setConsumerKey('...') 87 | .setConsumerSecret('...') 88 | // Set the name of the callback function in the script referenced 89 | // above that should be invoked to complete the OAuth flow. 90 | .setCallbackFunction('authCallback') 91 | // Set the property store where authorized tokens should be persisted. 92 | .setPropertyStore(PropertiesService.getUserProperties()); 93 | } 94 | ``` 95 | 96 | ### 2. Create a request token and direct the user to the authorization URL 97 | 98 | Apps Script UI's are not allowed to redirect the user's window to a new URL, so 99 | you'll need to present the authorization URL as a link for the user to click. 100 | The service's `authorize()` method generates the request token and returns the 101 | authorization URL. 102 | 103 | ```js 104 | function showSidebar() { 105 | var twitterService = getTwitterService_(); 106 | if (!twitterService.hasAccess()) { 107 | var authorizationUrl = twitterService.authorize(); 108 | var template = HtmlService.createTemplate( 109 | 'Authorize. ' + 110 | 'Reopen the sidebar when the authorization is complete.'); 111 | template.authorizationUrl = authorizationUrl; 112 | var page = template.evaluate(); 113 | DocumentApp.getUi().showSidebar(page); 114 | } else { 115 | // ... 116 | } 117 | } 118 | ``` 119 | 120 | ### 3. Handle the callback 121 | 122 | When the user completes the OAuth1 flow, the callback function you specified 123 | for your service will be invoked. This callback function should pass its 124 | request object to the service's `handleCallback()` method, and show a message 125 | to the user. 126 | 127 | ```js 128 | function authCallback(request) { 129 | var twitterService = getTwitterService_(); 130 | var isAuthorized = twitterService.handleCallback(request); 131 | if (isAuthorized) { 132 | return HtmlService.createHtmlOutput('Success! You can close this tab.'); 133 | } else { 134 | return HtmlService.createHtmlOutput('Denied. You can close this tab'); 135 | } 136 | } 137 | ``` 138 | 139 | **Note:** In an Apps Script UI it's not possible to automatically close a window 140 | or tab, so you'll need to direct the user to close it themselves. 141 | 142 | ### 4. Make authorized requests 143 | 144 | Now that the service is authorized you can use it to make reqests to the API. 145 | The service's `fetch()` method accepts the same parameters as the built-in 146 | [`UrlFetchApp.fetch()`](https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)) 147 | and automatically signs the requests using the OAuth1 token. 148 | 149 | ```js 150 | function makeRequest() { 151 | var twitterService = getTwitterService_(); 152 | var response = twitterService.fetch('https://api.twitter.com/1.1/statuses/user_timeline.json'); 153 | // ... 154 | } 155 | ``` 156 | 157 | ## Compatiblity 158 | 159 | This library was designed to work with any OAuth1 provider, but because of small 160 | differences in how they implement the standard it may be that some APIs 161 | aren't compatible. If you find an API that it does't work with, open an issue or 162 | fix the problem yourself and make a pull request against the source code. 163 | 164 | ### 3-legged OAuth 165 | 166 | This library was primarily designed to support the 167 | [3-legged OAuth flow](http://oauthbible.com/#oauth-10a-three-legged), where 168 | the end-user visits a web page to grant authorization to your application. The 169 | "Usage" section above describes how to configure the library for this flow. 170 | 171 | ### 2-legged OAuth 172 | 173 | This library does not currently support the 174 | [2-legged OAuth flow](http://oauthbible.com/#oauth-10a-two-legged), where 175 | tokens are generated but the user is not prompted to authorize access. 176 | 177 | Be aware that many OAuth providers incorrectly use the term "2-legged" when 178 | describing their OAuth flow, when in reality they are using the 1-legged flow, 179 | which this library does support. 180 | 181 | ### 1-legged OAuth 182 | 183 | This library supports the 184 | [1-legged OAuth flow](http://oauthbible.com/#oauth-10a-one-legged), where the 185 | consumer key and secret are simply used to sign requests to the API endpoints, 186 | without the creation or exchanging of tokens. To use this flow, setup the 187 | service with a consumer key and secret (and optionally a token and token secret) 188 | and use it to call the API endpoint. See the 189 | [Semantics3 sample](samples/Semantics3.gs) and [Yelp sample](samples/Yelp.gs) 190 | for some example usage. 191 | 192 | ## Other features 193 | 194 | #### Resetting the access token 195 | 196 | If you have an access token set and need to remove it from the property store 197 | you can remove it with the `reset()` function. Before you can call reset you 198 | need to set the property store. 199 | 200 | ```js 201 | function clearService(){ 202 | OAuth1.createService('twitter') 203 | .setPropertyStore(PropertiesService.getUserProperties()) 204 | .reset(); 205 | } 206 | ``` 207 | 208 | #### Setting the request method and parameter location 209 | 210 | OAuth1 providers may require that you use a particular HTTP method or parameter 211 | location when performing the OAuth1 flow. You can use the methods `setMethod()` 212 | and `setParamLocation()` to controls these settings. 213 | -------------------------------------------------------------------------------- /src/Signer.gs: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // 3 | // Copyright (c) 2014 Ddo 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | // this software and associated documentation files (the "Software"), to deal in 7 | // the Software without restriction, including without limitation the rights to 8 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | // the Software, and to permit persons to whom the Software is furnished to do so, 10 | // subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in all 13 | // copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | 22 | /** 23 | * A modified version of the oauth-1.0a javascript library: 24 | * https://github.com/ddo/oauth-1.0a 25 | * The cryptojs dependency was removed in favor of native Apps Script functions. 26 | * A new parameter was added to authorize() for additional oauth params. 27 | * Support for realm authorization parameter was added in toHeader(). 28 | */ 29 | 30 | (function(global) { 31 | /** 32 | * Constructor 33 | * @param {Object} opts consumer key and secret 34 | */ 35 | function OAuth(opts) { 36 | if(!(this instanceof OAuth)) { 37 | return new OAuth(opts); 38 | } 39 | 40 | if(!opts) { 41 | opts = {}; 42 | } 43 | 44 | if(!opts.consumer) { 45 | throw new Error('consumer option is required'); 46 | } 47 | 48 | this.consumer = opts.consumer; 49 | this.signature_method = opts.signature_method || 'HMAC-SHA1'; 50 | this.nonce_length = opts.nonce_length || 32; 51 | this.version = opts.version || '1.0'; 52 | this.parameter_seperator = opts.parameter_seperator || ', '; 53 | 54 | if(typeof opts.last_ampersand === 'undefined') { 55 | this.last_ampersand = true; 56 | } else { 57 | this.last_ampersand = opts.last_ampersand; 58 | } 59 | 60 | switch (this.signature_method) { 61 | case 'HMAC-SHA1': 62 | this.hash = function(base_string, key) { 63 | var sig = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_1, base_string, key); 64 | return Utilities.base64Encode(sig); 65 | }; 66 | break; 67 | case 'PLAINTEXT': 68 | this.hash = function(base_string, key) { 69 | return key; 70 | }; 71 | break; 72 | case 'RSA-SHA1': 73 | this.hash = function(base_string, key) { 74 | var sig = Utilities.computeRsaSignature(Utilities.RsaAlgorithm.RSA_SHA_1, base_string, key); 75 | return Utilities.base64Encode(sig); 76 | }; 77 | break; 78 | default: 79 | throw new Error('The OAuth 1.0a protocol defines three signature methods: HMAC-SHA1, RSA-SHA1, and PLAINTEXT only'); 80 | } 81 | } 82 | 83 | /** 84 | * OAuth request authorize 85 | * @param {Object} request data 86 | * { 87 | * method, 88 | * url, 89 | * data 90 | * } 91 | * @param {Object} public and secret token 92 | * @return {Object} OAuth Authorized data 93 | */ 94 | OAuth.prototype.authorize = function(request, token, opt_oauth_data) { 95 | var oauth_data = { 96 | oauth_consumer_key: this.consumer.public, 97 | oauth_nonce: this.getNonce(), 98 | oauth_signature_method: this.signature_method, 99 | oauth_timestamp: this.getTimeStamp(), 100 | oauth_version: this.version 101 | }; 102 | 103 | if (opt_oauth_data) { 104 | oauth_data = this.mergeObject(oauth_data, opt_oauth_data); 105 | } 106 | 107 | if(!token) { 108 | token = {}; 109 | } 110 | 111 | if(token.public) { 112 | oauth_data.oauth_token = token.public; 113 | } 114 | 115 | if(!request.data) { 116 | request.data = {}; 117 | } 118 | 119 | oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data); 120 | 121 | return oauth_data; 122 | }; 123 | 124 | /** 125 | * Create a OAuth Signature 126 | * @param {Object} request data 127 | * @param {Object} token_secret public and secret token 128 | * @param {Object} oauth_data OAuth data 129 | * @return {String} Signature 130 | */ 131 | OAuth.prototype.getSignature = function(request, token_secret, oauth_data) { 132 | return this.hash(this.getBaseString(request, oauth_data), this.getSigningKey(token_secret)); 133 | }; 134 | 135 | /** 136 | * Base String = Method + Base Url + ParameterString 137 | * @param {Object} request data 138 | * @param {Object} OAuth data 139 | * @return {String} Base String 140 | */ 141 | OAuth.prototype.getBaseString = function(request, oauth_data) { 142 | return request.method.toUpperCase() + '&' + this.percentEncode(this.getBaseUrl(request.url)) + '&' + this.percentEncode(this.getParameterString(request, oauth_data)); 143 | }; 144 | 145 | /** 146 | * Get data from url 147 | * -> merge with oauth data 148 | * -> percent encode key & value 149 | * -> sort 150 | * 151 | * @param {Object} request data 152 | * @param {Object} OAuth data 153 | * @return {Object} Parameter string data 154 | */ 155 | OAuth.prototype.getParameterString = function(request, oauth_data) { 156 | var base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.mergeObject(request.data, this.deParamUrl(request.url))))); 157 | 158 | var data_str = ''; 159 | 160 | //base_string_data to string 161 | for(var key in base_string_data) { 162 | data_str += key + '=' + base_string_data[key] + '&'; 163 | } 164 | 165 | //remove the last character 166 | data_str = data_str.substr(0, data_str.length - 1); 167 | return data_str; 168 | }; 169 | 170 | /** 171 | * Create a Signing Key 172 | * @param {String} token_secret Secret Token 173 | * @return {String} Signing Key 174 | */ 175 | OAuth.prototype.getSigningKey = function(token_secret) { 176 | token_secret = token_secret || ''; 177 | 178 | // Don't percent encode the signing key (PKCS#8 PEM private key) when using 179 | // the RSA-SHA1 method. The token secret is never used with the RSA-SHA1 180 | // method. 181 | if (this.signature_method === 'RSA-SHA1') { 182 | return this.consumer.secret; 183 | } 184 | 185 | if(!this.last_ampersand && !token_secret) { 186 | return this.percentEncode(this.consumer.secret); 187 | } 188 | 189 | return this.percentEncode(this.consumer.secret) + '&' + this.percentEncode(token_secret); 190 | }; 191 | 192 | /** 193 | * Get base url 194 | * @param {String} url 195 | * @return {String} 196 | */ 197 | OAuth.prototype.getBaseUrl = function(url) { 198 | return url.split('?')[0]; 199 | }; 200 | 201 | /** 202 | * Get data from String 203 | * @param {String} string 204 | * @return {Object} 205 | */ 206 | OAuth.prototype.deParam = function(string) { 207 | var arr = string.replace(/\+/g, ' ').split('&'); 208 | var data = {}; 209 | 210 | for(var i = 0; i < arr.length; i++) { 211 | var item = arr[i].split('='); 212 | data[item[0]] = decodeURIComponent(item[1]); 213 | } 214 | return data; 215 | }; 216 | 217 | /** 218 | * Get data from url 219 | * @param {String} url 220 | * @return {Object} 221 | */ 222 | OAuth.prototype.deParamUrl = function(url) { 223 | var tmp = url.split('?'); 224 | 225 | if (tmp.length === 1) 226 | return {}; 227 | 228 | return this.deParam(tmp[1]); 229 | }; 230 | 231 | /** 232 | * Percent Encode 233 | * @param {String} str 234 | * @return {String} percent encoded string 235 | */ 236 | OAuth.prototype.percentEncode = function(str) { 237 | return encodeURIComponent(str) 238 | .replace(/\!/g, "%21") 239 | .replace(/\*/g, "%2A") 240 | .replace(/\'/g, "%27") 241 | .replace(/\(/g, "%28") 242 | .replace(/\)/g, "%29"); 243 | }; 244 | 245 | /** 246 | * Percent Encode Object 247 | * @param {Object} data 248 | * @return {Object} percent encoded data 249 | */ 250 | OAuth.prototype.percentEncodeData = function(data) { 251 | var result = {}; 252 | 253 | for(var key in data) { 254 | result[this.percentEncode(key)] = this.percentEncode(data[key]); 255 | } 256 | 257 | return result; 258 | }; 259 | 260 | /** 261 | * Get OAuth data as Header 262 | * @param {Object} oauth_data 263 | * @return {String} Header data key - value 264 | */ 265 | OAuth.prototype.toHeader = function(oauth_data) { 266 | oauth_data = this.sortObject(oauth_data); 267 | 268 | var header_value = 'OAuth '; 269 | 270 | for(var key in oauth_data) { 271 | if (key !== 'realm' && key.indexOf('oauth_') === -1) 272 | continue; 273 | header_value += this.percentEncode(key) + '="' + this.percentEncode(oauth_data[key]) + '"' + this.parameter_seperator; 274 | } 275 | 276 | return { 277 | Authorization: header_value.substr(0, header_value.length - this.parameter_seperator.length) //cut the last chars 278 | }; 279 | }; 280 | 281 | /** 282 | * Create a random word characters string with input length 283 | * @return {String} a random word characters string 284 | */ 285 | OAuth.prototype.getNonce = function() { 286 | var word_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 287 | var result = ''; 288 | 289 | for(var i = 0; i < this.nonce_length; i++) { 290 | result += word_characters[parseInt(Math.random() * word_characters.length, 10)]; 291 | } 292 | 293 | return result; 294 | }; 295 | 296 | /** 297 | * Get Current Unix TimeStamp 298 | * @return {Int} current unix timestamp 299 | */ 300 | OAuth.prototype.getTimeStamp = function() { 301 | return parseInt(new Date().getTime()/1000, 10); 302 | }; 303 | 304 | ////////////////////// HELPER FUNCTIONS ////////////////////// 305 | 306 | /** 307 | * Merge object 308 | * @param {Object} obj1 309 | * @param {Object} obj2 310 | * @return {Object} 311 | */ 312 | OAuth.prototype.mergeObject = function(obj1, obj2) { 313 | var merged_obj = obj1; 314 | for(var key in obj2) { 315 | merged_obj[key] = obj2[key]; 316 | } 317 | return merged_obj; 318 | }; 319 | 320 | /** 321 | * Sort object by key 322 | * @param {Object} data 323 | * @return {Object} sorted object 324 | */ 325 | OAuth.prototype.sortObject = function(data) { 326 | var keys = Object.keys(data); 327 | var result = {}; 328 | 329 | keys.sort(); 330 | 331 | for(var i = 0; i < keys.length; i++) { 332 | var key = keys[i]; 333 | result[key] = data[key]; 334 | } 335 | 336 | return result; 337 | }; 338 | 339 | global.Signer = OAuth; 340 | })(this); 341 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/Service.gs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | /** 16 | * @fileoverview Contains the Service_ class. 17 | */ 18 | 19 | // Disable JSHint warnings for the use of eval(), since it's required to prevent 20 | // scope issues in Apps Script. 21 | // jshint evil:true 22 | 23 | /** 24 | * Creates a new OAuth1 service. 25 | * @param {string} serviceName The name of the service. 26 | * @constructor 27 | */ 28 | var Service_ = function(serviceName) { 29 | validate_({ 30 | 'Service name': serviceName 31 | }); 32 | this.serviceName_ = serviceName; 33 | this.paramLocation_ = 'auth-header'; 34 | this.method_ = 'get'; 35 | this.oauthVersion_ = '1.0a'; 36 | this.scriptId_ = eval('Script' + 'App').getScriptId(); 37 | this.signatureMethod_ = 'HMAC-SHA1'; 38 | this.propertyStore_ = new MemoryProperties(); 39 | }; 40 | 41 | /** 42 | * The maximum amount of time that information can be cached. 43 | * @type {Number} 44 | */ 45 | Service_.MAX_CACHE_TIME = 21600; 46 | 47 | /** 48 | * Sets the request URL for the OAuth service (required). 49 | * @param {string} url The URL given by the OAuth service provider for obtaining 50 | * a request token. 51 | * @return {Service_} This service, for chaining. 52 | */ 53 | Service_.prototype.setRequestTokenUrl = function(url) { 54 | this.requestTokenUrl_ = url; 55 | return this; 56 | }; 57 | 58 | /** 59 | * Sets the URL for the OAuth authorization service (required). 60 | * @param {string} url The URL given by the OAuth service provider for 61 | * authorizing a token. 62 | * @return {Service_} This service, for chaining. 63 | */ 64 | Service_.prototype.setAuthorizationUrl = function(url) { 65 | this.authorizationUrl_ = url; 66 | return this; 67 | }; 68 | 69 | /** 70 | * Sets the URL to get an OAuth access token from (required). 71 | * @param {string} url The URL given by the OAuth service provider for obtaining 72 | * an access token. 73 | * @return {Service_} This service, for chaining. 74 | */ 75 | Service_.prototype.setAccessTokenUrl = function(url) { 76 | this.accessTokenUrl_ = url; 77 | return this; 78 | }; 79 | 80 | /** 81 | * Sets the parameter location in OAuth protocol requests (optional). The 82 | * default parameter location is 'auth-header'. 83 | * @param {string} location The parameter location for the OAuth request. 84 | * Allowed values are 'post-body', 'uri-query' and 'auth-header'. 85 | * @return {Service_} This service, for chaining. 86 | */ 87 | Service_.prototype.setParamLocation = function(location) { 88 | this.paramLocation_ = location; 89 | return this; 90 | }; 91 | 92 | /** 93 | * Sets the HTTP method used to complete the OAuth protocol (optional). The 94 | * default method is 'get'. 95 | * @param {string} method The method to be used with this service. Allowed 96 | * values are 'get' and 'post'. 97 | * @return {Service_} This service, for chaining. 98 | */ 99 | Service_.prototype.setMethod = function(method) { 100 | this.method_ = method; 101 | return this; 102 | }; 103 | 104 | /** 105 | * Sets the OAuth realm parameter to be used with this service (optional). 106 | * @param {string} realm The realm to be used with this service. 107 | * @return {Service_} This service, for chaining. 108 | */ 109 | Service_.prototype.setRealm = function(realm) { 110 | this.realm_ = realm; 111 | return this; 112 | }; 113 | 114 | /** 115 | * Sets the OAuth signature method to use. 'HMAC-SHA1' is the default. 116 | * @param {string} signatureMethod The OAuth signature method. Allowed values 117 | * are 'HMAC-SHA1', 'RSA-SHA1' and 'PLAINTEXT'. 118 | * @return {Service_} This service, for chaining. 119 | */ 120 | Service_.prototype.setSignatureMethod = function(signatureMethod) { 121 | this.signatureMethod_ = signatureMethod; 122 | return this; 123 | }; 124 | 125 | /** 126 | * Sets the specific OAuth version to use. The default is '1.0a'. 127 | * @param {string} oauthVersion The OAuth version. Allowed values are '1.0a' 128 | * and '1.0'. 129 | * @return {Service_} This service, for chaining. 130 | */ 131 | Service_.prototype.setOAuthVersion = function(oauthVersion) { 132 | this.oauthVersion_ = oauthVersion; 133 | return this; 134 | }; 135 | 136 | /** 137 | * Sets the ID of the script that contains the authorization callback 138 | * function (required). The script ID can be found in the Script Editor UI 139 | * under "File > Project properties". 140 | * @param {string} scriptId The ID of the script containing the callback 141 | * function. 142 | * @return {Service_} This service, for chaining. 143 | * @deprecated The script ID is now be determined automatically. 144 | */ 145 | Service_.prototype.setScriptId = function(scriptId) { 146 | this.scriptId_ = scriptId; 147 | return this; 148 | }; 149 | 150 | /** 151 | * Sets the name of the authorization callback function (required). This is the 152 | * function that will be called when the user completes the authorization flow 153 | * on the service provider's website. The callback accepts a request parameter, 154 | * which should be passed to this service's handleCallback() method 155 | * to complete the process. 156 | * @param {string} callbackFunctionName The name of the callback function. 157 | * @return {Service_} This service, for chaining. 158 | */ 159 | Service_.prototype.setCallbackFunction = function(callbackFunctionName) { 160 | this.callbackFunctionName_ = callbackFunctionName; 161 | return this; 162 | }; 163 | 164 | /** 165 | * Sets the consumer key, which is provided when you register with an OAuth 166 | * service (required). 167 | * @param {string} consumerKey The consumer key provided by the OAuth service 168 | * provider. 169 | * @return {Service_} This service, for chaining. 170 | */ 171 | Service_.prototype.setConsumerKey = function(consumerKey) { 172 | this.consumerKey_ = consumerKey; 173 | return this; 174 | }; 175 | 176 | /** 177 | * Sets the consumer secret, which is provided when you register with an OAuth 178 | * service (required). 179 | * @param {string} consumerSecret The consumer secret provided by the OAuth 180 | * service provider. 181 | * @return {Service_} This service, for chaining. 182 | */ 183 | Service_.prototype.setConsumerSecret = function(consumerSecret) { 184 | this.consumerSecret_ = consumerSecret; 185 | return this; 186 | }; 187 | 188 | /** 189 | * Sets the property store to use when persisting credentials (optional). In 190 | * most cases this should be user properties, but document or script properties 191 | * may be appropriate if you want to share access across users. If not set tokens 192 | * will be stored in memory only. 193 | * @param {PropertiesService.Properties} propertyStore The property store to use 194 | * when persisting credentials. 195 | * @return {Service_} This service, for chaining. 196 | */ 197 | Service_.prototype.setPropertyStore = function(propertyStore) { 198 | this.propertyStore_ = propertyStore; 199 | return this; 200 | }; 201 | 202 | /** 203 | * Sets the cache to use when persisting credentials (optional). Using a cache 204 | * will reduce the need to read from the property store and may increase 205 | * performance. In most cases this should be a private cache, but a public cache 206 | * may be appropriate if you want to share access across users. 207 | * @param {CacheService.Cache} cache The cache to use when persisting 208 | * credentials. 209 | * @return {Service_} This service, for chaining. 210 | */ 211 | Service_.prototype.setCache = function(cache) { 212 | this.cache_ = cache; 213 | return this; 214 | }; 215 | 216 | /** 217 | * Sets the access token and token secret to use (optional). For use with APIs 218 | * that support a 1-legged flow where no user interaction is required. 219 | * @param {string} token The access token. 220 | * @param {string} secret The token secret. 221 | * @return {Service_} This service, for chaining. 222 | */ 223 | Service_.prototype.setAccessToken = function(token, secret) { 224 | this.saveToken_({ 225 | public: token, 226 | secret: secret, 227 | type: 'access' 228 | }); 229 | return this; 230 | }; 231 | 232 | /** 233 | * Starts the authorization process. A new token will be generated and the 234 | * authorization URL for that token will be returned. Have the user visit this 235 | * URL and approve the authorization request. The user will then be redirected 236 | * back to your application using the script ID and callback function name 237 | * specified, so that the flow may continue. 238 | * @returns {string} The authorization URL for a new token. 239 | */ 240 | Service_.prototype.authorize = function() { 241 | validate_({ 242 | 'Authorization URL': this.authorizationUrl_ 243 | }); 244 | 245 | var token = this.getRequestToken_(); 246 | this.saveToken_(token); 247 | 248 | var oauthParams = { 249 | oauth_token: token.public 250 | }; 251 | if (this.oauthVersion_ == '1.0') { 252 | oauthParams.oauth_callback = this.getCallbackUrl(); 253 | } 254 | return buildUrl_(this.authorizationUrl_, oauthParams); 255 | }; 256 | 257 | /** 258 | * Completes the OAuth1 flow using the request data passed in to the callback 259 | * function. 260 | * @param {Object} callbackRequest The request data recieved from the callback 261 | * function. 262 | * @return {boolean} True if authorization was granted, false if it was denied. 263 | */ 264 | Service_.prototype.handleCallback = function(callbackRequest) { 265 | var requestToken = callbackRequest.parameter.oauth_token; 266 | var verifier = callbackRequest.parameter.oauth_verifier; 267 | var token = this.getToken_(); 268 | 269 | if (!token || (requestToken && requestToken != token.public)) { 270 | throw 'Error handling callback: token mismatch'; 271 | } 272 | 273 | if (this.oauthVersion_ == '1.0a' && !verifier) { 274 | return false; 275 | } 276 | 277 | token = this.getAccessToken_(verifier); 278 | this.saveToken_(token); 279 | return true; 280 | }; 281 | 282 | /** 283 | * Determines if the service has access (has been authorized). 284 | * @return {boolean} true if the user has access to the service, false 285 | * otherwise. 286 | */ 287 | Service_.prototype.hasAccess = function() { 288 | var token = this.getToken_(); 289 | return token && token.type == 'access'; 290 | }; 291 | 292 | /** 293 | * Fetches a URL using the OAuth1 credentials of the service. Use this method 294 | * the same way you would use `UrlFetchApp.fetch()`. 295 | * @param {string} url The URL to fetch. 296 | * @param {Object} params The request parameters. See the corresponding method 297 | * in `UrlFetchApp`. 298 | * @returns {UrlFetchApp.HTTPResponse} The response. 299 | */ 300 | Service_.prototype.fetch = function(url, params) { 301 | if (!this.hasAccess()) { 302 | throw 'Service not authorized.'; 303 | } 304 | var token = this.getToken_(); 305 | return this.fetchInternal_(url, params, token); 306 | }; 307 | 308 | /** 309 | * Resets the service, removing access and requiring the service to be 310 | * re-authorized. 311 | */ 312 | Service_.prototype.reset = function() { 313 | validate_({ 314 | 'Property store': this.propertyStore_ 315 | }); 316 | var key = this.getPropertyKey_(); 317 | this.propertyStore_.deleteProperty(key); 318 | if (this.cache_) { 319 | this.cache_.remove(key); 320 | } 321 | }; 322 | 323 | /** 324 | * Get a new request token. 325 | * @returns {Object} A request token. 326 | */ 327 | Service_.prototype.getRequestToken_ = function() { 328 | validate_({ 329 | 'Request Token URL': this.requestTokenUrl_, 330 | 'Method': this.method_, 331 | }); 332 | var url = this.requestTokenUrl_; 333 | var params = { 334 | method: this.method_, 335 | muteHttpExceptions: true 336 | }; 337 | var oauthParams = {}; 338 | if (this.oauthVersion_ == '1.0a') { 339 | oauthParams.oauth_callback = this.getCallbackUrl(); 340 | } 341 | 342 | var response = this.fetchInternal_(url, params, null, oauthParams); 343 | if (response.getResponseCode() >= 400) { 344 | throw 'Error starting OAuth flow: ' + response.getContentText(); 345 | } 346 | 347 | var token = this.parseToken_(response.getContentText()); 348 | token.type = 'request'; 349 | return token; 350 | }; 351 | 352 | /** 353 | * Get a new access token. 354 | * @param {string} opt_verifier The value of the `oauth_verifier` URL parameter 355 | * in the callback. Not used by OAuth version '1.0'. 356 | * @returns {Object} An access token. 357 | */ 358 | Service_.prototype.getAccessToken_ = function(opt_verifier) { 359 | validate_({ 360 | 'Access Token URL': this.accessTokenUrl_, 361 | 'Method': this.method_ 362 | }); 363 | var url = this.accessTokenUrl_; 364 | var params = { 365 | method: this.method_, 366 | muteHttpExceptions: true 367 | }; 368 | var token = this.getToken_(); 369 | 370 | var oauthParams = {}; 371 | if (opt_verifier) { 372 | oauthParams.oauth_verifier = opt_verifier; 373 | } 374 | 375 | var response = this.fetchInternal_(url, params, token, oauthParams); 376 | if (response.getResponseCode() >= 400) { 377 | throw 'Error completing OAuth flow: ' + response.getContentText(); 378 | } 379 | 380 | token = this.parseToken_(response.getContentText()); 381 | token.type = 'access'; 382 | return token; 383 | }; 384 | 385 | /** 386 | * Makes a `UrlFetchApp` request using the optional OAuth1 token and/or 387 | * additional parameters. 388 | * @param {string} url The URL to fetch. 389 | * @param {Object} params The request parameters. See the corresponding method 390 | * in `UrlFetchApp`. 391 | * @params {Object} opt_token OAuth token to use to sign the request (optional). 392 | * @param {Object} opt_oauthParams Additional OAuth parameters to use when 393 | * signing the request (optional). 394 | * @returns {UrlFetchApp.HTTPResponse} The response. 395 | */ 396 | Service_.prototype.fetchInternal_ = function(url, params, opt_token, 397 | opt_oauthParams) { 398 | validate_({ 399 | 'URL': url, 400 | 'OAuth Parameter Location': this.paramLocation_, 401 | 'Consumer Key': this.consumerKey_, 402 | 'Consumer Secret': this.consumerSecret_ 403 | }); 404 | params = params || {}; 405 | params.method = params.method || 'get'; 406 | var token = opt_token || null; 407 | var oauthParams = opt_oauthParams || null; 408 | var signer = new Signer({ 409 | signature_method: this.signatureMethod_, 410 | consumer: { 411 | public: this.consumerKey_, 412 | secret: this.consumerSecret_ 413 | } 414 | }); 415 | var request = { 416 | url: url, 417 | method: params.method 418 | }; 419 | if (params.payload && (!params.contentType || 420 | params.contentType == 'application/x-www-form-urlencoded')) { 421 | var data = params.payload; 422 | if (typeof(data) == 'string') { 423 | data = signer.deParam(data); 424 | } 425 | request.data = data; 426 | } 427 | oauthParams = signer.authorize(request, token, oauthParams); 428 | if (this.realm_ != null) { 429 | oauthParams.realm = this.realm_; 430 | } 431 | switch (this.paramLocation_) { 432 | case 'auth-header': 433 | params.headers = 434 | assign_({}, params.headers, signer.toHeader(oauthParams)); 435 | break; 436 | case 'uri-query': 437 | url = buildUrl_(url, oauthParams); 438 | break; 439 | case 'post-body': 440 | // Clone the payload. 441 | params.payload = assign_({}, params.payload, oauthParams); 442 | break; 443 | default: 444 | throw 'Unknown param location: ' + this.paramLocation_; 445 | } 446 | if (params.payload && (!params.contentType || 447 | params.contentType == 'application/x-www-form-urlencoded')) { 448 | // Disable UrlFetchApp escaping and use the signer's escaping instead. 449 | // This will ensure that the escaping is consistent between the signature and the request. 450 | var payload = request.data; 451 | payload = Object.keys(payload).map(function(key) { 452 | return signer.percentEncode(key) + '=' + signer.percentEncode(payload[key]); 453 | }).join('&'); 454 | params.payload = payload; 455 | params.escaping = false; 456 | } 457 | return UrlFetchApp.fetch(url, params); 458 | }; 459 | 460 | /** 461 | * Parses the token from the response. 462 | * @param {string} content The serialized token content. 463 | * @return {Object} The parsed token. 464 | * @private 465 | */ 466 | Service_.prototype.parseToken_ = function(content) { 467 | var token = content.split('&').reduce(function(result, pair) { 468 | var parts = pair.split('='); 469 | result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); 470 | return result; 471 | }, {}); 472 | // Verify that the response contains a token. 473 | if (!token.oauth_token) { 474 | throw 'Error parsing token: key "oauth_token" not found'; 475 | } 476 | // Set fields that the signing library expects. 477 | token.public = token.oauth_token; 478 | token.secret = token.oauth_token_secret; 479 | return token; 480 | }; 481 | 482 | /** 483 | * Saves a token to the service's property store and cache. 484 | * @param {Object} token The token to save. 485 | * @private 486 | */ 487 | Service_.prototype.saveToken_ = function(token) { 488 | validate_({ 489 | 'Property store': this.propertyStore_ 490 | }); 491 | var key = this.getPropertyKey_(); 492 | var value = JSON.stringify(token); 493 | this.propertyStore_.setProperty(key, value); 494 | if (this.cache_) { 495 | this.cache_.put(key, value, Service_.MAX_CACHE_TIME); 496 | } 497 | }; 498 | 499 | /** 500 | * Gets the token from the service's property store or cache. 501 | * @return {Object} The token, or null if no token was found. 502 | * @private 503 | */ 504 | Service_.prototype.getToken_ = function() { 505 | validate_({ 506 | 'Property store': this.propertyStore_ 507 | }); 508 | var key = this.getPropertyKey_(); 509 | var token; 510 | if (this.cache_) { 511 | token = this.cache_.get(key); 512 | } 513 | if (!token) { 514 | token = this.propertyStore_.getProperty(key); 515 | } 516 | if (token) { 517 | if (this.cache_) { 518 | this.cache_.put(key, token, Service_.MAX_CACHE_TIME); 519 | } 520 | return JSON.parse(token); 521 | } else { 522 | return null; 523 | } 524 | }; 525 | 526 | /** 527 | * Generates the property key for this service. 528 | * @return {string} The property key. 529 | * @private 530 | */ 531 | Service_.prototype.getPropertyKey_ = function() { 532 | return 'oauth1.' + this.serviceName_; 533 | }; 534 | 535 | /** 536 | * Gets a callback URL to use for the OAuth flow. 537 | * @return {string} A callback URL. 538 | */ 539 | Service_.prototype.getCallbackUrl = function() { 540 | validate_({ 541 | 'Callback Function Name': this.callbackFunctionName_, 542 | 'Service Name': this.serviceName_, 543 | 'Script ID': this.scriptId_ 544 | }); 545 | var stateToken = eval('Script' + 'App').newStateToken() 546 | .withMethod(this.callbackFunctionName_) 547 | .withArgument('serviceName', this.serviceName_) 548 | .withTimeout(3600) 549 | .createToken(); 550 | return buildUrl_(getCallbackUrl(this.scriptId_), { 551 | state: stateToken 552 | }); 553 | }; 554 | -------------------------------------------------------------------------------- /.github/linters/sun_checks.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 18 | 19 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 65 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 82 | 83 | 84 | 86 | 87 | 88 | 94 | 95 | 96 | 97 | 100 | 101 | 102 | 103 | 104 | 108 | 109 | 110 | 111 | 112 | 114 | 115 | 116 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 135 | 137 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 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 | 185 | 186 | 187 | 189 | 191 | 192 | 193 | 194 | 196 | 197 | 198 | 199 | 201 | 202 | 203 | 204 | 206 | 207 | 208 | 209 | 211 | 212 | 213 | 214 | 216 | 217 | 218 | 219 | 221 | 222 | 223 | 224 | 226 | 227 | 228 | 229 | 231 | 232 | 233 | 234 | 236 | 237 | 238 | 239 | 241 | 242 | 243 | 244 | 246 | 247 | 248 | 249 | 251 | 253 | 255 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 287 | 288 | 289 | 292 | 293 | 294 | 295 | 301 | 302 | 303 | 304 | 308 | 309 | 310 | 311 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 326 | 327 | 328 | 329 | 330 | 331 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 347 | 348 | 349 | 350 | 353 | 354 | 355 | 356 | 357 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 371 | 372 | 373 | 374 | -------------------------------------------------------------------------------- /dist/OAuth1.gs: -------------------------------------------------------------------------------- 1 | (function (host, expose) { 2 | var module = { exports: {} }; 3 | var exports = module.exports; 4 | /****** code begin *********/ 5 | /** 6 | * Creates a new MemoryProperties, an implementation of the Properties 7 | * interface that stores values in memory. 8 | * @constructor 9 | */ 10 | var MemoryProperties = function() { 11 | this.properties = {}; 12 | }; 13 | 14 | /** 15 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#deleteallproperties} 16 | */ 17 | MemoryProperties.prototype.deleteAllProperties = function() { 18 | this.properties = {}; 19 | }; 20 | 21 | /** 22 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#deletepropertykey} 23 | */ 24 | MemoryProperties.prototype.deleteProperty = function(key) { 25 | delete this.properties[key]; 26 | }; 27 | 28 | /** 29 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#getkeys} 30 | */ 31 | MemoryProperties.prototype.getKeys = function() { 32 | return Object.keys(this.properties); 33 | }; 34 | 35 | /** 36 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#getproperties} 37 | */ 38 | MemoryProperties.prototype.getProperties = function() { 39 | return extend_({}, this.properties); 40 | }; 41 | 42 | /** 43 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#getproperty} 44 | */ 45 | MemoryProperties.prototype.getProperty = function(key) { 46 | return this.properties[key]; 47 | }; 48 | 49 | /** 50 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#setpropertiesproperties-deleteallothers} 51 | */ 52 | MemoryProperties.prototype.setProperties = function(properties, opt_deleteAllOthers) { 53 | if (opt_deleteAllOthers) { 54 | this.deleteAllProperties(); 55 | } 56 | Object.keys(properties).forEach(function(key) { 57 | this.setProperty(key, properties[key]); 58 | }); 59 | }; 60 | 61 | /** 62 | * @see {@link https://developers.google.com/apps-script/reference/properties/properties#setpropertykey-value} 63 | */ 64 | MemoryProperties.prototype.setProperty = function(key, value) { 65 | this.properties[key] = String(value); 66 | }; 67 | 68 | // Copyright 2015 Google Inc. All Rights Reserved. 69 | // 70 | // Licensed under the Apache License, Version 2.0 (the "License"); 71 | // you may not use this file except in compliance with the License. 72 | // You may obtain a copy of the License at 73 | // 74 | // http://www.apache.org/licenses/LICENSE-2.0 75 | // 76 | // Unless required by applicable law or agreed to in writing, software 77 | // distributed under the License is distributed on an "AS IS" BASIS, 78 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 79 | // See the License for the specific language governing permissions and 80 | // limitations under the License. 81 | 82 | /** 83 | * @fileoverview Contains the methods exposed by the library, and performs any 84 | * required setup. 85 | */ 86 | 87 | /** 88 | * Creates a new OAuth1 service with the name specified. It's usually best to 89 | * create and configure your service once at the start of your script, and then 90 | * reference it during the different phases of the authorization flow. 91 | * @param {string} serviceName The name of the service. 92 | * @return {Service_} The service object. 93 | */ 94 | function createService(serviceName) { 95 | return new Service_(serviceName); 96 | } 97 | 98 | /** 99 | * Returns the callback URL that will be used for a given script. Often this URL 100 | * needs to be entered into a configuration screen of your OAuth provider. 101 | * @param {string} scriptId The ID of your script, which can be found in the 102 | * Script Editor UI under "File > Project properties". 103 | * @return {string} The callback URL. 104 | */ 105 | function getCallbackUrl(scriptId) { 106 | return Utilities.formatString( 107 | 'https://script.google.com/macros/d/%s/usercallback', scriptId); 108 | } 109 | 110 | if (typeof module != 'undefined') { 111 | module.exports = { 112 | createService: createService, 113 | getCallbackUrl: getCallbackUrl, 114 | MemoryProperties: MemoryProperties 115 | }; 116 | } 117 | 118 | // Copyright 2015 Google Inc. All Rights Reserved. 119 | // 120 | // Licensed under the Apache License, Version 2.0 (the "License"); 121 | // you may not use this file except in compliance with the License. 122 | // You may obtain a copy of the License at 123 | // 124 | // http://www.apache.org/licenses/LICENSE-2.0 125 | // 126 | // Unless required by applicable law or agreed to in writing, software 127 | // distributed under the License is distributed on an "AS IS" BASIS, 128 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 129 | // See the License for the specific language governing permissions and 130 | // limitations under the License. 131 | 132 | /** 133 | * @fileoverview Contains the Service_ class. 134 | */ 135 | 136 | // Disable JSHint warnings for the use of eval(), since it's required to prevent 137 | // scope issues in Apps Script. 138 | // jshint evil:true 139 | 140 | /** 141 | * Creates a new OAuth1 service. 142 | * @param {string} serviceName The name of the service. 143 | * @constructor 144 | */ 145 | var Service_ = function(serviceName) { 146 | validate_({ 147 | 'Service name': serviceName 148 | }); 149 | this.serviceName_ = serviceName; 150 | this.paramLocation_ = 'auth-header'; 151 | this.method_ = 'get'; 152 | this.oauthVersion_ = '1.0a'; 153 | this.scriptId_ = eval('Script' + 'App').getScriptId(); 154 | this.signatureMethod_ = 'HMAC-SHA1'; 155 | this.propertyStore_ = new MemoryProperties(); 156 | }; 157 | 158 | /** 159 | * The maximum amount of time that information can be cached. 160 | * @type {Number} 161 | */ 162 | Service_.MAX_CACHE_TIME = 21600; 163 | 164 | /** 165 | * Sets the request URL for the OAuth service (required). 166 | * @param {string} url The URL given by the OAuth service provider for obtaining 167 | * a request token. 168 | * @return {Service_} This service, for chaining. 169 | */ 170 | Service_.prototype.setRequestTokenUrl = function(url) { 171 | this.requestTokenUrl_ = url; 172 | return this; 173 | }; 174 | 175 | /** 176 | * Sets the URL for the OAuth authorization service (required). 177 | * @param {string} url The URL given by the OAuth service provider for 178 | * authorizing a token. 179 | * @return {Service_} This service, for chaining. 180 | */ 181 | Service_.prototype.setAuthorizationUrl = function(url) { 182 | this.authorizationUrl_ = url; 183 | return this; 184 | }; 185 | 186 | /** 187 | * Sets the URL to get an OAuth access token from (required). 188 | * @param {string} url The URL given by the OAuth service provider for obtaining 189 | * an access token. 190 | * @return {Service_} This service, for chaining. 191 | */ 192 | Service_.prototype.setAccessTokenUrl = function(url) { 193 | this.accessTokenUrl_ = url; 194 | return this; 195 | }; 196 | 197 | /** 198 | * Sets the parameter location in OAuth protocol requests (optional). The 199 | * default parameter location is 'auth-header'. 200 | * @param {string} location The parameter location for the OAuth request. 201 | * Allowed values are 'post-body', 'uri-query' and 'auth-header'. 202 | * @return {Service_} This service, for chaining. 203 | */ 204 | Service_.prototype.setParamLocation = function(location) { 205 | this.paramLocation_ = location; 206 | return this; 207 | }; 208 | 209 | /** 210 | * Sets the HTTP method used to complete the OAuth protocol (optional). The 211 | * default method is 'get'. 212 | * @param {string} method The method to be used with this service. Allowed 213 | * values are 'get' and 'post'. 214 | * @return {Service_} This service, for chaining. 215 | */ 216 | Service_.prototype.setMethod = function(method) { 217 | this.method_ = method; 218 | return this; 219 | }; 220 | 221 | /** 222 | * Sets the OAuth realm parameter to be used with this service (optional). 223 | * @param {string} realm The realm to be used with this service. 224 | * @return {Service_} This service, for chaining. 225 | */ 226 | Service_.prototype.setRealm = function(realm) { 227 | this.realm_ = realm; 228 | return this; 229 | }; 230 | 231 | /** 232 | * Sets the OAuth signature method to use. 'HMAC-SHA1' is the default. 233 | * @param {string} signatureMethod The OAuth signature method. Allowed values 234 | * are 'HMAC-SHA1', 'RSA-SHA1' and 'PLAINTEXT'. 235 | * @return {Service_} This service, for chaining. 236 | */ 237 | Service_.prototype.setSignatureMethod = function(signatureMethod) { 238 | this.signatureMethod_ = signatureMethod; 239 | return this; 240 | }; 241 | 242 | /** 243 | * Sets the specific OAuth version to use. The default is '1.0a'. 244 | * @param {string} oauthVersion The OAuth version. Allowed values are '1.0a' 245 | * and '1.0'. 246 | * @return {Service_} This service, for chaining. 247 | */ 248 | Service_.prototype.setOAuthVersion = function(oauthVersion) { 249 | this.oauthVersion_ = oauthVersion; 250 | return this; 251 | }; 252 | 253 | /** 254 | * Sets the ID of the script that contains the authorization callback 255 | * function (required). The script ID can be found in the Script Editor UI 256 | * under "File > Project properties". 257 | * @param {string} scriptId The ID of the script containing the callback 258 | * function. 259 | * @return {Service_} This service, for chaining. 260 | * @deprecated The script ID is now be determined automatically. 261 | */ 262 | Service_.prototype.setScriptId = function(scriptId) { 263 | this.scriptId_ = scriptId; 264 | return this; 265 | }; 266 | 267 | /** 268 | * Sets the name of the authorization callback function (required). This is the 269 | * function that will be called when the user completes the authorization flow 270 | * on the service provider's website. The callback accepts a request parameter, 271 | * which should be passed to this service's handleCallback() method 272 | * to complete the process. 273 | * @param {string} callbackFunctionName The name of the callback function. 274 | * @return {Service_} This service, for chaining. 275 | */ 276 | Service_.prototype.setCallbackFunction = function(callbackFunctionName) { 277 | this.callbackFunctionName_ = callbackFunctionName; 278 | return this; 279 | }; 280 | 281 | /** 282 | * Sets the consumer key, which is provided when you register with an OAuth 283 | * service (required). 284 | * @param {string} consumerKey The consumer key provided by the OAuth service 285 | * provider. 286 | * @return {Service_} This service, for chaining. 287 | */ 288 | Service_.prototype.setConsumerKey = function(consumerKey) { 289 | this.consumerKey_ = consumerKey; 290 | return this; 291 | }; 292 | 293 | /** 294 | * Sets the consumer secret, which is provided when you register with an OAuth 295 | * service (required). 296 | * @param {string} consumerSecret The consumer secret provided by the OAuth 297 | * service provider. 298 | * @return {Service_} This service, for chaining. 299 | */ 300 | Service_.prototype.setConsumerSecret = function(consumerSecret) { 301 | this.consumerSecret_ = consumerSecret; 302 | return this; 303 | }; 304 | 305 | /** 306 | * Sets the property store to use when persisting credentials (optional). In 307 | * most cases this should be user properties, but document or script properties 308 | * may be appropriate if you want to share access across users. If not set tokens 309 | * will be stored in memory only. 310 | * @param {PropertiesService.Properties} propertyStore The property store to use 311 | * when persisting credentials. 312 | * @return {Service_} This service, for chaining. 313 | */ 314 | Service_.prototype.setPropertyStore = function(propertyStore) { 315 | this.propertyStore_ = propertyStore; 316 | return this; 317 | }; 318 | 319 | /** 320 | * Sets the cache to use when persisting credentials (optional). Using a cache 321 | * will reduce the need to read from the property store and may increase 322 | * performance. In most cases this should be a private cache, but a public cache 323 | * may be appropriate if you want to share access across users. 324 | * @param {CacheService.Cache} cache The cache to use when persisting 325 | * credentials. 326 | * @return {Service_} This service, for chaining. 327 | */ 328 | Service_.prototype.setCache = function(cache) { 329 | this.cache_ = cache; 330 | return this; 331 | }; 332 | 333 | /** 334 | * Sets the access token and token secret to use (optional). For use with APIs 335 | * that support a 1-legged flow where no user interaction is required. 336 | * @param {string} token The access token. 337 | * @param {string} secret The token secret. 338 | * @return {Service_} This service, for chaining. 339 | */ 340 | Service_.prototype.setAccessToken = function(token, secret) { 341 | this.saveToken_({ 342 | public: token, 343 | secret: secret, 344 | type: 'access' 345 | }); 346 | return this; 347 | }; 348 | 349 | /** 350 | * Starts the authorization process. A new token will be generated and the 351 | * authorization URL for that token will be returned. Have the user visit this 352 | * URL and approve the authorization request. The user will then be redirected 353 | * back to your application using the script ID and callback function name 354 | * specified, so that the flow may continue. 355 | * @returns {string} The authorization URL for a new token. 356 | */ 357 | Service_.prototype.authorize = function() { 358 | validate_({ 359 | 'Authorization URL': this.authorizationUrl_ 360 | }); 361 | 362 | var token = this.getRequestToken_(); 363 | this.saveToken_(token); 364 | 365 | var oauthParams = { 366 | oauth_token: token.public 367 | }; 368 | if (this.oauthVersion_ == '1.0') { 369 | oauthParams.oauth_callback = this.getCallbackUrl(); 370 | } 371 | return buildUrl_(this.authorizationUrl_, oauthParams); 372 | }; 373 | 374 | /** 375 | * Completes the OAuth1 flow using the request data passed in to the callback 376 | * function. 377 | * @param {Object} callbackRequest The request data recieved from the callback 378 | * function. 379 | * @return {boolean} True if authorization was granted, false if it was denied. 380 | */ 381 | Service_.prototype.handleCallback = function(callbackRequest) { 382 | var requestToken = callbackRequest.parameter.oauth_token; 383 | var verifier = callbackRequest.parameter.oauth_verifier; 384 | var token = this.getToken_(); 385 | 386 | if (!token || (requestToken && requestToken != token.public)) { 387 | throw 'Error handling callback: token mismatch'; 388 | } 389 | 390 | if (this.oauthVersion_ == '1.0a' && !verifier) { 391 | return false; 392 | } 393 | 394 | token = this.getAccessToken_(verifier); 395 | this.saveToken_(token); 396 | return true; 397 | }; 398 | 399 | /** 400 | * Determines if the service has access (has been authorized). 401 | * @return {boolean} true if the user has access to the service, false 402 | * otherwise. 403 | */ 404 | Service_.prototype.hasAccess = function() { 405 | var token = this.getToken_(); 406 | return token && token.type == 'access'; 407 | }; 408 | 409 | /** 410 | * Fetches a URL using the OAuth1 credentials of the service. Use this method 411 | * the same way you would use `UrlFetchApp.fetch()`. 412 | * @param {string} url The URL to fetch. 413 | * @param {Object} params The request parameters. See the corresponding method 414 | * in `UrlFetchApp`. 415 | * @returns {UrlFetchApp.HTTPResponse} The response. 416 | */ 417 | Service_.prototype.fetch = function(url, params) { 418 | if (!this.hasAccess()) { 419 | throw 'Service not authorized.'; 420 | } 421 | var token = this.getToken_(); 422 | return this.fetchInternal_(url, params, token); 423 | }; 424 | 425 | /** 426 | * Resets the service, removing access and requiring the service to be 427 | * re-authorized. 428 | */ 429 | Service_.prototype.reset = function() { 430 | validate_({ 431 | 'Property store': this.propertyStore_ 432 | }); 433 | var key = this.getPropertyKey_(); 434 | this.propertyStore_.deleteProperty(key); 435 | if (this.cache_) { 436 | this.cache_.remove(key); 437 | } 438 | }; 439 | 440 | /** 441 | * Get a new request token. 442 | * @returns {Object} A request token. 443 | */ 444 | Service_.prototype.getRequestToken_ = function() { 445 | validate_({ 446 | 'Request Token URL': this.requestTokenUrl_, 447 | 'Method': this.method_, 448 | }); 449 | var url = this.requestTokenUrl_; 450 | var params = { 451 | method: this.method_, 452 | muteHttpExceptions: true 453 | }; 454 | var oauthParams = {}; 455 | if (this.oauthVersion_ == '1.0a') { 456 | oauthParams.oauth_callback = this.getCallbackUrl(); 457 | } 458 | 459 | var response = this.fetchInternal_(url, params, null, oauthParams); 460 | if (response.getResponseCode() >= 400) { 461 | throw 'Error starting OAuth flow: ' + response.getContentText(); 462 | } 463 | 464 | var token = this.parseToken_(response.getContentText()); 465 | token.type = 'request'; 466 | return token; 467 | }; 468 | 469 | /** 470 | * Get a new access token. 471 | * @param {string} opt_verifier The value of the `oauth_verifier` URL parameter 472 | * in the callback. Not used by OAuth version '1.0'. 473 | * @returns {Object} An access token. 474 | */ 475 | Service_.prototype.getAccessToken_ = function(opt_verifier) { 476 | validate_({ 477 | 'Access Token URL': this.accessTokenUrl_, 478 | 'Method': this.method_ 479 | }); 480 | var url = this.accessTokenUrl_; 481 | var params = { 482 | method: this.method_, 483 | muteHttpExceptions: true 484 | }; 485 | var token = this.getToken_(); 486 | 487 | var oauthParams = {}; 488 | if (opt_verifier) { 489 | oauthParams.oauth_verifier = opt_verifier; 490 | } 491 | 492 | var response = this.fetchInternal_(url, params, token, oauthParams); 493 | if (response.getResponseCode() >= 400) { 494 | throw 'Error completing OAuth flow: ' + response.getContentText(); 495 | } 496 | 497 | token = this.parseToken_(response.getContentText()); 498 | token.type = 'access'; 499 | return token; 500 | }; 501 | 502 | /** 503 | * Makes a `UrlFetchApp` request using the optional OAuth1 token and/or 504 | * additional parameters. 505 | * @param {string} url The URL to fetch. 506 | * @param {Object} params The request parameters. See the corresponding method 507 | * in `UrlFetchApp`. 508 | * @params {Object} opt_token OAuth token to use to sign the request (optional). 509 | * @param {Object} opt_oauthParams Additional OAuth parameters to use when 510 | * signing the request (optional). 511 | * @returns {UrlFetchApp.HTTPResponse} The response. 512 | */ 513 | Service_.prototype.fetchInternal_ = function(url, params, opt_token, 514 | opt_oauthParams) { 515 | validate_({ 516 | 'URL': url, 517 | 'OAuth Parameter Location': this.paramLocation_, 518 | 'Consumer Key': this.consumerKey_, 519 | 'Consumer Secret': this.consumerSecret_ 520 | }); 521 | params = params || {}; 522 | params.method = params.method || 'get'; 523 | var token = opt_token || null; 524 | var oauthParams = opt_oauthParams || null; 525 | var signer = new Signer({ 526 | signature_method: this.signatureMethod_, 527 | consumer: { 528 | public: this.consumerKey_, 529 | secret: this.consumerSecret_ 530 | } 531 | }); 532 | var request = { 533 | url: url, 534 | method: params.method 535 | }; 536 | if (params.payload && (!params.contentType || 537 | params.contentType == 'application/x-www-form-urlencoded')) { 538 | var data = params.payload; 539 | if (typeof(data) == 'string') { 540 | data = signer.deParam(data); 541 | } 542 | request.data = data; 543 | } 544 | oauthParams = signer.authorize(request, token, oauthParams); 545 | if (this.realm_ != null) { 546 | oauthParams.realm = this.realm_; 547 | } 548 | switch (this.paramLocation_) { 549 | case 'auth-header': 550 | params.headers = 551 | assign_({}, params.headers, signer.toHeader(oauthParams)); 552 | break; 553 | case 'uri-query': 554 | url = buildUrl_(url, oauthParams); 555 | break; 556 | case 'post-body': 557 | // Clone the payload. 558 | params.payload = assign_({}, params.payload, oauthParams); 559 | break; 560 | default: 561 | throw 'Unknown param location: ' + this.paramLocation_; 562 | } 563 | if (params.payload && (!params.contentType || 564 | params.contentType == 'application/x-www-form-urlencoded')) { 565 | // Disable UrlFetchApp escaping and use the signer's escaping instead. 566 | // This will ensure that the escaping is consistent between the signature and the request. 567 | var payload = request.data; 568 | payload = Object.keys(payload).map(function(key) { 569 | return signer.percentEncode(key) + '=' + signer.percentEncode(payload[key]); 570 | }).join('&'); 571 | params.payload = payload; 572 | params.escaping = false; 573 | } 574 | return UrlFetchApp.fetch(url, params); 575 | }; 576 | 577 | /** 578 | * Parses the token from the response. 579 | * @param {string} content The serialized token content. 580 | * @return {Object} The parsed token. 581 | * @private 582 | */ 583 | Service_.prototype.parseToken_ = function(content) { 584 | var token = content.split('&').reduce(function(result, pair) { 585 | var parts = pair.split('='); 586 | result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); 587 | return result; 588 | }, {}); 589 | // Verify that the response contains a token. 590 | if (!token.oauth_token) { 591 | throw 'Error parsing token: key "oauth_token" not found'; 592 | } 593 | // Set fields that the signing library expects. 594 | token.public = token.oauth_token; 595 | token.secret = token.oauth_token_secret; 596 | return token; 597 | }; 598 | 599 | /** 600 | * Saves a token to the service's property store and cache. 601 | * @param {Object} token The token to save. 602 | * @private 603 | */ 604 | Service_.prototype.saveToken_ = function(token) { 605 | validate_({ 606 | 'Property store': this.propertyStore_ 607 | }); 608 | var key = this.getPropertyKey_(); 609 | var value = JSON.stringify(token); 610 | this.propertyStore_.setProperty(key, value); 611 | if (this.cache_) { 612 | this.cache_.put(key, value, Service_.MAX_CACHE_TIME); 613 | } 614 | }; 615 | 616 | /** 617 | * Gets the token from the service's property store or cache. 618 | * @return {Object} The token, or null if no token was found. 619 | * @private 620 | */ 621 | Service_.prototype.getToken_ = function() { 622 | validate_({ 623 | 'Property store': this.propertyStore_ 624 | }); 625 | var key = this.getPropertyKey_(); 626 | var token; 627 | if (this.cache_) { 628 | token = this.cache_.get(key); 629 | } 630 | if (!token) { 631 | token = this.propertyStore_.getProperty(key); 632 | } 633 | if (token) { 634 | if (this.cache_) { 635 | this.cache_.put(key, token, Service_.MAX_CACHE_TIME); 636 | } 637 | return JSON.parse(token); 638 | } else { 639 | return null; 640 | } 641 | }; 642 | 643 | /** 644 | * Generates the property key for this service. 645 | * @return {string} The property key. 646 | * @private 647 | */ 648 | Service_.prototype.getPropertyKey_ = function() { 649 | return 'oauth1.' + this.serviceName_; 650 | }; 651 | 652 | /** 653 | * Gets a callback URL to use for the OAuth flow. 654 | * @return {string} A callback URL. 655 | */ 656 | Service_.prototype.getCallbackUrl = function() { 657 | validate_({ 658 | 'Callback Function Name': this.callbackFunctionName_, 659 | 'Service Name': this.serviceName_, 660 | 'Script ID': this.scriptId_ 661 | }); 662 | var stateToken = eval('Script' + 'App').newStateToken() 663 | .withMethod(this.callbackFunctionName_) 664 | .withArgument('serviceName', this.serviceName_) 665 | .withTimeout(3600) 666 | .createToken(); 667 | return buildUrl_(getCallbackUrl(this.scriptId_), { 668 | state: stateToken 669 | }); 670 | }; 671 | 672 | // The MIT License (MIT) 673 | // 674 | // Copyright (c) 2014 Ddo 675 | // 676 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 677 | // this software and associated documentation files (the "Software"), to deal in 678 | // the Software without restriction, including without limitation the rights to 679 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 680 | // the Software, and to permit persons to whom the Software is furnished to do so, 681 | // subject to the following conditions: 682 | // 683 | // The above copyright notice and this permission notice shall be included in all 684 | // copies or substantial portions of the Software. 685 | // 686 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 687 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 688 | // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 689 | // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 690 | // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 691 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 692 | 693 | /** 694 | * A modified version of the oauth-1.0a javascript library: 695 | * https://github.com/ddo/oauth-1.0a 696 | * The cryptojs dependency was removed in favor of native Apps Script functions. 697 | * A new parameter was added to authorize() for additional oauth params. 698 | * Support for realm authorization parameter was added in toHeader(). 699 | */ 700 | 701 | (function(global) { 702 | /** 703 | * Constructor 704 | * @param {Object} opts consumer key and secret 705 | */ 706 | function OAuth(opts) { 707 | if(!(this instanceof OAuth)) { 708 | return new OAuth(opts); 709 | } 710 | 711 | if(!opts) { 712 | opts = {}; 713 | } 714 | 715 | if(!opts.consumer) { 716 | throw new Error('consumer option is required'); 717 | } 718 | 719 | this.consumer = opts.consumer; 720 | this.signature_method = opts.signature_method || 'HMAC-SHA1'; 721 | this.nonce_length = opts.nonce_length || 32; 722 | this.version = opts.version || '1.0'; 723 | this.parameter_seperator = opts.parameter_seperator || ', '; 724 | 725 | if(typeof opts.last_ampersand === 'undefined') { 726 | this.last_ampersand = true; 727 | } else { 728 | this.last_ampersand = opts.last_ampersand; 729 | } 730 | 731 | switch (this.signature_method) { 732 | case 'HMAC-SHA1': 733 | this.hash = function(base_string, key) { 734 | var sig = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_1, base_string, key); 735 | return Utilities.base64Encode(sig); 736 | }; 737 | break; 738 | case 'PLAINTEXT': 739 | this.hash = function(base_string, key) { 740 | return key; 741 | }; 742 | break; 743 | case 'RSA-SHA1': 744 | this.hash = function(base_string, key) { 745 | var sig = Utilities.computeRsaSignature(Utilities.RsaAlgorithm.RSA_SHA_1, base_string, key); 746 | return Utilities.base64Encode(sig); 747 | }; 748 | break; 749 | default: 750 | throw new Error('The OAuth 1.0a protocol defines three signature methods: HMAC-SHA1, RSA-SHA1, and PLAINTEXT only'); 751 | } 752 | } 753 | 754 | /** 755 | * OAuth request authorize 756 | * @param {Object} request data 757 | * { 758 | * method, 759 | * url, 760 | * data 761 | * } 762 | * @param {Object} public and secret token 763 | * @return {Object} OAuth Authorized data 764 | */ 765 | OAuth.prototype.authorize = function(request, token, opt_oauth_data) { 766 | var oauth_data = { 767 | oauth_consumer_key: this.consumer.public, 768 | oauth_nonce: this.getNonce(), 769 | oauth_signature_method: this.signature_method, 770 | oauth_timestamp: this.getTimeStamp(), 771 | oauth_version: this.version 772 | }; 773 | 774 | if (opt_oauth_data) { 775 | oauth_data = this.mergeObject(oauth_data, opt_oauth_data); 776 | } 777 | 778 | if(!token) { 779 | token = {}; 780 | } 781 | 782 | if(token.public) { 783 | oauth_data.oauth_token = token.public; 784 | } 785 | 786 | if(!request.data) { 787 | request.data = {}; 788 | } 789 | 790 | oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data); 791 | 792 | return oauth_data; 793 | }; 794 | 795 | /** 796 | * Create a OAuth Signature 797 | * @param {Object} request data 798 | * @param {Object} token_secret public and secret token 799 | * @param {Object} oauth_data OAuth data 800 | * @return {String} Signature 801 | */ 802 | OAuth.prototype.getSignature = function(request, token_secret, oauth_data) { 803 | return this.hash(this.getBaseString(request, oauth_data), this.getSigningKey(token_secret)); 804 | }; 805 | 806 | /** 807 | * Base String = Method + Base Url + ParameterString 808 | * @param {Object} request data 809 | * @param {Object} OAuth data 810 | * @return {String} Base String 811 | */ 812 | OAuth.prototype.getBaseString = function(request, oauth_data) { 813 | return request.method.toUpperCase() + '&' + this.percentEncode(this.getBaseUrl(request.url)) + '&' + this.percentEncode(this.getParameterString(request, oauth_data)); 814 | }; 815 | 816 | /** 817 | * Get data from url 818 | * -> merge with oauth data 819 | * -> percent encode key & value 820 | * -> sort 821 | * 822 | * @param {Object} request data 823 | * @param {Object} OAuth data 824 | * @return {Object} Parameter string data 825 | */ 826 | OAuth.prototype.getParameterString = function(request, oauth_data) { 827 | var base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.mergeObject(request.data, this.deParamUrl(request.url))))); 828 | 829 | var data_str = ''; 830 | 831 | //base_string_data to string 832 | for(var key in base_string_data) { 833 | data_str += key + '=' + base_string_data[key] + '&'; 834 | } 835 | 836 | //remove the last character 837 | data_str = data_str.substr(0, data_str.length - 1); 838 | return data_str; 839 | }; 840 | 841 | /** 842 | * Create a Signing Key 843 | * @param {String} token_secret Secret Token 844 | * @return {String} Signing Key 845 | */ 846 | OAuth.prototype.getSigningKey = function(token_secret) { 847 | token_secret = token_secret || ''; 848 | 849 | // Don't percent encode the signing key (PKCS#8 PEM private key) when using 850 | // the RSA-SHA1 method. The token secret is never used with the RSA-SHA1 851 | // method. 852 | if (this.signature_method === 'RSA-SHA1') { 853 | return this.consumer.secret; 854 | } 855 | 856 | if(!this.last_ampersand && !token_secret) { 857 | return this.percentEncode(this.consumer.secret); 858 | } 859 | 860 | return this.percentEncode(this.consumer.secret) + '&' + this.percentEncode(token_secret); 861 | }; 862 | 863 | /** 864 | * Get base url 865 | * @param {String} url 866 | * @return {String} 867 | */ 868 | OAuth.prototype.getBaseUrl = function(url) { 869 | return url.split('?')[0]; 870 | }; 871 | 872 | /** 873 | * Get data from String 874 | * @param {String} string 875 | * @return {Object} 876 | */ 877 | OAuth.prototype.deParam = function(string) { 878 | var arr = string.replace(/\+/g, ' ').split('&'); 879 | var data = {}; 880 | 881 | for(var i = 0; i < arr.length; i++) { 882 | var item = arr[i].split('='); 883 | data[item[0]] = decodeURIComponent(item[1]); 884 | } 885 | return data; 886 | }; 887 | 888 | /** 889 | * Get data from url 890 | * @param {String} url 891 | * @return {Object} 892 | */ 893 | OAuth.prototype.deParamUrl = function(url) { 894 | var tmp = url.split('?'); 895 | 896 | if (tmp.length === 1) 897 | return {}; 898 | 899 | return this.deParam(tmp[1]); 900 | }; 901 | 902 | /** 903 | * Percent Encode 904 | * @param {String} str 905 | * @return {String} percent encoded string 906 | */ 907 | OAuth.prototype.percentEncode = function(str) { 908 | return encodeURIComponent(str) 909 | .replace(/\!/g, "%21") 910 | .replace(/\*/g, "%2A") 911 | .replace(/\'/g, "%27") 912 | .replace(/\(/g, "%28") 913 | .replace(/\)/g, "%29"); 914 | }; 915 | 916 | /** 917 | * Percent Encode Object 918 | * @param {Object} data 919 | * @return {Object} percent encoded data 920 | */ 921 | OAuth.prototype.percentEncodeData = function(data) { 922 | var result = {}; 923 | 924 | for(var key in data) { 925 | result[this.percentEncode(key)] = this.percentEncode(data[key]); 926 | } 927 | 928 | return result; 929 | }; 930 | 931 | /** 932 | * Get OAuth data as Header 933 | * @param {Object} oauth_data 934 | * @return {String} Header data key - value 935 | */ 936 | OAuth.prototype.toHeader = function(oauth_data) { 937 | oauth_data = this.sortObject(oauth_data); 938 | 939 | var header_value = 'OAuth '; 940 | 941 | for(var key in oauth_data) { 942 | if (key !== 'realm' && key.indexOf('oauth_') === -1) 943 | continue; 944 | header_value += this.percentEncode(key) + '="' + this.percentEncode(oauth_data[key]) + '"' + this.parameter_seperator; 945 | } 946 | 947 | return { 948 | Authorization: header_value.substr(0, header_value.length - this.parameter_seperator.length) //cut the last chars 949 | }; 950 | }; 951 | 952 | /** 953 | * Create a random word characters string with input length 954 | * @return {String} a random word characters string 955 | */ 956 | OAuth.prototype.getNonce = function() { 957 | var word_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 958 | var result = ''; 959 | 960 | for(var i = 0; i < this.nonce_length; i++) { 961 | result += word_characters[parseInt(Math.random() * word_characters.length, 10)]; 962 | } 963 | 964 | return result; 965 | }; 966 | 967 | /** 968 | * Get Current Unix TimeStamp 969 | * @return {Int} current unix timestamp 970 | */ 971 | OAuth.prototype.getTimeStamp = function() { 972 | return parseInt(new Date().getTime()/1000, 10); 973 | }; 974 | 975 | ////////////////////// HELPER FUNCTIONS ////////////////////// 976 | 977 | /** 978 | * Merge object 979 | * @param {Object} obj1 980 | * @param {Object} obj2 981 | * @return {Object} 982 | */ 983 | OAuth.prototype.mergeObject = function(obj1, obj2) { 984 | var merged_obj = obj1; 985 | for(var key in obj2) { 986 | merged_obj[key] = obj2[key]; 987 | } 988 | return merged_obj; 989 | }; 990 | 991 | /** 992 | * Sort object by key 993 | * @param {Object} data 994 | * @return {Object} sorted object 995 | */ 996 | OAuth.prototype.sortObject = function(data) { 997 | var keys = Object.keys(data); 998 | var result = {}; 999 | 1000 | keys.sort(); 1001 | 1002 | for(var i = 0; i < keys.length; i++) { 1003 | var key = keys[i]; 1004 | result[key] = data[key]; 1005 | } 1006 | 1007 | return result; 1008 | }; 1009 | 1010 | global.Signer = OAuth; 1011 | })(this); 1012 | 1013 | // Copyright 2015 Google Inc. All Rights Reserved. 1014 | // 1015 | // Licensed under the Apache License, Version 2.0 (the "License"); 1016 | // you may not use this file except in compliance with the License. 1017 | // You may obtain a copy of the License at 1018 | // 1019 | // http://www.apache.org/licenses/LICENSE-2.0 1020 | // 1021 | // Unless required by applicable law or agreed to in writing, software 1022 | // distributed under the License is distributed on an "AS IS" BASIS, 1023 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1024 | // See the License for the specific language governing permissions and 1025 | // limitations under the License. 1026 | 1027 | /** 1028 | * @fileoverview Contains utility methods used by the library. 1029 | */ 1030 | 1031 | /** 1032 | * Builds a complete URL from a base URL and a map of URL parameters. 1033 | * @param {string} url The base URL. 1034 | * @param {Object.} params The URL parameters and values. 1035 | * @returns {string} The complete URL. 1036 | * @private 1037 | */ 1038 | function buildUrl_(url, params) { 1039 | var paramString = Object.keys(params).map(function(key) { 1040 | return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); 1041 | }).join('&'); 1042 | return url + (url.indexOf('?') >= 0 ? '&' : '?') + paramString; 1043 | } 1044 | 1045 | /** 1046 | * Validates that all of the values in the object are non-empty. If an empty 1047 | * value is found, and error is thrown using the key as the name. 1048 | * @param {Object.} params The values to validate. 1049 | * @private 1050 | */ 1051 | function validate_(params) { 1052 | Object.keys(params).forEach(function(name) { 1053 | var value = params[name]; 1054 | if (!value) { 1055 | throw new Error(name + ' is required.'); 1056 | } 1057 | }); 1058 | } 1059 | 1060 | /** 1061 | * Polyfill for Object.assign, which isn't available on the legacy runtime. 1062 | * Not assigning to Object to avoid overwriting behavior in the parent 1063 | * script(s). 1064 | * @param {Object} target The target object to apply the sources’ properties to, 1065 | * which is returned after it is modified. 1066 | * @param {...Object} sources The source object(s) containing the properties you 1067 | * want to apply. 1068 | * @returns {Object} The target object. 1069 | * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill} 1070 | * @license Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ 1071 | */ 1072 | function assign_(target, varArgs) { 1073 | if (typeof Object.assign === 'function') { 1074 | return Object.assign.apply(null, arguments); 1075 | } 1076 | if (target === null || target === undefined) { 1077 | throw new TypeError('Cannot convert undefined or null to object'); 1078 | } 1079 | var to = Object(target); 1080 | for (var index = 1; index < arguments.length; index++) { 1081 | var nextSource = arguments[index]; 1082 | 1083 | if (nextSource !== null && nextSource !== undefined) { 1084 | for (var nextKey in nextSource) { 1085 | // Avoid bugs when hasOwnProperty is shadowed 1086 | if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { 1087 | to[nextKey] = nextSource[nextKey]; 1088 | } 1089 | } 1090 | } 1091 | } 1092 | return to; 1093 | } 1094 | 1095 | /** 1096 | * Gets the time in seconds, rounded down to the nearest second. 1097 | * @param {Date} date The Date object to convert. 1098 | * @returns {Number} The number of seconds since the epoch. 1099 | * @private 1100 | */ 1101 | function getTimeInSeconds_(date) { 1102 | return Math.floor(date.getTime() / 1000); 1103 | } 1104 | 1105 | /****** code end *********/ 1106 | ;( 1107 | function copy(src, target, obj) { 1108 | obj[target] = obj[target] || {}; 1109 | if (src && typeof src === 'object') { 1110 | for (var k in src) { 1111 | if (src.hasOwnProperty(k)) { 1112 | obj[target][k] = src[k]; 1113 | } 1114 | } 1115 | } else { 1116 | obj[target] = src; 1117 | } 1118 | } 1119 | ).call(null, module.exports, expose, host); 1120 | }).call(this, this, "OAuth1"); --------------------------------------------------------------------------------