method_wrapper()   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
c 0
b 0
f 0
dl 0
loc 16
rs 8.6666
1
from django.core.exceptions import PermissionDenied, ValidationError
2
from django.http import HttpRequest, HttpResponse
3
from django.shortcuts import redirect
4
5
6
def login_required_no_redirect(do_redirect=None):
7
	"""
8
	@param do_redirect: throws exception on None, redirects to login on True, redirects to register of False
9
	@type do_redirect: bool
10
	"""
11
	def method_wrapper(f):
12
		def wrap(*args, **kwargs):
13
			# handle self
14
			request = args[0] if isinstance(args[0], HttpRequest) else args[1]
15
			if request.user.is_authenticated():
16
				return f(*args, **kwargs)
17
			else:
18
				if do_redirect is None:
19
					raise PermissionDenied
20
				else:
21
					type_arg = "login" if do_redirect else "register"
22
					return redirect('/register?type={}&next={}'.format(type_arg, request.path))
23
24
		wrap.__doc__ = f.__doc__
25
		wrap.__name__ = f.__name__
26
		return wrap
27
	return method_wrapper
28
29
30
def validation(func):
31
	def wrapper(*a, **ka):
32
		try:
33
			return func(*a, **ka)
34
		except ValidationError as e:
35
			message = e.message
36
			return HttpResponse(message, content_type='text/plain')
37
	return wrapper
38