2011年7月31日日曜日

AppEngineアプリで2-Legged-Oauthを使ってAppsのドメイン管理者かどうかをチェックする

shin1ogawaさんからご指摘頂いた方法です。
すげえ簡単じゃん・・AuthSubとかアホすぎる・・
この投稿は、AppEngineアプリでAuthSubを使ってAppsのドメイン管理者かどうかをチェックする の続きです。

まず、マーケットプレースに登録するアプリの、Application Manifestで、
Provisioning APIを使うよ、って宣言しときます。
<?xml version="1.0" encoding="UTF-8" ?>
<ApplicationManifest xmlns="http://schemas.google.com/ApplicationManifest/2009">
  <Name>Hello World</Name>
  <Description>Demonstrates a simple Google Apps Marketplace application</Description>

  <!-- Administrators and users will be sent to this URL for application support -->
  <Support>
    <Link rel="support" href="https://***.appspot.com/" />
  </Support>

  <!-- Show this link in Google's universal navigation for all users -->
  <Extension id="navLink" type="link">
    <Name>Hello World</Name>
    <Url>https://***.appspot.com?from=google&amp;domain=${DOMAIN_NAME}</Url>
    <Scope ref="ProvisioningAPI"/>
  </Extension>

  <!-- Declare our OpenID realm so our app is white listed -->
  <Extension id="realm" type="openIdRealm">
    <Url>https://***.appspot.com</Url>
  </Extension>
  <!-- Need access to the Provisioning API -->
  <Scope id="ProvisioningAPI">
    <Url> https://apps-apis.google.com/a/feeds/user/#readonly</Url>
    <Reason>This app grants some control to domain admin.</Reason>
  </Scope>
</ApplicationManifest>

上の様にScopeを定義しておくと、「Add it Now」でのインストール時に、こんな感じで聞いてきます。












「データアクセスを許可する」をクリックすることで、Provisioning APIの使用が可能になります。
なお、この許可は、ドメイン管理画面から後で取り消すこともできますし、
ここでキャンセルしたとしても、ドメイン管理画面から後で許可することもできます。

んで、アプリの方はこんな感じ。一部抜粋です。

from gdata.apps.service import AppsService 

CONSUMER_KEY = "..."
CONSUMER_SECRET = "..."
SIG_METHOD = gdata.auth.OAuthSignatureMethod.HMAC_SHA1

class MainHandler(webapp.RequestHandler):
  def get(self):
    template_values = {}
    user = users.get_current_user()
    if user and check_email(user):
        srv = AppsService(domain=urlparse(user.federated_identity()).hostname , source="Hello World")
        srv.SetOAuthInputParameters(SIG_METHOD, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET,
                                   two_legged_oauth=True, requestor_id=user.email())
        srv.ssl = True
        gdata.alt.appengine.run_on_appengine(srv)
        user_name = user.email().split('@', 1)[0]
        user_entry = srv.RetrieveUser(user_name)
        if user_entry.login.admin == "true":
            self.response.out.write("%s is admin." % user_name)
        else:
            self.response.out.write("%s is not admin." % user_name)
    else:
        greeting = 'You need to log in!'
        template_values['greeting'] = greeting
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, template_values))
CONSUMER_KEY とCONSUMER_SECRETは、マーケットプレースの「My Vendor Profile」を開いて、
リスティングの「View OAuth Consumer Key 」で見ることができます。

ホント、shin1ogawaさんに感謝です!ありがとうございます!

0 件のコメント:

コメントを投稿