1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
|
%global _empty_manifest_terminate_build 0
Name: python-django-request-token
Version: 2.2
Release: 1
Summary: JWT-backed Django app for managing querystring tokens.
License: MIT
URL: https://github.com/yunojuno/django-request-token
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/65/84/2c6cc3ebc6e91e910c436e41f2b4bb6575da9bbc586131c7e0c831cb60d6/django_request_token-2.2.tar.gz
BuildArch: noarch
Requires: python3-django
Requires: python3-pyjwt
%description
## Supported versions
This project supports Django 3.2+ and Python 3.8+. The latest version
supported is Django 4.1 running on Python 3.11.
## Django Request Token
Django app that uses JWT to manage one-time and expiring tokens to
protect URLs.
This app currently requires the use of PostgreSQL.
### Background
This project was borne out of our experiences at YunoJuno with 'expiring
links' - which is a common use case of providing users with a URL that
performs a single action, and may bypass standard authentication. A
well-known use of this is the ubiquitous 'unsubscribe' link you find
at the bottom of newsletters. You click on the link and it immediately
unsubscribes you, irrespective of whether you are already authenticated
or not.
If you google "temporary url", "one-time link" or something similar you
will find lots of StackOverflow articles on supporting this in Django -
it's pretty obvious, you have a dedicated token url, and you store the
tokens in a model - when they are used you expire the token, and it
can't be used again. This works well, but it falls down in a number of
areas:
* Hard to support multiple endpoints (views)
If you want to support the same functionality (expiring links) for more
than one view in your project, you either need to have multiple models
and token handlers, or you need to store the specific view function and
args in the model; neither of these is ideal.
* Hard to debug
If you use have a single token url view that proxies view functions, you
need to store the function name, args and it then becomes hard to
support - when someone claims that they clicked on
`example.com/t/<token>`, you can't tell what that would resolve to
without looking it up in the database - which doesn't work for customer
support.
* Hard to support multiple scenarios
Some links expire, others have usage quotas - some have both. Links may
be for use by a single user, or multiple users.
This project is intended to provide an easy-to-support mechanism for
'tokenising' URLs without having to proxy view functions - you can build
well-formed Django URLs and views, and then add request token support
afterwards.
### Use Cases
This project supports three core use cases, each of which is modelled
using the `login_mode` attribute of a request token:
1. Public link with payload
2. ~~Single authenticated request~~ (DEPRECATED: use `django-visitor-pass`)
3. ~~Auto-login~~ (DEPRECATED: use `django-magic-link`)
**Public Link** (`RequestToken.LOGIN_MODE_NONE`)
In this mode (the default for a new token), there is no authentication,
and no assigned user. The token is used as a mechanism for attaching a
payload to the link. An example of this might be a custom registration
or affiliate link, that renders the standard template with additional
information extracted from the token - e.g. the name of the affiliate,
or the person who invited you to register.
```python
# a token that can be used to access a public url, without authenticating
# as a user, but carrying a payload (affiliate_id).
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_NONE,
data={
'affiliate_id': 1
}
)
...
@use_request_token(scope="foo")
function view_func(request):
# extract the affiliate id from an token _if_ one is supplied
affiliate_id = (
request.token.data['affiliate_id']
if hasattr(request, 'token')
else None
)
```
**Single Request** (`RequestToken.LOGIN_MODE_REQUEST`)
In Request mode, the request.user property is overridden by the user
specified in the token, but only for a single request. This is useful
for responding to a single action (e.g. RSVP, unsubscribe). If the user
then navigates onto another page on the site, they will not be
authenticated. If the user is already authenticated, but as a different
user to the one in the token, then they will receive a 403 response.
```python
# this token will identify the request.user as a given user, but only for
# a single request - not the entire session.
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_REQUEST,
user=User.objects.get(username="hugo")
)
...
@use_request_token(scope="foo")
function view_func(request):
assert request.user == User.objects.get(username="hugo")
```
**Auto-login** (`RequestToken.LOGIN_MODE_SESSION`)
This is the nuclear option, and must be treated with extreme care. Using
a Session token will automatically log the user in for an entire
session, giving the user who clicks on the link full access the token
user's account. This is useful for automatic logins. A good example of
this is the email login process on medium.com, which takes an email
address (no password) and sends out a login link.
Session tokens have a default expiry of ten minutes.
```python
# this token will log in as the given user for the entire session -
# NB use with caution.
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_SESSION,
user=User.objects.get(username="hugo")
)
```
### Implementation
The project contains middleware and a view function decorator that
together validate request tokens added to site URLs.
**request_token.models.RequestToken** - stores the token details
Step 1 is to create a `RequestToken` - this has various attributes that
can be used to modify its behaviour, and mandatory property - `scope`.
This is a text value - it can be anything you like - it is used by the
function decorator (described below) to confirm that the token given
matches the function being called - i.e. the `token.scope` must match
the function decorator scope kwarg:
```python
token = RequestToken(scope="foo")
# this will raise a 403 without even calling the function
@use_request_token(scope="bar")
def incorrect_scope(request):
pass
# this will call the function as expected
@use_request_token(scope="foo")
def correct_scope(request):
pass
```
The token itself - the value that must be appended to links as a
querystring argument - is a JWT - and comes from the
`RequestToken.jwt()` method. For example, if you were sending out an
email, you might render the email as an HTML template like this:
```html
{% if token %}
<a href="{{url}}?rt={{token.jwt}}>click here</a>
{% else %}
<a href="{{url}}">click here</a>
{% endif %}
```
If you haven't come across JWT before you can find out more on the
[jwt.io](https://jwt.io/) website. The token produced will include the
following JWT claims (available as the property `RequestToken.claims`:
* `max`: maximum times the token can be used
* `sub`: the scope
* `mod`: the login mode
* `jti`: the token id
* `aud`: (optional) the user the token represents
* `exp`: (optional) the expiration time of the token
* `iat`: (optional) the time the token was issued
* `ndf`: (optional) the not-before-time of the token
**request_token.models.RequestTokenLog** - stores usage data for tokens
Each time a token is used successfully, a log object is written to the
database. This provided an audit log of the usage, and it stores client
IP address and user agent, so can be used to debug issues. This can be
disabled using the `REQUEST_TOKEN_DISABLE_LOGS` setting. The logs table
can be maintained using the management command as described below.
**request_token.middleware.RequestTokenMiddleware** - decodes and verifies tokens
The `RequestTokenMiddleware` will look for a querystring token value
(the argument name defaults to 'rt' and can overridden using the
`JWT_QUERYSTRING_ARG` setting), and if it finds one it will verify the
token (using the JWT decode verification). If the token is verified, it
will fetch the token object from the database and perform additional
validation against the token attributes. If the token checks out it is
added to the incoming request as a `token` attribute. This way you can
add arbitrary data (stored on the token) to incoming requests.
If the token has a user specified, then the `request.user` is updated to
reflect this. The middleware must run after the Django auth middleware,
and before any custom middleware that inspects / monkey-patches the
`request.user`.
If the token cannot be verified it returns a 403.
**request_token.decorators.use_request_token** - applies token
permissions to views
A function decorator that takes one mandatory kwargs (`scope`) and one
optional kwargs (`required`). The `scope` is used to match tokens to
view functions - it's just a straight text match - the value can be
anything you like, but if the token scope is 'foo', then the
corresponding view function decorator scope must match. The `required`
kwarg is used to indicate whether the view **must** have a token in
order to be used, or not. This defaults to False - if a token **is**
provided, then it will be validated, if not, the view function is called
as is.
If the scopes do not match then a 403 is returned.
If required is True and no token is provided the a 403 is returned.
### Installation
Download / install the app using pip:
```shell
pip install django-request-token
```
Add the app `request_token` to your `INSTALLED_APPS` Django setting:
```python
# settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'request_token',
...
)
```
Add the middleware to your settings, **after** the standard
authentication middleware, and before any custom middleware that uses
the `request.user`.
```python
MIDDLEWARE_CLASSES = [
# default django middleware
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'request_token.middleware.RequestTokenMiddleware',
]
```
You can now add `RequestToken` objects, either via the shell (or within
your app) or through the admin interface. Once you have added a
`RequestToken` you can add the token JWT to your URLs (using the `jwt()`
method):
```python
>>> token = RequestToken.objects.create_token(scope="foo")
>>> url = "https://example.com/foo?rt=" + token.jwt()
```
You now have a request token enabled URL. You can use this token to
protect a view function using the view decorator:
```python
@use_request_token(scope="foo")
function foo(request):
pass
```
NB The 'scope' argument to the decorator is used to bind the function to
the incoming token - if someone tries to use a valid token on another
URL, this will return a 403.
**NB this currently supports only view functions - not class-based views.**
### Management commands
There is a single management command, `truncate_request_token_log` which can
be used to manage the size of the log table (each token usage is logged to
the database). It supports two arguments - `--max-count` and `--max-days` which
are self-explanatory:
```
$ python manage.py truncate_request_token_log --max-count=100
Truncating request token log records:
-> Retaining last 100 request token log records
-> Truncating request token log records from 2021-08-01 00:00:00
-> Truncating 0 request token log records.
$
```
### Settings
* `REQUEST_TOKEN_QUERYSTRING`
The querystring argument name used to extract the token from incoming
requests, defaults to **rt**.
* `REQUEST_TOKEN_EXPIRY`
Session tokens have a default expiry interval, specified in minutes. The
primary use case (above) dictates that the expiry should be no longer
than it takes to receive and open an email, defaults to **10**
(minutes).
* `REQUEST_TOKEN_403_TEMPLATE`
Specifying the 403-template so that for prettyfying the 403-response,
in production with a setting like:
```python
FOUR03_TEMPLATE = os.path.join(BASE_DIR,'...','403.html')
```
* `REQUEST_TOKEN_DISABLE_LOGS`
Set to `True` to disable the creation of `RequestTokenLog` objects on
each use of a token. This is not recommended in production, as the
auditing of token use is a valuable part of the library.
### Tests
There is a set of `tox` tests.
### License
MIT
### Contributing
This is by no means complete, however, it's good enough to be of value, hence releasing it.
If you would like to contribute to the project, usual Github rules apply:
1. Fork the repo to your own account
2. Submit a pull request
3. Add tests for any new code
4. Follow coding style of existing project
### Acknowledgements
@jpadilla for [PyJWT](https://github.com/jpadilla/pyjwt/)
%package -n python3-django-request-token
Summary: JWT-backed Django app for managing querystring tokens.
Provides: python-django-request-token
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-django-request-token
## Supported versions
This project supports Django 3.2+ and Python 3.8+. The latest version
supported is Django 4.1 running on Python 3.11.
## Django Request Token
Django app that uses JWT to manage one-time and expiring tokens to
protect URLs.
This app currently requires the use of PostgreSQL.
### Background
This project was borne out of our experiences at YunoJuno with 'expiring
links' - which is a common use case of providing users with a URL that
performs a single action, and may bypass standard authentication. A
well-known use of this is the ubiquitous 'unsubscribe' link you find
at the bottom of newsletters. You click on the link and it immediately
unsubscribes you, irrespective of whether you are already authenticated
or not.
If you google "temporary url", "one-time link" or something similar you
will find lots of StackOverflow articles on supporting this in Django -
it's pretty obvious, you have a dedicated token url, and you store the
tokens in a model - when they are used you expire the token, and it
can't be used again. This works well, but it falls down in a number of
areas:
* Hard to support multiple endpoints (views)
If you want to support the same functionality (expiring links) for more
than one view in your project, you either need to have multiple models
and token handlers, or you need to store the specific view function and
args in the model; neither of these is ideal.
* Hard to debug
If you use have a single token url view that proxies view functions, you
need to store the function name, args and it then becomes hard to
support - when someone claims that they clicked on
`example.com/t/<token>`, you can't tell what that would resolve to
without looking it up in the database - which doesn't work for customer
support.
* Hard to support multiple scenarios
Some links expire, others have usage quotas - some have both. Links may
be for use by a single user, or multiple users.
This project is intended to provide an easy-to-support mechanism for
'tokenising' URLs without having to proxy view functions - you can build
well-formed Django URLs and views, and then add request token support
afterwards.
### Use Cases
This project supports three core use cases, each of which is modelled
using the `login_mode` attribute of a request token:
1. Public link with payload
2. ~~Single authenticated request~~ (DEPRECATED: use `django-visitor-pass`)
3. ~~Auto-login~~ (DEPRECATED: use `django-magic-link`)
**Public Link** (`RequestToken.LOGIN_MODE_NONE`)
In this mode (the default for a new token), there is no authentication,
and no assigned user. The token is used as a mechanism for attaching a
payload to the link. An example of this might be a custom registration
or affiliate link, that renders the standard template with additional
information extracted from the token - e.g. the name of the affiliate,
or the person who invited you to register.
```python
# a token that can be used to access a public url, without authenticating
# as a user, but carrying a payload (affiliate_id).
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_NONE,
data={
'affiliate_id': 1
}
)
...
@use_request_token(scope="foo")
function view_func(request):
# extract the affiliate id from an token _if_ one is supplied
affiliate_id = (
request.token.data['affiliate_id']
if hasattr(request, 'token')
else None
)
```
**Single Request** (`RequestToken.LOGIN_MODE_REQUEST`)
In Request mode, the request.user property is overridden by the user
specified in the token, but only for a single request. This is useful
for responding to a single action (e.g. RSVP, unsubscribe). If the user
then navigates onto another page on the site, they will not be
authenticated. If the user is already authenticated, but as a different
user to the one in the token, then they will receive a 403 response.
```python
# this token will identify the request.user as a given user, but only for
# a single request - not the entire session.
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_REQUEST,
user=User.objects.get(username="hugo")
)
...
@use_request_token(scope="foo")
function view_func(request):
assert request.user == User.objects.get(username="hugo")
```
**Auto-login** (`RequestToken.LOGIN_MODE_SESSION`)
This is the nuclear option, and must be treated with extreme care. Using
a Session token will automatically log the user in for an entire
session, giving the user who clicks on the link full access the token
user's account. This is useful for automatic logins. A good example of
this is the email login process on medium.com, which takes an email
address (no password) and sends out a login link.
Session tokens have a default expiry of ten minutes.
```python
# this token will log in as the given user for the entire session -
# NB use with caution.
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_SESSION,
user=User.objects.get(username="hugo")
)
```
### Implementation
The project contains middleware and a view function decorator that
together validate request tokens added to site URLs.
**request_token.models.RequestToken** - stores the token details
Step 1 is to create a `RequestToken` - this has various attributes that
can be used to modify its behaviour, and mandatory property - `scope`.
This is a text value - it can be anything you like - it is used by the
function decorator (described below) to confirm that the token given
matches the function being called - i.e. the `token.scope` must match
the function decorator scope kwarg:
```python
token = RequestToken(scope="foo")
# this will raise a 403 without even calling the function
@use_request_token(scope="bar")
def incorrect_scope(request):
pass
# this will call the function as expected
@use_request_token(scope="foo")
def correct_scope(request):
pass
```
The token itself - the value that must be appended to links as a
querystring argument - is a JWT - and comes from the
`RequestToken.jwt()` method. For example, if you were sending out an
email, you might render the email as an HTML template like this:
```html
{% if token %}
<a href="{{url}}?rt={{token.jwt}}>click here</a>
{% else %}
<a href="{{url}}">click here</a>
{% endif %}
```
If you haven't come across JWT before you can find out more on the
[jwt.io](https://jwt.io/) website. The token produced will include the
following JWT claims (available as the property `RequestToken.claims`:
* `max`: maximum times the token can be used
* `sub`: the scope
* `mod`: the login mode
* `jti`: the token id
* `aud`: (optional) the user the token represents
* `exp`: (optional) the expiration time of the token
* `iat`: (optional) the time the token was issued
* `ndf`: (optional) the not-before-time of the token
**request_token.models.RequestTokenLog** - stores usage data for tokens
Each time a token is used successfully, a log object is written to the
database. This provided an audit log of the usage, and it stores client
IP address and user agent, so can be used to debug issues. This can be
disabled using the `REQUEST_TOKEN_DISABLE_LOGS` setting. The logs table
can be maintained using the management command as described below.
**request_token.middleware.RequestTokenMiddleware** - decodes and verifies tokens
The `RequestTokenMiddleware` will look for a querystring token value
(the argument name defaults to 'rt' and can overridden using the
`JWT_QUERYSTRING_ARG` setting), and if it finds one it will verify the
token (using the JWT decode verification). If the token is verified, it
will fetch the token object from the database and perform additional
validation against the token attributes. If the token checks out it is
added to the incoming request as a `token` attribute. This way you can
add arbitrary data (stored on the token) to incoming requests.
If the token has a user specified, then the `request.user` is updated to
reflect this. The middleware must run after the Django auth middleware,
and before any custom middleware that inspects / monkey-patches the
`request.user`.
If the token cannot be verified it returns a 403.
**request_token.decorators.use_request_token** - applies token
permissions to views
A function decorator that takes one mandatory kwargs (`scope`) and one
optional kwargs (`required`). The `scope` is used to match tokens to
view functions - it's just a straight text match - the value can be
anything you like, but if the token scope is 'foo', then the
corresponding view function decorator scope must match. The `required`
kwarg is used to indicate whether the view **must** have a token in
order to be used, or not. This defaults to False - if a token **is**
provided, then it will be validated, if not, the view function is called
as is.
If the scopes do not match then a 403 is returned.
If required is True and no token is provided the a 403 is returned.
### Installation
Download / install the app using pip:
```shell
pip install django-request-token
```
Add the app `request_token` to your `INSTALLED_APPS` Django setting:
```python
# settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'request_token',
...
)
```
Add the middleware to your settings, **after** the standard
authentication middleware, and before any custom middleware that uses
the `request.user`.
```python
MIDDLEWARE_CLASSES = [
# default django middleware
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'request_token.middleware.RequestTokenMiddleware',
]
```
You can now add `RequestToken` objects, either via the shell (or within
your app) or through the admin interface. Once you have added a
`RequestToken` you can add the token JWT to your URLs (using the `jwt()`
method):
```python
>>> token = RequestToken.objects.create_token(scope="foo")
>>> url = "https://example.com/foo?rt=" + token.jwt()
```
You now have a request token enabled URL. You can use this token to
protect a view function using the view decorator:
```python
@use_request_token(scope="foo")
function foo(request):
pass
```
NB The 'scope' argument to the decorator is used to bind the function to
the incoming token - if someone tries to use a valid token on another
URL, this will return a 403.
**NB this currently supports only view functions - not class-based views.**
### Management commands
There is a single management command, `truncate_request_token_log` which can
be used to manage the size of the log table (each token usage is logged to
the database). It supports two arguments - `--max-count` and `--max-days` which
are self-explanatory:
```
$ python manage.py truncate_request_token_log --max-count=100
Truncating request token log records:
-> Retaining last 100 request token log records
-> Truncating request token log records from 2021-08-01 00:00:00
-> Truncating 0 request token log records.
$
```
### Settings
* `REQUEST_TOKEN_QUERYSTRING`
The querystring argument name used to extract the token from incoming
requests, defaults to **rt**.
* `REQUEST_TOKEN_EXPIRY`
Session tokens have a default expiry interval, specified in minutes. The
primary use case (above) dictates that the expiry should be no longer
than it takes to receive and open an email, defaults to **10**
(minutes).
* `REQUEST_TOKEN_403_TEMPLATE`
Specifying the 403-template so that for prettyfying the 403-response,
in production with a setting like:
```python
FOUR03_TEMPLATE = os.path.join(BASE_DIR,'...','403.html')
```
* `REQUEST_TOKEN_DISABLE_LOGS`
Set to `True` to disable the creation of `RequestTokenLog` objects on
each use of a token. This is not recommended in production, as the
auditing of token use is a valuable part of the library.
### Tests
There is a set of `tox` tests.
### License
MIT
### Contributing
This is by no means complete, however, it's good enough to be of value, hence releasing it.
If you would like to contribute to the project, usual Github rules apply:
1. Fork the repo to your own account
2. Submit a pull request
3. Add tests for any new code
4. Follow coding style of existing project
### Acknowledgements
@jpadilla for [PyJWT](https://github.com/jpadilla/pyjwt/)
%package help
Summary: Development documents and examples for django-request-token
Provides: python3-django-request-token-doc
%description help
## Supported versions
This project supports Django 3.2+ and Python 3.8+. The latest version
supported is Django 4.1 running on Python 3.11.
## Django Request Token
Django app that uses JWT to manage one-time and expiring tokens to
protect URLs.
This app currently requires the use of PostgreSQL.
### Background
This project was borne out of our experiences at YunoJuno with 'expiring
links' - which is a common use case of providing users with a URL that
performs a single action, and may bypass standard authentication. A
well-known use of this is the ubiquitous 'unsubscribe' link you find
at the bottom of newsletters. You click on the link and it immediately
unsubscribes you, irrespective of whether you are already authenticated
or not.
If you google "temporary url", "one-time link" or something similar you
will find lots of StackOverflow articles on supporting this in Django -
it's pretty obvious, you have a dedicated token url, and you store the
tokens in a model - when they are used you expire the token, and it
can't be used again. This works well, but it falls down in a number of
areas:
* Hard to support multiple endpoints (views)
If you want to support the same functionality (expiring links) for more
than one view in your project, you either need to have multiple models
and token handlers, or you need to store the specific view function and
args in the model; neither of these is ideal.
* Hard to debug
If you use have a single token url view that proxies view functions, you
need to store the function name, args and it then becomes hard to
support - when someone claims that they clicked on
`example.com/t/<token>`, you can't tell what that would resolve to
without looking it up in the database - which doesn't work for customer
support.
* Hard to support multiple scenarios
Some links expire, others have usage quotas - some have both. Links may
be for use by a single user, or multiple users.
This project is intended to provide an easy-to-support mechanism for
'tokenising' URLs without having to proxy view functions - you can build
well-formed Django URLs and views, and then add request token support
afterwards.
### Use Cases
This project supports three core use cases, each of which is modelled
using the `login_mode` attribute of a request token:
1. Public link with payload
2. ~~Single authenticated request~~ (DEPRECATED: use `django-visitor-pass`)
3. ~~Auto-login~~ (DEPRECATED: use `django-magic-link`)
**Public Link** (`RequestToken.LOGIN_MODE_NONE`)
In this mode (the default for a new token), there is no authentication,
and no assigned user. The token is used as a mechanism for attaching a
payload to the link. An example of this might be a custom registration
or affiliate link, that renders the standard template with additional
information extracted from the token - e.g. the name of the affiliate,
or the person who invited you to register.
```python
# a token that can be used to access a public url, without authenticating
# as a user, but carrying a payload (affiliate_id).
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_NONE,
data={
'affiliate_id': 1
}
)
...
@use_request_token(scope="foo")
function view_func(request):
# extract the affiliate id from an token _if_ one is supplied
affiliate_id = (
request.token.data['affiliate_id']
if hasattr(request, 'token')
else None
)
```
**Single Request** (`RequestToken.LOGIN_MODE_REQUEST`)
In Request mode, the request.user property is overridden by the user
specified in the token, but only for a single request. This is useful
for responding to a single action (e.g. RSVP, unsubscribe). If the user
then navigates onto another page on the site, they will not be
authenticated. If the user is already authenticated, but as a different
user to the one in the token, then they will receive a 403 response.
```python
# this token will identify the request.user as a given user, but only for
# a single request - not the entire session.
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_REQUEST,
user=User.objects.get(username="hugo")
)
...
@use_request_token(scope="foo")
function view_func(request):
assert request.user == User.objects.get(username="hugo")
```
**Auto-login** (`RequestToken.LOGIN_MODE_SESSION`)
This is the nuclear option, and must be treated with extreme care. Using
a Session token will automatically log the user in for an entire
session, giving the user who clicks on the link full access the token
user's account. This is useful for automatic logins. A good example of
this is the email login process on medium.com, which takes an email
address (no password) and sends out a login link.
Session tokens have a default expiry of ten minutes.
```python
# this token will log in as the given user for the entire session -
# NB use with caution.
token = RequestToken.objects.create_token(
scope="foo",
login_mode=RequestToken.LOGIN_MODE_SESSION,
user=User.objects.get(username="hugo")
)
```
### Implementation
The project contains middleware and a view function decorator that
together validate request tokens added to site URLs.
**request_token.models.RequestToken** - stores the token details
Step 1 is to create a `RequestToken` - this has various attributes that
can be used to modify its behaviour, and mandatory property - `scope`.
This is a text value - it can be anything you like - it is used by the
function decorator (described below) to confirm that the token given
matches the function being called - i.e. the `token.scope` must match
the function decorator scope kwarg:
```python
token = RequestToken(scope="foo")
# this will raise a 403 without even calling the function
@use_request_token(scope="bar")
def incorrect_scope(request):
pass
# this will call the function as expected
@use_request_token(scope="foo")
def correct_scope(request):
pass
```
The token itself - the value that must be appended to links as a
querystring argument - is a JWT - and comes from the
`RequestToken.jwt()` method. For example, if you were sending out an
email, you might render the email as an HTML template like this:
```html
{% if token %}
<a href="{{url}}?rt={{token.jwt}}>click here</a>
{% else %}
<a href="{{url}}">click here</a>
{% endif %}
```
If you haven't come across JWT before you can find out more on the
[jwt.io](https://jwt.io/) website. The token produced will include the
following JWT claims (available as the property `RequestToken.claims`:
* `max`: maximum times the token can be used
* `sub`: the scope
* `mod`: the login mode
* `jti`: the token id
* `aud`: (optional) the user the token represents
* `exp`: (optional) the expiration time of the token
* `iat`: (optional) the time the token was issued
* `ndf`: (optional) the not-before-time of the token
**request_token.models.RequestTokenLog** - stores usage data for tokens
Each time a token is used successfully, a log object is written to the
database. This provided an audit log of the usage, and it stores client
IP address and user agent, so can be used to debug issues. This can be
disabled using the `REQUEST_TOKEN_DISABLE_LOGS` setting. The logs table
can be maintained using the management command as described below.
**request_token.middleware.RequestTokenMiddleware** - decodes and verifies tokens
The `RequestTokenMiddleware` will look for a querystring token value
(the argument name defaults to 'rt' and can overridden using the
`JWT_QUERYSTRING_ARG` setting), and if it finds one it will verify the
token (using the JWT decode verification). If the token is verified, it
will fetch the token object from the database and perform additional
validation against the token attributes. If the token checks out it is
added to the incoming request as a `token` attribute. This way you can
add arbitrary data (stored on the token) to incoming requests.
If the token has a user specified, then the `request.user` is updated to
reflect this. The middleware must run after the Django auth middleware,
and before any custom middleware that inspects / monkey-patches the
`request.user`.
If the token cannot be verified it returns a 403.
**request_token.decorators.use_request_token** - applies token
permissions to views
A function decorator that takes one mandatory kwargs (`scope`) and one
optional kwargs (`required`). The `scope` is used to match tokens to
view functions - it's just a straight text match - the value can be
anything you like, but if the token scope is 'foo', then the
corresponding view function decorator scope must match. The `required`
kwarg is used to indicate whether the view **must** have a token in
order to be used, or not. This defaults to False - if a token **is**
provided, then it will be validated, if not, the view function is called
as is.
If the scopes do not match then a 403 is returned.
If required is True and no token is provided the a 403 is returned.
### Installation
Download / install the app using pip:
```shell
pip install django-request-token
```
Add the app `request_token` to your `INSTALLED_APPS` Django setting:
```python
# settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'request_token',
...
)
```
Add the middleware to your settings, **after** the standard
authentication middleware, and before any custom middleware that uses
the `request.user`.
```python
MIDDLEWARE_CLASSES = [
# default django middleware
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'request_token.middleware.RequestTokenMiddleware',
]
```
You can now add `RequestToken` objects, either via the shell (or within
your app) or through the admin interface. Once you have added a
`RequestToken` you can add the token JWT to your URLs (using the `jwt()`
method):
```python
>>> token = RequestToken.objects.create_token(scope="foo")
>>> url = "https://example.com/foo?rt=" + token.jwt()
```
You now have a request token enabled URL. You can use this token to
protect a view function using the view decorator:
```python
@use_request_token(scope="foo")
function foo(request):
pass
```
NB The 'scope' argument to the decorator is used to bind the function to
the incoming token - if someone tries to use a valid token on another
URL, this will return a 403.
**NB this currently supports only view functions - not class-based views.**
### Management commands
There is a single management command, `truncate_request_token_log` which can
be used to manage the size of the log table (each token usage is logged to
the database). It supports two arguments - `--max-count` and `--max-days` which
are self-explanatory:
```
$ python manage.py truncate_request_token_log --max-count=100
Truncating request token log records:
-> Retaining last 100 request token log records
-> Truncating request token log records from 2021-08-01 00:00:00
-> Truncating 0 request token log records.
$
```
### Settings
* `REQUEST_TOKEN_QUERYSTRING`
The querystring argument name used to extract the token from incoming
requests, defaults to **rt**.
* `REQUEST_TOKEN_EXPIRY`
Session tokens have a default expiry interval, specified in minutes. The
primary use case (above) dictates that the expiry should be no longer
than it takes to receive and open an email, defaults to **10**
(minutes).
* `REQUEST_TOKEN_403_TEMPLATE`
Specifying the 403-template so that for prettyfying the 403-response,
in production with a setting like:
```python
FOUR03_TEMPLATE = os.path.join(BASE_DIR,'...','403.html')
```
* `REQUEST_TOKEN_DISABLE_LOGS`
Set to `True` to disable the creation of `RequestTokenLog` objects on
each use of a token. This is not recommended in production, as the
auditing of token use is a valuable part of the library.
### Tests
There is a set of `tox` tests.
### License
MIT
### Contributing
This is by no means complete, however, it's good enough to be of value, hence releasing it.
If you would like to contribute to the project, usual Github rules apply:
1. Fork the repo to your own account
2. Submit a pull request
3. Add tests for any new code
4. Follow coding style of existing project
### Acknowledgements
@jpadilla for [PyJWT](https://github.com/jpadilla/pyjwt/)
%prep
%autosetup -n django-request-token-2.2
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-django-request-token -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Tue May 30 2023 Python_Bot <Python_Bot@openeuler.org> - 2.2-1
- Package Spec generated
|