plain.oauth 0.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plain/oauth/README.md ADDED
@@ -0,0 +1,329 @@
1
+ # plain-oauth
2
+
3
+ Let users log in with OAuth providers.
4
+
5
+ [Watch on YouTube (3 mins) →](https://www.youtube.com/watch?v=UxbxBa6AFsU)
6
+
7
+ This library is intentionally minimal.
8
+ It has no dependencies and a single database model.
9
+ If you simply want users to log in with GitHub, Google, Twitter, etc. (and maybe use that access token for API calls),
10
+ then this is the library for you.
11
+
12
+ There are three OAuth flows that it makes possible:
13
+
14
+ 1. Signup via OAuth (new user, new OAuth connection)
15
+ 2. Login via OAuth (existing user, existing OAuth connection)
16
+ 3. Connect/disconnect OAuth accounts to a user (existing user, new OAuth connection)
17
+
18
+
19
+ ## Usage
20
+
21
+ Install the package from PyPi:
22
+
23
+ ```sh
24
+ pip install plain-oauth
25
+ ```
26
+
27
+ Add `plain.oauth` to your `INSTALLED_PACKAGES` in `settings.py`:
28
+
29
+ ```python
30
+ INSTALLED_PACKAGES = [
31
+ ...
32
+ "plain.oauth",
33
+ ]
34
+ ```
35
+
36
+ In your `urls.py`, include `plain.oauth.urls`:
37
+
38
+ ```python
39
+ urlpatterns = [
40
+ path("oauth/", include("plain.oauth.urls")),
41
+ ...
42
+ ]
43
+ ```
44
+
45
+ Then run migrations:
46
+
47
+ ```sh
48
+ python manage.py migrate plain.oauth
49
+ ```
50
+
51
+ Create a new OAuth provider ([or copy one from our examples](https://github.com/forgepackages/plain-oauth/tree/master/provider_examples)):
52
+
53
+ ```python
54
+ # yourapp/oauth.py
55
+ import requests
56
+
57
+ from plain.oauth.providers import OAuthProvider, OAuthToken, OAuthUser
58
+
59
+
60
+ class ExampleOAuthProvider(OAuthProvider):
61
+ authorization_url = "https://example.com/login/oauth/authorize"
62
+
63
+ def get_oauth_token(self, *, code, request):
64
+ response = requests.post(
65
+ "https://example.com/login/oauth/token",
66
+ headers={
67
+ "Accept": "application/json",
68
+ },
69
+ data={
70
+ "client_id": self.get_client_id(),
71
+ "client_secret": self.get_client_secret(),
72
+ "code": code,
73
+ },
74
+ )
75
+ response.raise_for_status()
76
+ data = response.json()
77
+ return OAuthToken(
78
+ access_token=data["access_token"],
79
+ )
80
+
81
+ def get_oauth_user(self, *, oauth_token):
82
+ response = requests.get(
83
+ "https://example.com/api/user",
84
+ headers={
85
+ "Accept": "application/json",
86
+ "Authorization": f"token {oauth_token.access_token}",
87
+ },
88
+ )
89
+ response.raise_for_status()
90
+ data = response.json()
91
+ return OAuthUser(
92
+ id=data["id"],
93
+ username=data["username"],
94
+ email=data["email"],
95
+ )
96
+ ```
97
+
98
+ Create your OAuth app/consumer on the provider's site (GitHub, Google, etc.).
99
+ When setting it up, you'll likely need to give it a callback URL.
100
+ In development this can be `http://localhost:8000/oauth/github/callback/` (if you name it `"github"` like in the example below).
101
+ At the end you should get some sort of "client id" and "client secret" which you can then use in your `settings.py`:
102
+
103
+ ```python
104
+ OAUTH_LOGIN_PROVIDERS = {
105
+ "github": {
106
+ "class": "yourapp.oauth.GitHubOAuthProvider",
107
+ "kwargs": {
108
+ "client_id": environ["GITHUB_CLIENT_ID"],
109
+ "client_secret": environ["GITHUB_CLIENT_SECRET"],
110
+ # "scope" is optional, defaults to ""
111
+
112
+ # You can add other fields if you have additional kwargs in your class __init__
113
+ # def __init__(self, *args, custom_arg="default", **kwargs):
114
+ # self.custom_arg = custom_arg
115
+ # super().__init__(*args, **kwargs)
116
+ },
117
+ },
118
+ }
119
+ ```
120
+
121
+ Then add a login button (which is a form using POST rather than a basic link, for security purposes):
122
+
123
+ ```html
124
+ <h1>Login</h1>
125
+ <form action="{% url 'oauth:login' 'github' %}" method="post">
126
+ {{ csrf_input }}
127
+ <button type="submit">Login with GitHub</button>
128
+ </form>
129
+ ```
130
+
131
+ Depending on your URL and provider names,
132
+ your OAuth callback will be something like `https://example.com/oauth/{provider}/callback/`.
133
+
134
+ That's pretty much it!
135
+
136
+ ## Advanced usage
137
+
138
+ ### Email addresses should be unique
139
+
140
+ When you're integrating with an OAuth provider,
141
+ we think that the user's email address is the best "primary key" when linking to your `User` model in your app.
142
+ Unfortunately in Django, by default an email address is not required to be unique!
143
+ **We strongly recommend you require email addresses to be unique in your app.**
144
+
145
+ [As suggested by the Django docs](https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project),
146
+ one way to do this is to have your own `User` model:
147
+
148
+ ```python
149
+ # In an app named "users", for example
150
+ from plain.auth.models import BaseUser
151
+
152
+ class User(BaseUser):
153
+ email = models.EmailField(unique=True)
154
+
155
+
156
+ # In settings.py
157
+ AUTH_USER_MODEL = 'users.User'
158
+ ```
159
+
160
+ You'll also notice that there are no "email confirmation" or "email verification" flows in this library.
161
+ This is also intentional.
162
+ You can implement something like that yourself if you need to,
163
+ but the easier solution in our opinion is to use an OAuth provider you *trust to have done that already*.
164
+ If you look at our [provider examples](https://github.com/forgepackages/plain-oauth/tree/master/provider_examples) you'll notice how we often use provider APIs to get the email address which is "primary" and "verified" already.
165
+ If they've already done that work,
166
+ then we can just use that information.
167
+
168
+ ### Handling OAuth errors
169
+
170
+ The most common error you'll run into is if an existing user clicks a login button,
171
+ but they haven't yet connected that provider to their account.
172
+ For security reasons,
173
+ the required flow here is that the user actually logs in with another method (however they signed up) and then *connects* the OAuth provider from a settings page.
174
+
175
+ For this error (and a couple others),
176
+ there is an error template that is rendered.
177
+ You can customize this by copying `oauth/error.html` to one of your own template directories:
178
+
179
+ ```html
180
+ {% extends "base.html" %}
181
+
182
+ {% block content %}
183
+ <h1>OAuth Error</h1>
184
+ <p>{{ oauth_error }}</p>
185
+ {% endblock %}
186
+ ```
187
+
188
+ ![Django OAuth duplicate email address error](https://user-images.githubusercontent.com/649496/159065848-b4ee6e63-9aa0-47b5-94e8-7bee9b509e60.png)
189
+
190
+ ### Connecting and disconnecting OAuth accounts
191
+
192
+ To connect and disconnect OAuth accounts,
193
+ you can add a series of forms to a user/profile settings page.
194
+ Here's an very basic example:
195
+
196
+ ```html
197
+ {% extends "base.html" %}
198
+
199
+ {% block content %}
200
+ Hello {{ request.user }}!
201
+
202
+ <h2>Existing connections</h2>
203
+ <ul>
204
+ {% for connection in request.user.oauth_connections.all %}
205
+ <li>
206
+ {{ connection.provider_key }} [ID: {{ connection.provider_user_id }}]
207
+ {% if connection.can_be_disconnected %}
208
+ <form action="{% url 'oauth:disconnect' connection.provider_key %}" method="post">
209
+ {{ csrf_input }}
210
+ <input type="hidden" name="provider_user_id" value="{{ connection.provider_user_id }}">
211
+ <button type="submit">Disconnect</button>
212
+ </form>
213
+ {% endif %}
214
+ </li>
215
+ {% endfor %}
216
+ </ul>
217
+
218
+ <h2>Add a connection</h2>
219
+ <ul>
220
+ {% for provider_key in oauth_provider_keys %}
221
+ <li>
222
+ {{ provider_key}}
223
+ <form action="{% url 'oauth:connect' provider_key %}" method="post">
224
+ {{ csrf_input }}
225
+ <button type="submit">Connect</button>
226
+ </form>
227
+ </li>
228
+ {% endfor %}
229
+ </ul>
230
+
231
+ {% endblock %}
232
+ ```
233
+
234
+ The `get_provider_keys` function can help populate the list of options:
235
+
236
+ ```python
237
+ from plain.oauth.providers import get_provider_keys
238
+
239
+ class ExampleView(TemplateView):
240
+ template_name = "index.html"
241
+
242
+ def get_context(self, **kwargs):
243
+ context = super().get_context(**kwargs)
244
+ context["oauth_provider_keys"] = get_provider_keys()
245
+ return context
246
+ ```
247
+
248
+ ![Connecting and disconnecting Django OAuth accounts](https://user-images.githubusercontent.com/649496/159065096-30239a1f-62f6-4ee2-a944-45140f45af6f.png)
249
+
250
+ ### Using a saved access token
251
+
252
+ ```python
253
+ import requests
254
+
255
+ # Get the OAuth connection for a user
256
+ connection = user.oauth_connections.get(provider_key="github")
257
+
258
+ # If the token can expire, check and refresh it
259
+ if connection.access_token_expired():
260
+ connection.refresh_access_token()
261
+
262
+ # Use the token in an API call
263
+ token = connection.access_token
264
+ response = requests.get(...)
265
+ ```
266
+
267
+ ### Using the Django system check
268
+
269
+ This library comes with a Django system check to ensure you don't *remove* a provider from `settings.py` that is still in use in your database.
270
+ You do need to specify the `--database` for this to run when using the check command by itself:
271
+
272
+ ```sh
273
+ python manage.py check --database default
274
+ ```
275
+
276
+ ## FAQs
277
+
278
+ ### How is this different from [other Django OAuth libraries](https://djangopackages.org/grids/g/oauth/)?
279
+
280
+ The short answer is that *it does less*.
281
+
282
+ In [django-allauth](https://github.com/pennersr/django-allauth)
283
+ (maybe the most popular alternative)
284
+ you get all kinds of other features like managing multiple email addresses,
285
+ email verification,
286
+ a long list of supported providers,
287
+ and a whole suite of forms/urls/views/templates/signals/tags.
288
+ And in my experience,
289
+ it's too much.
290
+ It often adds more complexity to your app than you actually need (or want) and honestly it can just be a lot to wrap your head around.
291
+ Personally, I don't like the way that your OAuth settings are stored in the database vs when you use `settings.py`,
292
+ and the implications for doing it one way or another.
293
+
294
+ The other popular OAuth libraries have similar issues,
295
+ and I think their *weight* outweighs their usefulness for 80% of the use cases.
296
+
297
+ ### Why aren't providers included in the library itself?
298
+
299
+ One thing you'll notice is that we don't have a long list of pre-configured providers in this library.
300
+ Instead, we have some examples (which you can usually just copy, paste, and use) and otherwise encourage you to wire up the provider yourself.
301
+ Often times all this means is finding the two OAuth URLs ("oauth/authorize" and "oauth/token") in their docs,
302
+ and writing two class methods that do the actual work of getting the user's data (which is often customized anyway).
303
+
304
+ We've written examples for the following providers:
305
+
306
+ - [GitHub](https://github.com/forgepackages/plain-oauth/tree/master/provider_examples/github.py)
307
+ - [GitLab](https://github.com/forgepackages/plain-oauth/tree/master/provider_examples/gitlab.py)
308
+ - [Bitbucket](https://github.com/forgepackages/plain-oauth/tree/master/provider_examples/bitbucket.py)
309
+
310
+ Just copy that code and paste it in your project.
311
+ Tweak as necessary!
312
+
313
+ This might sound strange at first.
314
+ But in the long run we think it's actually *much* more maintainable for both us (as library authors) and you (as app author).
315
+ If something breaks with a provider, you can fix it immediately!
316
+ You don't need to try to run changes through us or wait for an upstream update.
317
+ You're welcome to contribute an example to this repo,
318
+ and there won't be an expectation that it "works perfectly for every use case until the end of time".
319
+
320
+ ### Redirect/callback URL mismatch in local development?
321
+
322
+ If you're doing local development through a proxy/tunnel like [ngrok](https://ngrok.com/),
323
+ then the callback URL might be automatically built as `http` instead of `https`.
324
+
325
+ This is the Django setting you're probably looking for:
326
+
327
+ ```python
328
+ SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
329
+ ```
File without changes
plain/oauth/admin.py ADDED
@@ -0,0 +1,47 @@
1
+ from plain.models import Count
2
+ from plain.staff.admin.cards import ChartCard
3
+ from plain.staff.admin.views import (
4
+ AdminModelDetailView,
5
+ AdminModelListView,
6
+ AdminModelViewset,
7
+ register_viewset,
8
+ )
9
+
10
+ from .models import OAuthConnection
11
+
12
+
13
+ class ProvidersChartCard(ChartCard):
14
+ title = "Providers"
15
+
16
+ def get_chart_data(self) -> dict:
17
+ results = (
18
+ OAuthConnection.objects.all()
19
+ .values("provider_key")
20
+ .annotate(count=Count("id"))
21
+ )
22
+ return {
23
+ "type": "doughnut",
24
+ "data": {
25
+ "labels": [result["provider_key"] for result in results],
26
+ "datasets": [
27
+ {
28
+ "label": "Providers",
29
+ "data": [result["count"] for result in results],
30
+ }
31
+ ],
32
+ },
33
+ }
34
+
35
+
36
+ @register_viewset
37
+ class OAuthConnectionViewset(AdminModelViewset):
38
+ class ListView(AdminModelListView):
39
+ nav_section = "OAuth"
40
+ model = OAuthConnection
41
+ title = "Connections"
42
+ fields = ["id", "user", "provider_key", "provider_user_id"]
43
+ cards = [ProvidersChartCard]
44
+
45
+ class DetailView(AdminModelDetailView):
46
+ model = OAuthConnection
47
+ title = "OAuth connection"
plain/oauth/config.py ADDED
@@ -0,0 +1,6 @@
1
+ from plain.packages import PackageConfig
2
+
3
+
4
+ class PlainOAuthConfig(PackageConfig):
5
+ name = "plain.oauth"
6
+ label = "plainoauth" # Primarily for migrations
@@ -0,0 +1,12 @@
1
+ class OAuthError(Exception):
2
+ """Base class for OAuth errors"""
3
+
4
+ pass
5
+
6
+
7
+ class OAuthStateMismatchError(OAuthError):
8
+ pass
9
+
10
+
11
+ class OAuthUserAlreadyExistsError(OAuthError):
12
+ pass
@@ -0,0 +1,56 @@
1
+ # Generated by Plain 4.0.3 on 2022-03-16 19:11
2
+
3
+ import plain.models.deletion
4
+ from plain import models
5
+ from plain.models import migrations
6
+ from plain.runtime import settings
7
+
8
+
9
+ class Migration(migrations.Migration):
10
+ initial = True
11
+
12
+ dependencies = [
13
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
14
+ ]
15
+
16
+ operations = [
17
+ migrations.CreateModel(
18
+ name="OAuthConnection",
19
+ fields=[
20
+ (
21
+ "id",
22
+ models.BigAutoField(
23
+ auto_created=True,
24
+ primary_key=True,
25
+ serialize=False,
26
+ ),
27
+ ),
28
+ ("created_at", models.DateTimeField(auto_now_add=True)),
29
+ ("updated_at", models.DateTimeField(auto_now=True)),
30
+ ("provider_key", models.CharField(db_index=True, max_length=100)),
31
+ ("provider_user_id", models.CharField(db_index=True, max_length=100)),
32
+ ("access_token", models.CharField(blank=True, max_length=100)),
33
+ ("refresh_token", models.CharField(blank=True, max_length=100)),
34
+ (
35
+ "access_token_expires_at",
36
+ models.DateTimeField(blank=True, null=True),
37
+ ),
38
+ (
39
+ "refresh_token_expires_at",
40
+ models.DateTimeField(blank=True, null=True),
41
+ ),
42
+ (
43
+ "user",
44
+ models.ForeignKey(
45
+ on_delete=plain.models.deletion.CASCADE,
46
+ related_name="oauth_connections",
47
+ to=settings.AUTH_USER_MODEL,
48
+ ),
49
+ ),
50
+ ],
51
+ options={
52
+ "ordering": ("provider_key",),
53
+ "unique_together": {("provider_key", "provider_user_id")},
54
+ },
55
+ ),
56
+ ]
@@ -0,0 +1,24 @@
1
+ # Generated by Plain 4.0.3 on 2022-03-18 18:24
2
+
3
+ from plain import models
4
+ from plain.models import migrations
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+ dependencies = [
9
+ ("plainoauth", "0001_initial"),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.AlterModelOptions(
14
+ name="oauthconnection",
15
+ options={
16
+ "ordering": ("provider_key",),
17
+ },
18
+ ),
19
+ migrations.AlterField(
20
+ model_name="oauthconnection",
21
+ name="access_token",
22
+ field=models.CharField(max_length=100),
23
+ ),
24
+ ]
@@ -0,0 +1,23 @@
1
+ # Generated by Plain 4.0.6 on 2022-08-11 19:18
2
+
3
+ from plain import models
4
+ from plain.models import migrations
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+ dependencies = [
9
+ ("plainoauth", "0002_alter_oauthconnection_options_and_more"),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.AlterField(
14
+ model_name="oauthconnection",
15
+ name="access_token",
16
+ field=models.CharField(max_length=300),
17
+ ),
18
+ migrations.AlterField(
19
+ model_name="oauthconnection",
20
+ name="refresh_token",
21
+ field=models.CharField(blank=True, max_length=300),
22
+ ),
23
+ ]
@@ -0,0 +1,23 @@
1
+ # Generated by Plain 5.0.dev20230806030948 on 2023-08-08 19:32
2
+
3
+ from plain import models
4
+ from plain.models import migrations
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+ dependencies = [
9
+ ("plainoauth", "0003_alter_oauthconnection_access_token_and_more"),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.AlterField(
14
+ model_name="oauthconnection",
15
+ name="access_token",
16
+ field=models.CharField(max_length=2000),
17
+ ),
18
+ migrations.AlterField(
19
+ model_name="oauthconnection",
20
+ name="refresh_token",
21
+ field=models.CharField(blank=True, max_length=2000),
22
+ ),
23
+ ]
File without changes