Debian Codegraph @

docs/tutorial/4-authentication-and-permissions.md

raw
1 # Tutorial 4: Authentication & Permissions
2
3 Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:
4
5 * Code snippets are always associated with a creator.
6 * Only authenticated users may create snippets.
7 * Only the creator of a snippet may update or delete it.
8 * Unauthenticated requests should have full read-only access.
9
10 ## Adding information to our model
11
12 We're going to make a couple of changes to our `Snippet` model class.
13 First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.
14
15 Add the following two fields to the `Snippet` model in `models.py`.
16
17 ```python
18 owner = models.ForeignKey(
19 "auth.User", related_name="snippets", on_delete=models.CASCADE
20 )
21 highlighted = models.TextField()
22 ```
23
24 We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code highlighting library.
25
26 We'll need some extra imports:
27
28 ```python
29 from pygments.lexers import get_lexer_by_name
30 from pygments.formatters.html import HtmlFormatter
31 from pygments import highlight
32 ```
33
34 And now we can add a `.save()` method to our model class:
35
36 ```python
37 def save(self, *args, **kwargs):
38 """
39 Use the `pygments` library to create a highlighted HTML
40 representation of the code snippet.
41 """
42 lexer = get_lexer_by_name(self.language)
43 linenos = "table" if self.linenos else False
44 options = {"title": self.title} if self.title else {}
45 formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
46 self.highlighted = highlight(self.code, lexer, formatter)
47 super().save(*args, **kwargs)
48 ```
49
50 When that's all done we'll need to update our database tables.
51 Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
52
53 ```bash
54 rm -f db.sqlite3
55 rm -r snippets/migrations
56 python manage.py makemigrations snippets
57 python manage.py migrate
58 ```
59
60 You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command.
61
62 ```bash
63 python manage.py createsuperuser
64 ```
65
66 ## Adding endpoints for our User models
67
68 Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In `serializers.py` add:
69
70 ```python
71 from django.contrib.auth.models import User
72
73
74 class UserSerializer(serializers.ModelSerializer):
75 snippets = serializers.PrimaryKeyRelatedField(
76 many=True, queryset=Snippet.objects.all()
77 )
78
79 class Meta:
80 model = User
81 fields = ["id", "username", "snippets"]
82 ```
83
84 Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it.
85
86 We'll also add a couple of views to `views.py`. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class-based views.
87
88 ```python
89 from django.contrib.auth.models import User
90
91
92 class UserList(generics.ListAPIView):
93 queryset = User.objects.all()
94 serializer_class = UserSerializer
95
96
97 class UserDetail(generics.RetrieveAPIView):
98 queryset = User.objects.all()
99 serializer_class = UserSerializer
100 ```
101
102 Make sure to also import the `UserSerializer` class
103
104 ```python
105 from snippets.serializers import UserSerializer
106 ```
107
108 Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`.
109
110 ```python
111 path("users/", views.UserList.as_view()),
112 path("users/<int:pk>/", views.UserDetail.as_view()),
113 ```
114
115 ## Associating Snippets with Users
116
117 Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
118
119 The way we deal with that is by overriding a `.perform_create()` method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.
120
121 On the `SnippetList` view class, add the following method:
122
123 ```python
124 def perform_create(self, serializer):
125 serializer.save(owner=self.request.user)
126 ```
127
128 The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request.
129
130 ## Updating our serializer
131
132 Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`:
133
134 ```python
135 owner = serializers.ReadOnlyField(source="owner.username")
136 ```
137
138 !!! note
139 Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
140
141 This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
142
143 The field we've added is the untyped `ReadOnlyField` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `ReadOnlyField` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used `CharField(read_only=True)` here.
144
145 ## Adding required permissions to views
146
147 Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.
148
149 REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is `IsAuthenticatedOrReadOnly`, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.
150
151 First add the following import in the views module
152
153 ```python
154 from rest_framework import permissions
155 ```
156
157 Then, add the following property to **both** the `SnippetList` and `SnippetDetail` view classes.
158
159 ```python
160 permission_classes = [permissions.IsAuthenticatedOrReadOnly]
161 ```
162
163 ## Adding login to the Browsable API
164
165 If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
166
167 We can add a login view for use with the browsable API, by editing the URLconf in our project-level `urls.py` file.
168
169 Add the following import at the top of the file:
170
171 ```python
172 from django.urls import path, include
173 ```
174
175 And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
176
177 ```python
178 urlpatterns += [
179 path("api-auth/", include("rest_framework.urls")),
180 ]
181 ```
182
183 The `'api-auth/'` part of pattern can actually be whatever URL you want to use.
184
185 Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.
186
187 Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets' field.
188
189 ## Object level permissions
190
191 Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.
192
193 To do that we're going to need to create a custom permission.
194
195 In the snippets app, create a new file, `permissions.py`
196
197 ```python
198 from rest_framework import permissions
199
200
201 class IsOwnerOrReadOnly(permissions.BasePermission):
202 """
203 Custom permission to only allow owners of an object to edit it.
204 """
205
206 def has_object_permission(self, request, view, obj):
207 # Read permissions are allowed to any request,
208 # so we'll always allow GET, HEAD or OPTIONS requests.
209 if request.method in permissions.SAFE_METHODS:
210 return True
211
212 # Write permissions are only allowed to the owner of the snippet.
213 return obj.owner == request.user
214 ```
215
216 Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class:
217
218 ```python
219 permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
220 ```
221
222 Make sure to also import the `IsOwnerOrReadOnly` class.
223
224 ```python
225 from snippets.permissions import IsOwnerOrReadOnly
226 ```
227
228 Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
229
230 ## Authenticating with the API
231
232 Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any [authentication classes][authentication], so the defaults are currently applied, which are `SessionAuthentication` and `BasicAuthentication`.
233
234 When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
235
236 If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
237
238 If we try to create a snippet without authenticating, we'll get an error:
239
240 ```bash
241 http POST http://127.0.0.1:8000/snippets/ code="print(123)"
242
243 {
244 "detail": "Authentication credentials were not provided."
245 }
246 ```
247
248 We can make a successful request by including the username and password of one of the users we created earlier.
249
250 ```bash
251 http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
252
253 {
254 "id": 1,
255 "owner": "admin",
256 "title": "foo",
257 "code": "print(789)",
258 "linenos": false,
259 "language": "python",
260 "style": "friendly"
261 }
262 ```
263
264 ## Summary
265
266 We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
267
268 In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
269
270 [authentication]: ../api-guide/authentication.md
271 [tut-5]: 5-relationships-and-hyperlinked-apis.md