forked from 00dani/lemoncurry
Switch from stateless JOSE tokens to stateful tokens in the DB, since they can then be much smaller and we're using a DB anyway
This commit is contained in:
parent
9c843ee145
commit
741c2eb234
7 changed files with 160 additions and 117 deletions
51
lemonauth/migrations/0003_indieauthcode_token.py
Normal file
51
lemonauth/migrations/0003_indieauthcode_token.py
Normal file
|
@ -0,0 +1,51 @@
|
|||
# Generated by Django 2.0.6 on 2018-06-12 04:51
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
import model_utils.fields
|
||||
import randomslugfield.fields
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('lemonauth', '0002_delete_indieauthcode'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='IndieAuthCode',
|
||||
fields=[
|
||||
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
|
||||
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
|
||||
('id', randomslugfield.fields.RandomSlugField(blank=True, editable=False, length=30, max_length=30, primary_key=True, serialize=False, unique=True)),
|
||||
('client_id', models.URLField()),
|
||||
('scope', models.TextField(blank=True)),
|
||||
('redirect_uri', models.URLField()),
|
||||
('response_type', model_utils.fields.StatusField(choices=[('id', 'id'), ('code', 'code')], default='id', max_length=100, no_check_for_status=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Token',
|
||||
fields=[
|
||||
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
|
||||
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
|
||||
('id', randomslugfield.fields.RandomSlugField(blank=True, editable=False, length=30, max_length=30, primary_key=True, serialize=False, unique=True)),
|
||||
('client_id', models.URLField()),
|
||||
('scope', models.TextField(blank=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
59
lemonauth/models.py
Normal file
59
lemonauth/models.py
Normal file
|
@ -0,0 +1,59 @@
|
|||
from datetime import timedelta
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import models
|
||||
from django.utils.timezone import now
|
||||
from randomslugfield import RandomSlugField
|
||||
from model_utils import Choices
|
||||
from model_utils.fields import StatusField
|
||||
from model_utils.models import TimeStampedModel
|
||||
|
||||
|
||||
class AuthSecret(TimeStampedModel):
|
||||
"""
|
||||
An AuthSecret is a model with an unguessable primary key, suitable for
|
||||
sharing with external sites for secure authentication.
|
||||
|
||||
AuthSecret is primarily used to factor out the many similarities between
|
||||
authorisation codes and tokens in IndieAuth - the two contain many
|
||||
identical fields, but just a few differences.
|
||||
"""
|
||||
id = RandomSlugField(primary_key=True, length=30)
|
||||
client_id = models.URLField()
|
||||
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
|
||||
scope = models.TextField(blank=True)
|
||||
|
||||
@property
|
||||
def me(self):
|
||||
return self.user.full_url
|
||||
|
||||
def __contains__(self, scope):
|
||||
return scope in self.scope.split(' ')
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
|
||||
class IndieAuthCode(AuthSecret):
|
||||
"""
|
||||
An IndieAuthCode is an authorisation code that a client must provide to us
|
||||
to complete the IndieAuth process.
|
||||
|
||||
Codes are single-use, and if unused will be expired automatically after
|
||||
thirty seconds.
|
||||
"""
|
||||
redirect_uri = models.URLField()
|
||||
|
||||
RESPONSE_TYPE = Choices('id', 'code')
|
||||
response_type = StatusField(choices_name='RESPONSE_TYPE')
|
||||
|
||||
@property
|
||||
def expired(self):
|
||||
return self.created + timedelta(seconds=30) < now()
|
||||
|
||||
|
||||
class Token(AuthSecret):
|
||||
"""
|
||||
A Token grants a client long-term authorisation - it will not expire unless
|
||||
explicitly revoked by the user.
|
||||
"""
|
||||
pass
|
|
@ -1,10 +1,5 @@
|
|||
from jose import jwt
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.conf import settings
|
||||
|
||||
from micropub.views import error
|
||||
from .models import IndieAuthCode, Token
|
||||
|
||||
|
||||
def auth(request):
|
||||
|
@ -25,54 +20,29 @@ def auth(request):
|
|||
return error.unauthorized()
|
||||
|
||||
try:
|
||||
token = decode(token)
|
||||
except Exception as e:
|
||||
token = Token.objects.get(pk=token)
|
||||
except Token.DoesNotExist:
|
||||
return error.forbidden()
|
||||
|
||||
return MicropubToken(token)
|
||||
|
||||
|
||||
class MicropubToken:
|
||||
def __init__(self, tok):
|
||||
self.user = get_user_model().objects.get(pk=tok['uid'])
|
||||
self.client = tok['cid']
|
||||
self.scope = tok['sco']
|
||||
|
||||
self.me = self.user.full_url
|
||||
self.scopes = self.scope.split(' ')
|
||||
|
||||
def __contains__(self, scope):
|
||||
return scope in self.scopes
|
||||
|
||||
|
||||
def encode(payload):
|
||||
return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
|
||||
|
||||
|
||||
def decode(token):
|
||||
return jwt.decode(token, settings.SECRET_KEY, algorithms=('HS256',))
|
||||
return token
|
||||
|
||||
|
||||
def gen_auth_code(req):
|
||||
code = {
|
||||
'uid': req.user.id,
|
||||
'cid': req.POST['client_id'],
|
||||
'uri': req.POST['redirect_uri'],
|
||||
'typ': req.POST.get('response_type', 'id'),
|
||||
'iat': datetime.utcnow(),
|
||||
'exp': datetime.utcnow() + timedelta(seconds=30),
|
||||
}
|
||||
code = IndieAuthCode()
|
||||
code.user = req.user
|
||||
code.client_id = req.POST['client_id']
|
||||
code.redirect_uri = req.POST['redirect_uri']
|
||||
code.response_type = req.POST.get('response_type', 'id')
|
||||
if 'scope' in req.POST:
|
||||
code['sco'] = ' '.join(req.POST.getlist('scope'))
|
||||
|
||||
return encode(code)
|
||||
code.scope = ' '.join(req.POST.getlist('scope'))
|
||||
code.save()
|
||||
return code.id
|
||||
|
||||
|
||||
def gen_token(code):
|
||||
tok = {
|
||||
'uid': code['uid'],
|
||||
'cid': code['cid'],
|
||||
'sco': code['sco'],
|
||||
'iat': datetime.utcnow(),
|
||||
}
|
||||
return encode(tok)
|
||||
tok = Token()
|
||||
tok.user = code.user
|
||||
tok.client_id = code.client_id
|
||||
tok.scope = code.scope
|
||||
tok.save()
|
||||
return tok.id
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
from annoying.decorators import render_to
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import redirect
|
||||
|
@ -11,6 +10,7 @@ from lemoncurry import breadcrumbs, requests, utils
|
|||
from urllib.parse import urlencode, urljoin, urlunparse, urlparse
|
||||
|
||||
from .. import tokens
|
||||
from ..models import IndieAuthCode
|
||||
|
||||
breadcrumbs.add('lemonauth:indie', parent='home:index')
|
||||
|
||||
|
@ -90,25 +90,26 @@ class IndieView(TemplateView):
|
|||
def post(self, request):
|
||||
post = request.POST.dict()
|
||||
try:
|
||||
code = tokens.decode(post.get('code'))
|
||||
except Exception:
|
||||
code = IndieAuthCode.objects.get(pk=post.get('code'))
|
||||
except IndieAuthCode.DoesNotExist:
|
||||
# if anything at all goes wrong when decoding the auth code, bail
|
||||
# out immediately.
|
||||
return utils.forbid('invalid auth code')
|
||||
code.delete()
|
||||
if code.expired:
|
||||
return utils.forbid('invalid auth code')
|
||||
|
||||
if code['typ'] != 'id':
|
||||
if code.response_type != 'id':
|
||||
return utils.bad_req(
|
||||
'this endpoint only supports response_type=id'
|
||||
)
|
||||
if code['cid'] != post.get('client_id'):
|
||||
if code.client_id != post.get('client_id'):
|
||||
return utils.forbid('client id did not match')
|
||||
if code['uri'] != post.get('redirect_uri'):
|
||||
if code.redirect_uri != post.get('redirect_uri'):
|
||||
return utils.forbid('redirect uri did not match')
|
||||
|
||||
user = get_user_model().objects.get(pk=code['uid'])
|
||||
me = urljoin(utils.origin(request), user.url)
|
||||
# If we got here, it's valid! Yay!
|
||||
return utils.choose_type(request, {'me': me}, {
|
||||
return utils.choose_type(request, {'me': code.me}, {
|
||||
'application/x-www-form-urlencoded': utils.form_encoded_response,
|
||||
'application/json': JsonResponse,
|
||||
})
|
||||
|
|
|
@ -1,10 +1,9 @@
|
|||
from django.contrib.auth import get_user_model
|
||||
from django.views import View
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from .. import tokens
|
||||
from ..models import IndieAuthCode
|
||||
from lemoncurry import utils
|
||||
|
||||
|
||||
|
@ -16,7 +15,7 @@ class TokenView(View):
|
|||
return token
|
||||
res = {
|
||||
'me': token.me,
|
||||
'client_id': token.client,
|
||||
'client_id': token.client_id,
|
||||
'scope': token.scope,
|
||||
}
|
||||
return utils.choose_type(req, res)
|
||||
|
@ -24,26 +23,27 @@ class TokenView(View):
|
|||
def post(self, req):
|
||||
post = req.POST
|
||||
try:
|
||||
code = tokens.decode(post.get('code'))
|
||||
except Exception:
|
||||
code = IndieAuthCode.objects.get(pk=post.get('code'))
|
||||
except IndieAuthCode.DoesNotExist:
|
||||
return utils.forbid('invalid auth code')
|
||||
code.delete()
|
||||
if code.expired:
|
||||
return utils.forbid('invalid auth code')
|
||||
|
||||
if code['typ'] != 'code':
|
||||
if code.response_type != 'code':
|
||||
return utils.bad_req(
|
||||
'this endpoint only supports response_type=code'
|
||||
)
|
||||
if code['cid'] != post.get('client_id'):
|
||||
if code.client_id != post.get('client_id'):
|
||||
return utils.forbid('client id did not match')
|
||||
if code['uri'] != post.get('redirect_uri'):
|
||||
if code.redirect_uri != post.get('redirect_uri'):
|
||||
return utils.forbid('redirect uri did not match')
|
||||
|
||||
user = get_user_model().objects.get(pk=code['uid'])
|
||||
me = urljoin(utils.origin(req), user.url)
|
||||
if me != post.get('me'):
|
||||
if code.me != post.get('me'):
|
||||
return utils.forbid('me did not match')
|
||||
|
||||
return utils.choose_type(req, {
|
||||
'access_token': tokens.gen_token(code),
|
||||
'me': me,
|
||||
'scope': code['sco'],
|
||||
'me': code.me,
|
||||
'scope': code.scope,
|
||||
})
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue