diff --git a/PyRIGS/decorators.py b/PyRIGS/decorators.py index 5e4e613d..a7c1db90 100644 --- a/PyRIGS/decorators.py +++ b/PyRIGS/decorators.py @@ -33,4 +33,35 @@ def permission_required_with_403(perm, login_url=None): Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page or rendering a 403 as necessary. """ - return user_passes_test_with_403(lambda u: u.has_perm(perm), login_url=login_url) \ No newline at end of file + return user_passes_test_with_403(lambda u: u.has_perm(perm), login_url=login_url) + +from RIGS import models + +def api_key_required(function): + """ + Decorator for views that checks api_pk and api_key. + Failed users will be given a 403 error. + Should only be used for urls which include and kwargs + """ + def wrap(request, *args, **kwargs): + + userid = kwargs.get('api_pk') + key = kwargs.get('api_key') + + error_resp = render_to_response('403.html', context_instance=RequestContext(request)) + error_resp.status_code = 403 + + if key is None: + return error_resp + if userid is None: + return error_resp + + try: + user_object = models.Profile.objects.get(pk=userid) + except Profile.DoesNotExist: + return error_resp + + if user_object.api_key != key: + return error_resp + return function(request, *args, **kwargs) + return wrap \ No newline at end of file