0f46ff79916a30697c4dde15da10f06efb8f8a05
[myslice.git] / unfold / loginrequired.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, request, *args, **kwargs):
14         return super(LoginRequiredView, self).dispatch(request, *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 (fun_that_returns_httpresponse):
28     def wrapped (request, *args, **kwds):
29         print 'wrapped by logout_on_manifold_exception'
30         try:
31             return fun_that_returns_httpresponse(request,*args, **kwds)
32         except ManifoldException, manifold_result:
33             # xxx we need a means to display this message to user...
34             from django.contrib.auth import logout
35             logout(request)
36             return HttpResponseRedirect ('/')
37         except Exception, e:
38             # xxx we need to sugarcoat this error message in some error template...
39             print "Unexpected exception",e
40             import traceback
41             traceback.print_exc()
42             return HttpResponseRedirect ('/')
43     return wrapped
44
45 # at first sight this matters only for views that require login
46 # so for now we expose a single class that behaves like 
47 # login_required + logout_on_manifold_exception
48 class LoginRequiredAutoLogoutView (TemplateView):
49
50     @logout_on_manifold_exception
51     @method_decorator(login_required)
52     def dispatch (self, request, *args, **kwds):
53         return super(LoginRequiredAutoLogoutView,self).dispatch(request,*args,**kwds)