Skip to content

Commit

Permalink
Many improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
juyrjola committed Jun 11, 2015
1 parent 60a9007 commit f78f575
Show file tree
Hide file tree
Showing 18 changed files with 102 additions and 28 deletions.
File renamed without changes.
File renamed without changes.
23 changes: 23 additions & 0 deletions hkijwt/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.OAUTH2_PROVIDER_APPLICATION_MODEL),
]

operations = [
migrations.CreateModel(
name='AppToAppPermission',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('requester', models.ForeignKey(related_name='+', to=settings.OAUTH2_PROVIDER_APPLICATION_MODEL)),
('target', models.ForeignKey(related_name='+', to=settings.OAUTH2_PROVIDER_APPLICATION_MODEL)),
],
),
]
File renamed without changes.
7 changes: 7 additions & 0 deletions hkijwt/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.db import models
from oauth2_provider.models import Application


class AppToAppPermission(models.Model):
requester = models.ForeignKey(Application, db_index=True, related_name='+')
target = models.ForeignKey(Application, db_index=True, related_name='+')
File renamed without changes.
File renamed without changes.
17 changes: 0 additions & 17 deletions hkiprofile/models.py

This file was deleted.

37 changes: 34 additions & 3 deletions hkisaml/api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import logging
import jwt
import datetime

from django.contrib.auth import get_user_model
from rest_framework import permissions, serializers, generics, mixins, views
from rest_framework.response import Response
from rest_framework.exceptions import PermissionDenied
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
from oauth2_provider.models import get_application_model
from hkijwt.models import AppToAppPermission

logger = logging.getLogger(__name__)


class UserSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -46,11 +53,35 @@ def get_object(self):


class GetJWTView(views.APIView):
# permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]

def get(self, request, format=None):
secret = '12345'
user = get_user_model().objects.first()
requester_app = request.auth.application
target_app = request.QUERY_PARAMS.get('target_app', '').strip()
if target_app:
qs = get_application_model().objects.all()
target_app = generics.get_object_or_404(qs, client_id=target_app)
try:
perm = AppToAppPermission.objects.get(requester=requester_app,
target=target_app)
except AppToAppPermission.DoesNotExist:
raise PermissionDenied()
else:
target_app = requester_app

secret = target_app.client_secret
user = request.user

payload = UserSerializer(user).data
delete_fields = ['last_login', 'date_joined', 'uuid']
for field in delete_fields:
if field in payload:
del payload[field]

payload['iss'] = 'https://api.hel.fi/sso' # FIXME: Make configurable
payload['sub'] = str(user.uuid)
payload['aud'] = target_app.client_id
payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
encoded = jwt.encode(payload, secret, algorithm='HS256')
return Response({'token': encoded})

Expand Down
22 changes: 16 additions & 6 deletions hkisaml/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,15 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'djangosaml2',
'oauth2_provider',
'corsheaders',
'hkiprofile',

'helusers',

'hkijwt',
'users',
)

MIDDLEWARE_CLASSES = (
Expand Down Expand Up @@ -87,7 +92,7 @@

LOGIN_URL = '/sso/saml2/login/'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
AUTH_USER_MODEL = 'hkiprofile.User'
AUTH_USER_MODEL = 'users.User'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
Expand Down Expand Up @@ -187,9 +192,9 @@
'contact_type': 'technical'
}],
# you can set multilanguage information here
#'organization': {
# 'organization': {
# 'name': [('City of Helsinki', 'en'), ('Helsingin kaupunki', 'fi')],
#},
# },
'valid_for': 24, # how long is our metadata valid
}

Expand All @@ -210,12 +215,12 @@
'level': 'DEBUG',
'class': 'django.utils.log.NullHandler',
},
'console':{
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
},
},
'loggers': {
'django': {
'handlers': ['console'],
Expand Down Expand Up @@ -249,6 +254,11 @@

CORS_ORIGIN_ALLOW_ALL = True

OAUTH2_PROVIDER_APPLICATION_MODEL = 'oauth2_provider.Application'
OAUTH2_PROVIDER = {
'CLIENT_SECRET_GENERATOR_LENGTH': 96,
}

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ django-oauth-toolkit
django-cors-headers
djangorestframework
pyjwt
git+https://github.com/City-of-Helsinki/django-helusers.git#egg=django-helusers
Empty file added users/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions users/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ class Migration(migrations.Migration):
],
options={
'abstract': False,
'verbose_name': 'user',
'verbose_name_plural': 'users',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
Expand Down
Empty file added users/migrations/__init__.py
Empty file.
12 changes: 12 additions & 0 deletions users/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import uuid
from django.db import models
from helusers.models import AbstractUser


class User(AbstractUser):
primary_sid = models.CharField(max_length=100, unique=True)

def save(self, *args, **kwargs):
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(User, self).save(*args, **kwargs)
3 changes: 3 additions & 0 deletions users/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions users/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.

0 comments on commit f78f575

Please sign in to comment.