google-signin.html 15.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="google-signin-aware.html">
<link rel="import" href="../iron-icon/iron-icon.html">
<link rel="import" href="../iron-icons/iron-icons.html">
<link rel="import" href="../font-roboto/roboto.html">
<link rel="import" href="../google-apis/google-js-api.html">
<link rel="import" href="../paper-ripple/paper-ripple.html">
<link rel="import" href="../paper-material/paper-material.html">
<link rel="import" href="../iron-flex-layout/classes/iron-flex-layout.html">
<link rel="import" href="google-icons.html">

<dom-module id="google-signin">
  <link rel="import" type="css" href="google-signin.css">
  <template>
    <google-signin-aware id="aware"
      app-package-name="{{appPackageName}}"
      client-id="{{clientId}}"
      cookie-policy="{{cookiePolicy}}"
      request-visible-actions="{{requestVisibleActions}}"
      hosted-domain="{{hostedDomain}}"
      offline="{{offline}}"
      offline-always-prompt="{{offlineAlwaysPrompt}}"
      scopes="{{scopes}}"
      signed-in="{{signedIn}}"
      is-authorized="{{isAuthorized}}"
      need-additional-auth="{{needAdditionalAuth}}"
      has-plus-scopes="{{hasPlusScopes}}"></google-signin-aware>
    <template is="dom-if" if="{{raised}}">
      <paper-material id="shadow" class="fit" elevation="2" animated></paper-material>
    </template>
    <div id="button"
      class$="[[_computeButtonClass(height, width, theme, signedIn, _brand, needAdditionalAuth)]]">

      <paper-ripple id="ripple" class="fit"></paper-ripple>
      <!-- this div is needed to position the ripple behind text content -->
      <div relative layout horizontal center-center>
        <template is="dom-if" if="{{_computeButtonIsSignIn(signedIn, needAdditionalAuth)}}">
          <div class="button-content signIn" tabindex="0"
              on-click="signIn" on-keydown="_signInKeyPress">
            <span class="icon"><iron-icon icon="[[_brandIcon]]"></iron-icon></span>
            <span class="buttonText">{{_labelSignin}}</span>
          </div>
        </template>
        <template is="dom-if" if="{{_computeButtonIsSignOut(signedIn, needAdditionalAuth) }}">
          <div class="button-content signOut" tabindex="0"
              on-click="signOut" on-keydown="_signOutKeyPress">
            <span class="icon"><iron-icon icon="[[_brandIcon]]"></iron-icon></span>
            <span class="buttonText">{{labelSignout}}</span>
          </div>
        </template>
        <template is="dom-if" if="{{_computeButtonIsSignOutAddl(signedIn, needAdditionalAuth) }}">
          <div class="button-content signIn" tabindex="0"
              on-click="signIn" on-keydown="_signInKeyPress">
            <span class="icon"><iron-icon icon="[[_brandIcon]]"></iron-icon></span>
            <span class="buttonText">{{labelAdditional}}</span>
          </div>
        </template>
      </div>

    </div>
  </template>
