認証を追加しよう

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(中垣健志)

認証を追加しよう

web2pyのロールベースのアクセス制御APIは非常に洗練されています。ただし、ここではshowアクションへのアクセスを認証されたユーザのみに限定する説明だけにし、残りの詳しい説明は第8章に委ねます。

The web2py API for Role-Based Access Control is quite sophisticated, but for now we will limit ourselves to restricting access to the show action to authenticated users, deferring a more detailed discussion to Chapter 8.

認証されたユーザにのみアクセスを限定するには、3つのステップを完了する必要があります。モデル(たとえば"db.py")では、以下を追加する必要があります:

To limit access to authenticated users, we need to complete three steps. In a model, for example "db.py", we need to add:

1.

2.

3.

from gluon.tools import Auth

auth = Auth(globals(), db)

auth.define_tables()

コントローラでは、次の1つのアクションを追加する必要があります:

In our controller, we need to add one action:

1.

2.

def user():

return dict(form=auth())

こうするだけで、ログイン、登録、ログアウトなどが可能になります。デフォルトのレイアウトはまた、対応するページへのオプションを右上隅に表示します。

This is sufficient to enable login, register, logout, etc. pages. The default layout will also show options to the corresponding pages in the top right corner.

このとき、制限したい関数を次のように修飾することができます:

We can now decorate the functions that we want to restrict, for example:

1.

2.

3.

4.

5.

6.

7.

8.

@auth.requires_login()

def show():

image = db.image(request.args(0)) or redirect(URL('index'))

db.comment.image_id.default = image.id

form = crud.create(db.comment, next=URL(args=image.id),

message='your comment is posted')

comments = db(db.comment.image_id==image.id).select()

return dict(image=image, comments=comments, form=form)

次のアドレスへのいかなるアクセスも

Any attempt to access

http://127.0.0.1:8000/images/default/show/[image_id]

ログインが要求されます。ユーザーがログインしていない場合は、次のアドレスにリダイレクトされます。

will require login. If the user is not logged it, the user will be redirected to

http://127.0.0.1:8000/images/default/user/login

user関数はまた、他と一緒に、次のようなアクションを公開します:

The user function also exposes, among others, the following actions:

http://127.0.0.1:8000/images/default/user/logout

http://127.0.0.1:8000/images/default/user/register

http://127.0.0.1:8000/images/default/user/profile

http://127.0.0.1:8000/images/default/user/change_password

http://127.0.0.1:8000/images/default/user/request_reset_password

http://127.0.0.1:8000/images/default/user/retrieve_username

http://127.0.0.1:8000/images/default/user/retrieve_password

http://127.0.0.1:8000/images/default/user/verify_email

http://127.0.0.1:8000/images/default/user/impersonate

http://127.0.0.1:8000/images/default/user/not_authorized

このとき、ログインして、コメントを読み、投稿するために、ユーザーは最初に登録する必要があります。

Now, a first-time user needs to register in order to be able to log in and read or post comments.

authオブジェクトとuser関数の両方は雛形アプリケーションですでに定義されています。authオブジェクトは、非常にカスタマイズ可能で、emailによる照合、登録の承認、CAPTHCA、プラグインを介したログインメソッドの変更を行うことができます。

Both the auth object and the user function are already defined in the scaffolding application. The auth object is highly customizable and can deal with email verification, registration approvals, CAPTCHA, and alternate login methods via plugins.