0d76fcd5bf1c8779e98b761d8cca6efe5142fb53
[myslice.git] / portal / templateviews.py
1 from django.contrib.auth.decorators     import login_required
2 from django.utils.decorators            import method_decorator
3 from django.http                        import HttpResponseRedirect
4 # for 'as_view' that we need to call in urls.py and the like
5 from django.views.generic.base          import TemplateView
6
7 from manifold.manifoldresult            import ManifoldException
8
9 ########## the base class for views that require a login
10 class LoginRequiredView (TemplateView):
11
12     @method_decorator(login_required)
13     def dispatch(self, *args, **kwargs):
14         return super(LoginRequiredView, self).dispatch(*args, **kwargs)
15
16
17 ########## the base class for views that need to protect against ManifoldException
18 # a decorator for view classes to catch manifold exceptions
19 # by design views should not directly exercise a manifold query
20 # given that these are asynchroneous, you would expect a view to just 
21 # return a mundane skeleton
22 # however of course this is not always true, 
23 # e.g. we deal with metadata some other way, and so
24 # it is often a good idea for a view to monitor these exceptions
25 # and to take this opportunity to logout people 
26
27 def logout_on_manifold_exception (view_as_a_function):
28     def wrapped (request, *args, **kwds):
29         try:
30             return view_as_a_function(request,*args, **kwds)
31         except ManifoldException, manifold_result:
32             # xxx we need a means to display this message to user...
33             from django.contrib.auth import logout
34             logout(request)
35             return HttpResponseRedirect ('/')
36         except Exception, e:
37             # xxx we need to sugarcoat this error message in some error template...
38             print "Unexpected exception",e
39             import traceback
40             traceback.print_exc()
41             return HttpResponseRedirect ('/')
42     return wrapped
43
44 # at first sight this matters only for views that require login
45 # however we prefer this to be explicit
46 # i.e. a user class has to inherit both LoginRequiredView and LogoutOnManifoldExceptionView
47
48 class LogoutOnManifoldExceptionView (TemplateView):
49
50     @logout_on_manifold_exception
51     def get (self, request, *args, **kwds):
52         return self.get_or_logout (request, *args, **kwds)