</dom-module>
<script>
  (function() {

    /**
     * Enum brand values.
     * @readonly
     * @enum {string}
     */
    var BrandValue = {
        GOOGLE: 'google',
        PLUS: 'google-plus'
    };

    /**
     * Enum height values.
     * @readonly
     * @enum {string}
     */
    var HeightValue = {
      SHORT: 'short',
      STANDARD: 'standard',
      TALL: 'tall'
    };

    /**
     * Enum button label default values.
     * @readonly
     * @enum {string}
     */
    var LabelValue = {
      STANDARD: 'Sign in',
      WIDE: 'Sign in with Google',
      WIDE_PLUS: 'Sign in with Google+'
    };

    /**
     * Enum theme values.
     * @readonly
     * @enum {string}
     */
    var ThemeValue = {
      LIGHT: 'light',
      DARK: 'dark'
    };

    /**
     * Enum width values.
     * @readonly
     * @enum {string}
     */
    var WidthValue = {
      ICON_ONLY: 'iconOnly',
      STANDARD: 'standard',
      WIDE: 'wide'
    };

/**
&lt;google-signin&gt; is used to authenticate with Google, allowing you to interact
with other Google APIs such as Drive and Google+.

<img style="max-width:100%;" src="https://cloud.githubusercontent.com/assets/107076/6791176/5c868822-d16a-11e4-918c-ec9b84a2db45.png"/>

If you do not need to show the button, use companion `<google-signin-aware>` element to declare scopes, check authentication state.

#### Examples

    <google-signin client-id="..." scopes="https://www.googleapis.com/auth/drive"></google-signin>

    <google-signin label-signin="Sign-in" client-id="..." scopes="https://www.googleapis.com/auth/drive"></google-signin>

    <google-signin theme="dark" width="iconOnly" client-id="..." scopes="https://www.googleapis.com/auth/drive"></google-signin>


#### Notes

The attribute `clientId` is provided in your Google Developers Console
(https://console.developers.google.com).

The `scopes` attribute allows you to specify which scope permissions are required
(e.g do you want to allow interaction with the Google Drive API). Many APIs also
need to be enabled in the Google Developers Console before you can use them.

The `requestVisibleActions` attribute is necessary if you want to write app
activities (https://developers.google.com/+/web/app-activities/) on behalf of
the user. Please note that this attribute is only valid in combination with the
plus.login scope (https://www.googleapis.com/auth/plus.login).

The `offline` attribute allows you to get an auth code which your server can
redeem for an offline access token
(https://developers.google.com/identity/sign-in/web/server-side-flow).
You can also set `offline-always-prompt` instead of `offline` to ensure that your app
will re-prompt the user for offline access and generate a working `refresh_token`
even if they have already granted offline access to your app in the past.

Use label properties to customize prompts.

The button can be styled in using the `height`, `width`, and `theme` attributes.
These attributes help you follow the Google+ Sign-In button branding guidelines
(https://developers.google.com/+/branding-guidelines).

The `google-signin-success` event is triggered when a user successfully authenticates
and `google-signed-out` is triggered when user signs out.
You can also use `isAuthorized` attribute to observe user's authentication state.

Additional events, such as `google-signout-attempted` are
triggered when the user attempts to sign-out and successfully signs out.

When requesting offline access, the `google-signin-offline-success` event is
triggered when the user successfully consents with offline support.

The `google-signin-necessary` event is fired when scopes requested via
google-signin-aware elements require additional user permissions.

#### Testing

By default, the demo accompanying this element is setup to work on localhost with
port 8080. That said, you *should* update the `clientId` to your own one for
any apps you're building. See the Google Developers Console
(https://console.developers.google.com) for more info.

@demo
*/

    Polymer({

      is: 'google-signin',

    /**
     * Fired when user is signed in.
     * You can use auth2 api to retrieve current user: `gapi.auth2.getAuthInstance().currentUser.get();`
     * @event google-signin-success
     */

    /**
     * Fired when the user is signed-out.
     * @event google-signed-out
     */

    /**
     * Fired if user requires additional authorization
     * @event google-signin-necessary
     */

    /**
     * Fired when signed in, and scope has been authorized
     * @param {Object} result Authorization result.
     * @event google-signin-aware-success
     */

    /**
     * Fired when an offline authorization is successful.
     * @event google-signin-offline-success
     * @param {Object} detail
     * @param {string} detail.code The one-time authorization code from Google.
     *     Your application can exchange this for an `access_token` and `refresh_token`
     */

    /**
     * Fired when this scope is not authorized
     * @event google-signin-aware-signed-out
     */
      properties: {
        /**
         * App package name for android over-the-air installs.
         * See the relevant [docs](https://developers.google.com/+/web/signin/android-app-installs)
         */
        appPackageName: {
          type: String,
          value: ''
        },

        /**
         * The brand being used for logo and styling.
         *
         * @default 'google'
         */
        brand: {
          type: String,
          value: ''
        },

        /** @private */
        _brand: {
          type: String,
          computed: '_computeBrand(brand, hasPlusScopes)'
        },

        /**
         * a Google Developers clientId reference
         */
        clientId: {
          type: String,
          value: ''
        },

        /**
         * The cookie policy defines what URIs have access to the session cookie
         * remembering the user's sign-in state.
         * See the relevant [docs](https://developers.google.com/+/web/signin/reference#determining_a_value_for_cookie_policy) for more information.
         *
         * @default 'single_host_origin'
         */
        cookiePolicy: {
          type: String,
          value: ''
        },

        /**
         * The height to use for the button.
         *
         * Available options: short, standard, tall.
         *
         * @type {HeightValue}
         */
        height: {
          type: String,
          value: 'standard'
        },

        /**
         * By default the ripple expands to fill the button. Set this to true to
         * constrain the ripple to a circle within the button.
         */
        fill: {
          type: Boolean,
          value: true
        },

        /**
         * An optional label for the button for additional permissions.
         */
        labelAdditional: {
          type: String,
          value: 'Additional permissions required'
        },

        /**
         * An optional label for the sign-in button.
         */
        labelSignin: {
          type: String,
          value: ''
        },

        _labelSignin: {
          type: String,
          computed: '_computeSigninLabel(labelSignin, width, _brand)'
        },

        /**
         * An optional label for the sign-out button.
         */
        labelSignout: {
          type: String,
          value: 'Sign out'
        },

        /**
         * If true, the button will be styled with a shadow.
         */
        raised: {
          type: Boolean,
          value: false
        },

        /**
         * The app activity types you want to write on behalf of the user
         * (e.g http://schemas.google.com/AddActivity)
         */
        requestVisibleActions: {
          type: String,
          value: ''
        },

        /**
         * The Google Apps domain to which users must belong to sign in.
         * See the relevant [docs](https://developers.google.com/identity/sign-in/web/reference) for more information.
         */
        hostedDomain: {
          type: String,
          value: ''
        },

        /**
         * Allows for offline `access_token` retrieval during the signin process.
         */
        offline: {
          type: Boolean,
          value: false
        },

        /**
         * Forces a re-prompt, even if the user has already granted offline
         * access to your application in the past. You only need one of
         * `offline` and `offlineAlwaysPrompt`.
         */
        offlineAlwaysPrompt: {
          type: Boolean,
          value: false
        },

        /**
         * The scopes to provide access to (e.g https://www.googleapis.com/auth/drive)
         * and should be space-delimited.
         */
        scopes: {
          type: String,
          value: ''
        },

        /**
         * The theme to use for the button.
         *
         * Available options: light, dark.
         *
         * @attribute theme
         * @type {ThemeValue}
         * @default 'dark'
         */
        theme: {
          type: String,
          value: 'dark'
        },

        /**
         * The width to use for the button.
         *
         * Available options: iconOnly, standard, wide.
         *
         * @type {WidthValue}
         */
        width: {
          type: String,
          value: 'standard'
        },

        _brandIcon: {
          type: String,
          computed: '_computeIcon(_brand)'
        },

        /**
         * True if *any* element has google+ scopes
         */
        hasPlusScopes: {
          type: Boolean,
          notify: true,
          value: false
        },

        /**
         * True if additional authorization required globally
         */
        needAdditionalAuth: {
          type: Boolean,
          value: false
        },

        /**
         * Is user signed in?
         */
        signedIn: {
          type: Boolean,
          notify: true,
          value: false,
          observer: '_observeSignedIn'
        },

        /**
         * True if authorizations for *this* element have been granted
         */
        isAuthorized: {
          type: Boolean,
          notify: true,
          value: false
        }

      },

      _computeButtonClass: function(height, width, theme, signedIn, brand, needAdditionalAuth) {
        return "height-" + height + " width-" + width + " theme-" + theme + " signedIn-" + signedIn + " brand-" + brand + "  additionalAuth-" + needAdditionalAuth;
      },

      _computeIcon: function(brand) {
        return "google:" + brand;
      },

      /* Button state computed */
      _computeButtonIsSignIn: function(signedIn, additionalAuth) {
        return !signedIn;
      },

      _computeButtonIsSignOut: function(signedIn, additionalAuth) {
        return signedIn && !additionalAuth;
      },

      _computeButtonIsSignOutAddl: function(signedIn, additionalAuth) {
        return signedIn && additionalAuth;
      },

      _computeBrand: function(attrBrand, hasPlusScopes) {
        var newBrand;
        if (attrBrand) {
          newBrand = attrBrand;
        } else if (hasPlusScopes) {
          newBrand = BrandValue.PLUS;
        } else {
          newBrand = BrandValue.GOOGLE;
        };
        return newBrand;
      },

      _observeSignedIn: function(newVal, oldVal) {
        if (newVal) {
          if (this.needAdditionalAuth)
            this.fire('google-signin-necessary');
          this.fire('google-signin-success');
        }
        else
          this.fire('google-signed-out');
      },

      /**
       * Determines the proper label based on the attributes.
       */
      _computeSigninLabel: function(labelSignin, width, _brand) {
        if (labelSignin) {
          return labelSignin;
        } else {
          switch(width) {

            case WidthValue.WIDE:
              return (_brand == BrandValue.PLUS) ?
                LabelValue.WIDE_PLUS : LabelValue.WIDE;

            case WidthValue.STANDARD:
              return LabelValue.STANDARD;

            case WidthValue.ICON_ONLY:
              return '';

            default:
              console.warn("bad width value: ", width);
              return LabelValue.STANDARD;
          }
        }
      },

      /** Sign in user. Opens the authorization dialog for signing in.
       * The dialog will be blocked by a popup blocker unless called inside click handler.
       */
      signIn: function () {
        this.$.aware.signIn();
      },

      _signInKeyPress: function (e) {
        if (e.which == 13 || e.keyCode == 13 || e.which == 32 || e.keyCode == 32) {
          e.preventDefault();
          this.signIn();
        }
      },

      /** Sign out the user */
      signOut: function () {
        this.fire('google-signout-attempted');
        this.$.aware.signOut();
      },

      _signOutKeyPress: function (e) {
        if (e.which == 13 || e.keyCode == 13 || e.which == 32 || e.keyCode == 32) {
          e.preventDefault();
          this.signOut();
        }
      }
    });
  }());
</script>