Aurelia谷歌登录按钮

时间:2017-01-04 04:52:04

标签: javascript aurelia google-signin google-oauth2

我刚开始使用Aurelia并且我遇到了Google登录的问题。看起来我可以创建自己的Google按钮但是如果有可能的话我宁愿让它以这种方式工作。这是我的代码:

<script src="https://apis.google.com/js/platform.js" async defer></script>
...
<body aurelia-app="src/main">
...
<span id="googleButtonPlaceholder" class="g-signin2" data-onsuccess="onSignIn"></span>

我在Aurelia课程中设置了功能,但我不知道是否可以调用它。我尝试${onSignIn()}只在加载时调用该函数,${onSignIn}onSignIn()onSignIndata-onsuccess.bind="onSignin()"但似乎没有任何效果。有没有办法将Aurelia功能传递给Google data-onsuccess属性?

作为一个注释,我正在从Angular 1.5.8切换到以前有效的地方。

4 个答案:

答案 0 :(得分:3)

以下是一个示例:https://gist.run?id=5da90f48b43b9c5867c8d2ace0f6371f

<强> app.html

<?php
session_start();
if(isset($_POST['submit'])){
    if(isset($_POST['tsmdate'])){
        $entrydate = trim($_POST['tsmdate']);
        if($entrydate == date('Y-m-d')){
           echo "Same Date";
        }
        else{
          echo "Different Date";
        }
   }
else{
    echo "Date is missing";
}
}
?>

<html>
    <body>
        <form name="dates" id="dates" method="POST" action="">
            <table cellpadding="5" border="0" width="100%">
                <tr>
                    <td colspan="3" align="center">
                    <h1> select dates </h1>
                    </td>
                </tr>

                <tr>
                    <td width="30%" align="right">
                        <label for="tsmdate">Entry date </label>
                    </td>
                    <td align="left">
                        <input type="date" name="tsmdate" id="tsmdate" required="required">
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" name="submit" value="dates">
                    </td>
                </tr>
            </table>
       </form>
     </body>
</html>

<强> app.js

<template>
  <require from="google-signin-button"></require>

  <google-signin-button success.call="signinSuccess(googleUser)"
                        error.call="signinError(error)">
  </google-signin-button>

  <h1>${message}</h1>
</template>

<强>谷歌登入-button.js

export class App {
  message = 'Not signed in.';

  signinSuccess(googleUser) {
    const name = googleUser.getBasicProfile().getName();
    this.message = `Signed in: ${name}`;
  }

  signinError(error) {
    this.message = `Error: ${error}`;
  }
}

答案 1 :(得分:1)

@JeremyDanyow有一个很好的答案,但在我上床睡觉并阅读更多关于Aurelia之后,我想到了一个解决方案,在看到他的回答之前尝试,所以我想我会为那些感兴趣的人分享另一种方法。

<强>的index.html

<main aurelia-app="src/main">
</main>

<script src="https://apis.google.com/js/platform.js" async defer></script>

<强> app.html

<template>
    <span id="my-signin2"></span>
    <!-- other stuff -->
</template>

<强> app.js

attached() {
   this.render();
}

render() {
   gapi.signin2.render('my-signin2', {
      'scope': 'profile email',
      'theme': 'dark',
      'onsuccess': this.onSuccess,
      'onfailure': this.onFailure
   });
}

onSuccess(googleuser) {
  let gUser = googleuser.getBasicProfile(),
      id_token = googleuser.getAuthResponse().id_token;
}

onFailure(error) {
   console.log(error);
}

这种方法与谷歌在他们的网站上显示的略有不同,他们给你的platform.js一个onload函数来呈现按钮。相反,我在模板中创建了按钮,然后在加载模板后,调用attached(),然后调用我将使platform.js调用onload的函数。

答案 2 :(得分:0)

尝试data-onsuccess.call="onSignIn()"

答案 3 :(得分:0)

在遵循@JeremyDanyow的示例之后,我想到了这一点

可以简单使用,但需要帮助...

  1. 当使用Google登录名打开另一个窗口时,在Google添加的iframe中加载内容时出错(这似乎没有破坏它)

  2. 侦听器最多只能进行两次登录/注销操作

希望其他人可以对此有所改善。

google-signin-button.js

import { inject, noView, bindable } from 'aurelia-framework';

import { LogManager } from 'aurelia-framework';
const Console = LogManager.getLogger('google-signin-button');

