Debian Codegraph @

docs/auth.rst

raw
1 .. _authentication:
2
3 Authentication
4 ==============
5
6 The :py:class:`Authentication` class provides a means of authenticating users
7 of the site. It is designed to work out-of-the-box with a simple ``User`` model,
8 but can be heavily customized.
9
10 The :py:class:`Auth` system is comprised of a single class which is responsible
11 for coordinating incoming requests to your project with known users. It provides
12 the following:
13
14 * views for login and logout
15 * model to store user data (or you can provide your own)
16 * mechanism for identifying users across requests (uses session storage)
17
18 All of these pieces can be customized, but the default out-of-box implementation
19 aims to provide a good starting place.
20
21 The auth system is also designed to work closely with the :ref:`admin-interface`.
22
23
24 Getting started
25 ---------------
26
27 In order to provide a method for users to authenticate with your site, instantiate
28 an :py:class:`Auth` backend for your project:
29
30 .. code-block:: python
31
32 from flask import Flask
33
34 from flask_peewee.auth import Auth
35 from flask_peewee.db import Database
36
37 app = Flask(__name__)
38 db = Database(app)
39
40 # needed for authentication
41 auth = Auth(app, db)
42
43 .. note::
44 ``user`` is reserverd keyword in Postgres. Pass db_table to Auth to override db table.
45
46 Marking areas of the site as login required
47 -------------------------------------------
48
49 If you want to mark specific areas of your site as requiring auth, you can
50 decorate views using the :py:meth:`Auth.login_required` decorator:
51
52 .. code-block:: python
53
54 @app.route('/private/')
55 @auth.login_required
56 def private_timeline():
57 user = auth.get_logged_in_user()
58
59 # ... display the private timeline for the logged-in user
60
61 If the request comes from someone who has not logged-in with the site, they are
62 redirected to the :py:meth:`Auth.login` view, which allows the user to authenticate.
63 After successfully logging-in, they will be redirected to the page they requested
64 initially.
65
66
67 Requiring specific permissions
68 ------------------------------
69
70 :py:meth:`Auth.login_required` only checks that *someone* is logged in. When a
71 view should be restricted further, two more decorators are available:
72
73 * :py:meth:`Auth.admin_required` -- additionally requires the user's ``admin``
74 flag to be set.
75 * :py:meth:`Auth.test_user` -- takes a predicate ``fn(user)`` and builds a
76 decorator that requires a logged-in user for whom it returns a truthy value.
77
78 In fact ``login_required`` and ``admin_required`` are nothing more than
79 ``test_user(lambda user: True)`` and ``test_user(lambda user: user.admin)``. Use
80 ``test_user`` to express any rule you like:
81
82 .. code-block:: python
83
84 @app.route('/staff/')
85 @auth.test_user(lambda user: user.is_staff)
86 def staff_area():
87 # only reachable by a logged-in user whose is_staff attribute is truthy
88 ...
89
90 A request that fails the check is redirected to the login view, exactly like
91 ``login_required``.
92
93
94 Retrieving the current user
95 ---------------------------
96
97 Whenever in a `request context <https://flask.palletsprojects.com/en/stable/reqcontext/>`_, the
98 currently logged-in user is available by calling :py:meth:`Auth.get_logged_in_user`,
99 which will return ``None`` if the requesting user is not logged in.
100
101 The auth system also registers a pre-request hook that stores the currently logged-in
102 user in the special flask variable ``g``.
103
104
105 Logging users in and out programmatically
106 -----------------------------------------
107
108 Sometimes you need to establish the session yourself -- for instance, logging a
109 user in immediately after they register. :py:meth:`Auth.login_user` and
110 :py:meth:`Auth.logout_user` do exactly that from within a request:
111
112 .. code-block:: python
113
114 user = User.create(username='huey', email='[email protected]', ...)
115 user.set_password('meow')
116 user.save()
117
118 auth.login_user(user) # huey is now logged in for subsequent requests
119
120 ``logout_user()`` ends the session. By default it removes only flask-peewee's
121 own session keys, leaving any other data you've stored in the session intact.
122 Pass ``clear_session=True`` when constructing :py:class:`Auth` to have logout
123 wipe the *entire* session instead -- a simple hardening step against session
124 fixation:
125
126 .. code-block:: python
127
128 auth = Auth(app, db, clear_session=True)
129
130
131 Accessing the user in the templates
132 -----------------------------------
133
134 The auth system registers a template context processor which makes the logged-in
135 user available in any template:
136
137 .. code-block:: html
138
139 {% if user %}
140 <p>Hello {{ user.username }}</p>
141 {% else %}
142 <p>Please <a href="{{ url_for('auth.login') }}?next={{ request.path }}">log in</a></p>
143 {% endif %}
144
145
146 Using a custom "User" model
147 ---------------------------
148
149 It is easy to use your own model for the ``User``, though depending on the amount
150 of changes it may be necessary to override methods in both the :py:class:`Auth` and
151 :py:class:`Admin` classes.
152
153 Unless you want to override the default behavior of the :py:class:`Auth` class' mechanism
154 for actually authenticating users (which you may want to do if relying on a 3rd-party
155 for auth) -- you will want to be sure your ``User`` model implements two methods:
156
157 * ``set_password(password)`` -- takes a raw password and stores an encrypted version on model
158 * ``check_password(password)`` -- returns whether or not the supplied password matches
159 the one stored on the model instance
160
161 .. note::
162 The :py:class:`BaseUser` mixin provides default implementations of these two methods.
163
164 Here's a simple example of extending the auth system to use a custom user model:
165
166 .. code-block:: python
167
168 from flask_peewee.auth import BaseUser # <-- implements set_password and check_password
169
170 app = Flask(__name__)
171 db = Database(app)
172
173 # create our custom user model. note that we're mixing in BaseUser in order to
174 # use the default auth methods it implements, "set_password" and "check_password"
175 class User(db.Model, BaseUser):
176 username = CharField()
177 password = CharField()
178 email = CharField()
179
180 # ... our custom fields ...
181 is_superuser = BooleanField()
182
183
184 # create a modeladmin for it
185 class UserAdmin(ModelAdmin):
186 columns = ('username', 'email', 'is_superuser',)
187
188 # Make sure the user's password is hashed, after it's been changed in
189 # the admin interface. If we don't do this, the password will be saved
190 # in clear text inside the database and login will be impossible.
191 def save_model(self, instance, form, adding=False):
192 orig_password = instance.password
193
194 user = super(UserAdmin, self).save_model(instance, form, adding)
195
196 if orig_password != form.password.data:
197 user.set_password(form.password.data)
198 user.save()
199
200 return user
201
202
203 # subclass Auth so we can return our custom classes
204 class CustomAuth(Auth):
205 def get_user_model(self):
206 return User
207
208 def get_model_admin(self, model_admin=None):
209 return UserAdmin
210
211 # instantiate the auth
212 auth = CustomAuth(app, db)
213
214
215 Here's how you might integrate the custom auth with the admin area of your site:
216
217 .. code-block:: python
218
219 # subclass Admin to check for whether the user is a superuser
220 class CustomAdmin(Admin):
221 def check_user_permission(self, user):
222 return user.is_superuser
223
224 # instantiate the admin
225 admin = CustomAdmin(app, auth)
226
227 admin.register(User, UserAdmin)
228 admin.setup()