adding APIKey method
This commit is contained in:
@@ -164,7 +164,7 @@ from rowers.models import (
|
||||
StandardCollection, CourseStandard,
|
||||
VirtualRaceFollower, TombStone, InstantPlan,
|
||||
PlannedSessionStep,InStrokeAnalysis, ForceCurveAnalysis, SyncRecord,
|
||||
UserMessage,
|
||||
UserMessage,APIKey,
|
||||
)
|
||||
from rowers.models import ( RowerPowerForm, RowerHRZonesForm, SimpleRowerPowerForm,
|
||||
RowerForm, RowerCPForm, GraphImage, AdvancedWorkoutForm,
|
||||
@@ -307,6 +307,27 @@ import base64
|
||||
from django.http import HttpResponse
|
||||
from django.contrib.auth import authenticate, login
|
||||
|
||||
def view_or_apikey(view, request, test_func, realm = "", *args, **kwargs):
|
||||
if test_func(request.user):
|
||||
return view(request, *args, **kwargs)
|
||||
|
||||
if 'Authorization' in request.META:
|
||||
api_key = request.META.get('Authorization')
|
||||
if api_key:
|
||||
try:
|
||||
api_key = APIKey.objects.get(key=api_key, is_active=True)
|
||||
except APIKey.DoesNotExist:
|
||||
raise AuthenticationFailed('Invalid API key')
|
||||
|
||||
login(request, api_key.user, backend='django.contrib.auth.backends.ModelBackend')
|
||||
request.user = api_key.user
|
||||
return view(request, *args, **kwargs)
|
||||
|
||||
response = HttpResponse()
|
||||
response.status_code = 401
|
||||
response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
|
||||
return response
|
||||
|
||||
#############################################################################
|
||||
#
|
||||
def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
|
||||
@@ -348,6 +369,15 @@ def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs):
|
||||
|
||||
#############################################################################
|
||||
#
|
||||
def logged_in_or_apikey(realm = ""):
|
||||
def view_decorator(func):
|
||||
def wrapper(request, *args, **kwargs):
|
||||
return view_or_apikey(func, request,
|
||||
lambda u: u.is_authenticated,
|
||||
realm, *args, **kwargs)
|
||||
return wrapper
|
||||
return view_decorator
|
||||
|
||||
def logged_in_or_basicauth(realm = ""):
|
||||
"""
|
||||
A simple decorator that requires a user to be logged in. If they are not
|
||||
|
||||
Reference in New Issue
Block a user