// Integrating Google Sign-In into your web app
// https://developers.google.com/identity/sign-in/web/reference
// https://console.developers.google.com/apis/credentials

// inspiration: https://developers.google.com/identity/sign-in/web/build-button
function preparePlatform(): Promise<Function> {
  // Inject an async script element to load the google platform API.
  const script = document.createElement('script');
  script.src = `https://apis.google.com/js/platform.js?onload=gapi_ready`;
  script.async = true;
  script.defer = true;
  document.head.appendChild(script);
  // return a promise that will resolve with the onload callback
  return new Promise(resolve => window['gapi_ready'] = resolve);
}

@noView
@inject(Element)
export class GoogleSigninButton {

  @bindable authenticated = (signedIn: Boolean) => { };
  @bindable authorized = (GoogleUser: any) => { };

  @bindable scope = 'profile email';
  @bindable clientId = 'none';

  @bindable theme = 'dark';
  @bindable width = 240;
  @bindable height = 50;

  public element: Element;

  constructor(element) {
    this.element = element;
  }

  public wasAuthenticated: Boolean;
  sendAuthenticated(signedIn: Boolean) {
    if (signedIn !== this.wasAuthenticated) {
      this.authenticated(signedIn);
      this.wasAuthenticated = signedIn;
    }
  }

  public wasAuthorized: any;
  sendAuthorized(googleUser: any) {
    if (googleUser !== this.wasAuthorized) {
      this.authorized(googleUser);
      this.wasAuthorized = googleUser;
      this.sendAuthenticated(true);
    }
  }

  attached() {
    // inject the script tag
    preparePlatform()
      .then(() => {
        // load the auth lib
        // Console.debug('gapi created, loading auth2');
        window['gapi'].load('auth2', () => {
          // init the auth lib
          // Console.debug('gapi.auth2 loaded, intializing with clientId:', this.clientId);
          window['gapi'].auth2.init({
            client_id: this.clientId
          })
            .then(
              (googleAuth: any) => {
                // Console.debug('gapi.auth2 intialized');
                // listen for user signed in/out
                googleAuth.isSignedIn.listen((signedIn: Boolean) => {
                  // Console.debug('googleAuth.isSignedIn.listener', signedIn);
                  this.sendAuthenticated(signedIn);
                });
                // listen for who signed in
                googleAuth.currentUser.listen((googleUser: any) => {
                  // Console.debug('googleAuth.currentUser.listener', googleUser);
                  this.sendAuthorized(googleUser);
                });
                // draw the button
                window['gapi'].signin2.render(this.element, {
                  scope: this.scope,
                  width: this.width,
                  height: this.height,
                  longtitle: true,
                  theme: this.theme,
                  onsuccess: (googleUser: any) => {
                    // Console.debug('gapi.signin2.render success', googleUser);
                    this.sendAuthorized(googleUser);
                  },
                  // drawing button failure
                  onfailure: (error: any) => {
                    Console.error('gapi.signin2.render failure', error);
                  }
                });
              },
              // intialization error
              (errObj: any) => {
                Console.error('gapi.auth2.init -> errObj', errObj);
              }
            );
        });
      });
  }
}

some-usage.js

import environment from '../environment';

import { LogManager } from 'aurelia-framework';
const Console = LogManager.getLogger('Login');

import { inject } from 'aurelia-framework';
import { AuthService } from 'aurelia-authentication';
import { EventAggregator } from 'aurelia-event-aggregator';

import './login.scss';

@inject(AuthService, EventAggregator)
export class Login {

  public authService: AuthService;
  public eventAggregator: EventAggregator;

  public googleSigninClientID: string = 'none';

  constructor(authService: AuthService, eventAggregator: EventAggregator) {
    this.eventAggregator = eventAggregator;
    this.authService = authService;

    this.googleSigninClientID = environment.googleSigninClientID;
  };

  isAuthenticated(signedIn: Boolean) {
    Console.warn('isAuthenticated', signedIn);
  }

  isAuthorized(googleUser: any) {
    Console.warn('isAuthorized', googleUser);
  }

}

some-usage.html

<template>
  <require from="../resources/elements/google-signin-button"></require>
  <section>
    <div class="container-fluid">
      <center>
        <google-signin-button client-id.bind="googleSigninClientID" authenticated.bind="isAuthenticated" authorized.bind="isAuthorized"> </google-signin-button>
      </center>
    </div>
  </section>
</template>