FIBRE: updated to the new version, wip on institution page
[unfold.git] / manifoldapi / manifoldproxy.py
1 import json
2 import os.path
3
4 # this is for django objects only
5 #from django.core import serializers
6 from django.http                import HttpResponse, HttpResponseForbidden
7
8 #from manifoldapi.manifoldquery import ManifoldQuery
9 from manifold.core.query        import Query
10 from manifold.core.result_value import ResultValue
11 from manifoldapi                import ManifoldAPI
12 from manifoldresult             import ManifoldException
13 from manifold.util.log          import Log
14 from myslice.configengine       import ConfigEngine
15
16 debug=False
17 #debug=True
18
19 # pretend the server only returns - empty lists to 'get' requests - this is to mimick 
20 # misconfigurations or expired credentials or similar corner case situations
21 debug_empty=False
22 #debug_empty=True
23
24 # this view is what the javascript talks to when it sends a query
25 # see also
26 # myslice/urls.py
27 # as well as 
28 # static/js/manifold.js
29 def proxy (request,format):
30     """the view associated with /manifold/proxy/ 
31 with the query passed using POST"""
32     
33     # expecting a POST
34     if request.method != 'POST':
35         print "manifoldproxy.api: unexpected method %s -- exiting"%request.method
36         return 
37     # we only support json for now
38     # if needed in the future we should probably cater for
39     # format_in : how is the query encoded in POST
40     # format_out: how to serve the results
41     if format != 'json':
42         print "manifoldproxy.proxy: unexpected format %s -- exiting"%format
43         return HttpResponse ({"ret":0}, mimetype="application/json")
44     try:
45         # translate incoming POST request into a query object
46         if debug: print 'manifoldproxy.proxy: request.POST',request.POST
47         manifold_query = Query()
48         #manifold_query = ManifoldQuery()
49         manifold_query.fill_from_POST(request.POST)
50         # retrieve session for request
51
52         # We allow some requests to use the ADMIN user account
53         if (manifold_query.get_from() == 'local:user' and manifold_query.get_action() == 'create') \
54                 or (manifold_query.get_from() == 'local:platform' and manifold_query.get_action() == 'get'):
55             admin_user, admin_password = ConfigEngine().manifold_admin_user_password()
56             manifold_api_session_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
57         else:
58             print manifold_query
59             print request.session['manifold']
60             manifold_api_session_auth = request.session['manifold']['auth']
61
62         if debug_empty and manifold_query.action.lower()=='get':
63             json_answer=json.dumps({'code':0,'value':[]})
64             print "By-passing : debug_empty & 'get' request : returning a fake empty list"
65             return HttpResponse (json_answer, mimetype="application/json")
66                 
67         # actually forward
68         manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
69         if debug: print '===> manifoldproxy.proxy: sending to backend', manifold_query
70         # for the benefit of the python code, manifoldAPI raises an exception if something is wrong
71         # however in this case we want to propagate the complete manifold result to the js world
72
73         result = manifold_api.forward(manifold_query.to_dict())
74
75         # XXX TEMP HACK
76         if 'description' in result and result['description'] \
77                 and isinstance(result['description'], (tuple, list, set, frozenset)):
78             result [ 'description' ] = [ ResultValue.to_html (x) for x in result['description'] ]
79
80         json_answer=json.dumps(result)
81
82         return HttpResponse (json_answer, mimetype="application/json")
83
84     except Exception,e:
85         print "** PROXY ERROR **",e
86         import traceback
87         traceback.print_exc()
88         return HttpResponse ({"ret":0}, mimetype="application/json")
89
90 #################### 
91 # see CSRF_FAILURE_VIEW in settings.py
92 # the purpose of redefining this was to display the failure reason somehow
93 # this however turns out disappointing/not very informative
94 failure_answer=[ "csrf_failure" ]
95 def csrf_failure(request, reason=""):
96     print "CSRF failure with reason '%s'"%reason
97     return HttpResponseForbidden (json.dumps (failure_answer), mimetype="application/json")