Verified Commit abf18994 authored by Sébastiaan Versteeg's avatar Sébastiaan Versteeg
Browse files

Remove thaliapp module

parent d87d920f
......@@ -17,6 +17,5 @@ website
photos
pizzas
thabloid
thaliapp
thaliawebsite
utils
thaliapp package
================
.. automodule:: thaliapp
:members:
:undoc-members:
:show-inheritance:
Submodules
----------
thaliapp.apps module
--------------------
.. automodule:: thaliapp.apps
:members:
:undoc-members:
:show-inheritance:
thaliapp.models module
----------------------
.. automodule:: thaliapp.models
:members:
:undoc-members:
:show-inheritance:
thaliapp.urls module
--------------------
.. automodule:: thaliapp.urls
:members:
:undoc-members:
:show-inheritance:
thaliapp.views module
---------------------
.. automodule:: thaliapp.views
:members:
:undoc-members:
:show-inheritance:
from django.apps import AppConfig
class ThaliappConfig(AppConfig):
name = 'thaliapp'
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-11-09 18:56
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token', models.CharField(max_length=64)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
from django.db import models
from django.conf import settings
from django.utils.crypto import get_random_string
from django.contrib.auth.models import User
from hashlib import sha256
class Token(models.Model):
"""This class contains an authentication token for an user
An user may have multiple tokens"""
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
token = models.CharField(max_length=64)
@classmethod
def create_token(cls, user):
# Post quantum approved
token = get_random_string(length=64)
hashed_token = sha256(
''.join([user.username, token]).encode()).hexdigest()
t = cls(user=user, token=hashed_token)
t.save()
return token
@classmethod
def authenticate(cls, username, token):
hashed_token = sha256(''.join([username, token]).encode()).hexdigest()
try:
user = User.objects.get(username=username,
token__token=hashed_token)
except User.DoesNotExist:
return None
return user
from datetime import datetime
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase, override_settings
from members.models import Member
from thaliapp.models import Token
class RaaSTestCase(SimpleTestCase):
def test_raas(self):
response = self.client.get('/api/randomasaservice')
self.assertEqual(response.json()['status'], 'ok')
self.assertIn('random', response.json())
response = self.client.post('/api/randomasaservice')
self.assertEqual(response.json()['status'], 'ok')
self.assertIn('random', response.json())
# preimage: key
@override_settings(
THALIAPP_API_KEY=('2c70e12b7a0646f92279f427c7b38e'
'7334d8e5389cff167a1dc30e73f826b683'))
class AppApiTestCase(TestCase):
"""Tests event registrations"""
@classmethod
def setUpTestData(cls):
cls.user = get_user_model().objects.create_user(
username='testuser',
first_name='first',
last_name='last_name',
email='foo@bar.com',
password='top secret')
cls.member = Member.objects.create(
user=cls.user,
birthday=datetime(1993, 3, 2)
)
cls.token = Token.create_token(cls.user)
def test_GET_denied(self):
response = self.client.get('/api/login')
self.assertEqual(response.status_code, 405)
response = self.client.get('/api/app')
self.assertEqual(response.status_code, 405)
def test_wrong_apikey(self):
response = self.client.post('/api/login',
{'apikey': 'bla',
'username': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()['status'], "error")
response = self.client.post('/api/app',
{'apikey': 'bla',
'username': 'testuser',
'token': self.token})
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()['status'], "error")
def test_wrong_arguments(self):
response = self.client.post('/api/login',
{'apikey': 'key',
'username': 'testuser',
'pas': 'top secret'})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['status'], "error")
response = self.client.post('/api/login',
{'apikey': 'key',
'user': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['status'], "error")
response = self.client.post('/api/app',
{'apikey': 'key',
'username': 'testuser',
'tok': self.token})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['status'], "error")
response = self.client.post('/api/login',
{'apikey': 'key',
'user': 'testuser',
'token': self.token})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['status'], "error")
def test_wrong_password(self):
response = self.client.post('/api/login',
{'apikey': 'key',
'username': 'testuser',
'password': 'wrong'})
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()['status'], "error")
def test_correct_login(self):
response = self.client.post('/api/login',
{'apikey': 'key',
'username': 'testuser',
'password': 'top secret'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['status'], 'ok')
self.assertEqual(response.json()['username'], 'testuser')
self.assertIn('token', response.json())
self.assertIn('profile_image', response.json())
def test_correct_token_login(self):
response = self.client.post('/api/app',
{'apikey': 'key',
'username': 'testuser',
'token': self.token})
self.assertEqual(response.status_code, 200)
data = response.json()
self.assertIn('profile_image', data)
del data['profile_image']
self.assertEqual(data['status'], 'ok')
self.assertEqual(data['birthday'], '1993-03-02')
self.assertEqual(data['real_name'], 'first last_name')
self.assertEqual(data['display_name'], 'first last_name')
self.assertEqual(data['membership_type'], 'Expired')
self.assertEqual(data['over18'], True)
self.assertEqual(data['is_thalia_member'], False)
from django.conf.urls import url
from rest_framework.authtoken import views as rfviews
from . import views
app_name = "thaliapp"
urlpatterns = [
url(r'^login', views.login,
name='thaliapp-login'),
url(r'^app', views.app,
name='thaliapp-app'),
url(r'^randomasaservice', views.raas,
name='thaliapp-raas'),
]
from django.conf import settings
from django.http import (JsonResponse, HttpResponseBadRequest,
HttpResponseForbidden)
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.contrib.auth import authenticate
from django.contrib.staticfiles.finders import find as find_static_file
from django.core.cache import cache
from django.views.decorators.debug import (sensitive_variables,
sensitive_post_parameters)
from thaliapp.models import Token
from hashlib import sha256
from base64 import b64encode
import datetime
from os import urandom
from binascii import hexlify
def get_photo(user):
if user.member.photo:
photo = ''.join(['data:image/jpeg;base64,',
b64encode(
user.member.photo.file.read()).decode()
])
else:
filename = find_static_file('members/images/default-avatar.jpg')
with open(filename, 'rb') as f:
photo = ''.join(['data:image/jpeg;base64,',
b64encode(f.read()).decode()
])
return photo
@sensitive_post_parameters()
@sensitive_variables('user', 'password', 'token')
@csrf_exempt
@require_POST
def login(request):
if (sha256(request.POST.get('apikey', '').encode('ascii')).hexdigest() !=
settings.THALIAPP_API_KEY):
return HttpResponseForbidden(
'{"status":"error","msg":"wrong api key"}',
content_type='application/json')
user = request.POST.get('username')
password = request.POST.get('password')
if user is None or password is None:
return HttpResponseBadRequest(
'{"status":"error","msg":"Missing username or password"}',
content_type='application/json')
user = authenticate(username=user, password=password)
if user is not None:
token = Token.create_token(user)
photo = get_photo(user)
return JsonResponse({'status': 'ok',
'username': user.username,
'token': token,
'profile_image': photo,
})
return JsonResponse({'status': 'error',
'msg': 'Authentication Failed'},
status=403)
@sensitive_post_parameters()
@sensitive_variables('username', 'token')
@csrf_exempt
@require_POST
def app(request):
username = request.POST.get('username')
token = request.POST.get('token')
if (sha256(request.POST.get('apikey', '').encode('ascii')).hexdigest() !=
settings.THALIAPP_API_KEY):
return HttpResponseForbidden(
'{"status": "error", "message": "wrong api key"}',
content_type='application/json')
if username is None or token is None:
return HttpResponseBadRequest(
'{"status": "error","msg": "Missing arguments"}',
content_type='application/json')
user = Token.authenticate(username, token)
if user is None:
return JsonResponse({'status': 'error',
'msg': 'Authentication Failed'},
status=403)
today = datetime.date.today()
try:
eightteen_years_ago = today.replace(year=today.year - 18)
except ValueError as e:
# handle leap years
if today.month == 2 and today.day == 29:
eightteen_years_ago = today.replace(year=today.year - 18, day=28)
else:
raise e
over18 = user.member.birthday <= eightteen_years_ago
membership = user.member.current_membership
if membership:
membership_type = membership.type
is_member = True
else:
membership_type = 'Expired'
is_member = False
return JsonResponse({'status': 'ok',
'real_name': user.member.get_full_name(),
'display_name': user.member.display_name(),
'birthday': str(user.member.birthday),
'over18': over18,
'membership_type': membership_type,
'is_thalia_member': is_member,
'profile_image': get_photo(user),
})
@sensitive_post_parameters()
@sensitive_variables('username', 'token')
@csrf_exempt
@require_POST
def scan(request):
"""Not used until wolktm is deprecated"""
username = request.POST.get('username')
token = request.POST.get('token')
qrtoken = request.POST.get('qrToken')
if username is None or token is None or qrtoken is None:
return HttpResponseBadRequest()
user = Token.authenticate(username, token)
if user is None:
return JsonResponse({'status': 'error',
'msg': 'Authentication Failed'},
status=403)
cache.set(''.join([qrtoken]), user, 300)
return JsonResponse({'status': 'ok'})
@csrf_exempt
def raas(request):
return JsonResponse({'status': 'ok',
'random': hexlify(urandom(16)).decode()})
......@@ -70,7 +70,6 @@ INSTALLED_APPS = [
'pizzas',
'newsletters',
'education',
'thaliapp',
'announcements',
]
......@@ -239,10 +238,6 @@ PHOTO_UPLOAD_SIZE = 1920, 1080
# API key for wiki
WIKI_API_KEY = 'debug'
# API key for thaliapp related stuff
# SHA256 hash so it does not need replacement in production
THALIAPP_API_KEY = ('5b2bff55b74f74678dd578f8f669e959'
'09f356aa05548ecdf418e678af334844')
# CORS config
CORS_ORIGIN_ALLOW_ALL = True
......
......@@ -107,7 +107,6 @@ urlpatterns = [
url(r'^', include('members.api.urls')),
url(r'^', include('partners.api.urls')),
], namespace='v1')),
url(r'^', include('thaliapp.urls')),
])),
url(r'^education/', include('education.urls')),
url(r'^announcements/', include('announcements.urls')),
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment