3

現在、Python / App Engine / SimpleAuth を使用して、アプリケーションに OAuth ログインを提供しています。現在のワークフローでは、ユーザーは OAuth でログインし、後でアプリ内で自分用の一意のユーザー名を作成できます。

webapp2 User エンティティが既に作成された後、一意のユーザー名を作成する際に問題が発生しています。webapp2 モデルには、アプリケーション エンティティ グループ内で一意のユーザー名を有効にする方法があることがわかりましたが、自分で設定する方法がわかりません。( SimpleAuthを使用して、他の OAuth プロバイダーのすべてを設定しています。)

ユーザーが送信した「ユーザー名」が存在するかどうかを確認し、現在ログインしているユーザーにプロパティとして追加しないかどうかを確認したいと思います。これに関するヘルプ/ポインタをいただければ幸いです。

4

1 に答える 1

4

webapp2_extras.appengine.auth.models.Userユーザー名プロパティを拡張して追加できると思います。

from webapp2_extras.appengine.auth.models import User as Webapp2User

class User(Webapp2User):
    username = ndb.StringProperty(required=True)

次に、webapp2 アプリを作成するには、これを含む構成が必要です。

APP_CFG = {
  'webapp2_extras.auth': {
    'user_model': User,  # default is webapp2_extras.appengine.auth.models.User
    'user_attributes': ['username']  # list of User model properties
  }
}

app = webapp2.WSGIApplication(config=APP_CFG)

上記を踏まえて、次のコードを使用して新しいユーザーを作成すると、ユーザー名が一意であることを確認できます (Unique モデルによって保証されます)。

auth_id = 'some-auth-id'  # e.g. 'google:123456789', see simpleauth example.
ok, props = User.create_user(auth_id, unique_properties=['username'],
                                      username='some-username',
                                      ...)
if not ok:
  # props list will contain 'username', indicating that
  # another entity with the same username already exists
  ...

username問題は、この構成では、作成時に設定する必要があることです。

ユーザー名をオプションにしたい場合、またはユーザーが後で設定/変更できるようにしたい場合は、上記のコードを次のように変更することをお勧めします。

class User(Webapp2User):
    username = ndb.StringProperty()  # note, there's no required=True

# when creating a new user:
auth_id = 'some-auth-id'  # e.g. 'google:123456789', see simpleauth example.
ok, props = User.create_user(auth_id, unique_properties=[], ...)

基本的に、unique_properties空のリストになります (またはスキップできます)。また、ユーザーがユーザー名をより意味のあるものに変更することを決定するまで、usernameプロパティを一時的に割り当てることもできます。user.key.id()たとえば、Google+ プロフィールのリンクを考えてみましょう。私の現在のリンクはhttps://plus.google.com/114517983826182834234ですが、変更できるようになったら、https://plus.google.com/+IamNotANumberAnymoreのようなものを試してみます。

次に、「ユーザー名の変更/設定」フォーム ハンドラーで、ユーザー名が既に存在するかどうかを確認し、ユーザー エンティティを更新します (存在しない場合)。

def handle_change_username(self):
  user = ...  # get the user who wants to change their username
  username = self.request.get('username')
  uniq = 'User.username:%s' % username
  ok = User.unique_model.create(uniq)
  if ok:
    user.username = username
    user.put()
  else:
    # notify them that this username
    # is already taken
    ...

User.unique_model.create(uniq)Uniqueエンティティが存在しない場合は、指定された値でエンティティを作成します。この場合okは になりますTrue。それ以外の場合は、その値 (この場合は一意のユーザー名) を持つエンティティが既に存在するokことを示します。False

User.unique_model.create()また、とを同じトランザクションに入れることもできuser.put()ます (これらは異なるエンティティ グループにあるため、XG になります)。

お役に立てれば!

于 2013-08-18T14:34:12.080 に答える