cafe plugin
[unfold.git] / plugins / cafe-1.0 / edelberto-120314.py
1 #!/usr/bin/env python
2
3 #Edelberto from manifoldauth
4 import os,sys
5 import subprocess
6 import shlex
7 import getpass
8 from hashlib import md5
9 import time
10 from random import Random
11 import crypt
12
13 import re
14 #from manifold.manifold.core.router import Router
15 from manifold.core.query                import Query
16 from manifoldapi.manifoldapi               import execute_admin_query
17 from portal.actions                     import manifold_add_user, manifold_add_account, manifold_update_account
18 from manifold.core.query import Query
19 # add user to manifold
20
21 from django.views.generic import View
22 from django.core.context_processors import csrf
23 #from django.http import HttpResponseRedirect
24 from django.contrib.auth import authenticate, login, logout
25 from django.template import RequestContext
26 from django.shortcuts import render_to_response
27
28 from manifold.manifoldresult import ManifoldResult
29 from ui.topmenu import topmenu_items, the_user
30 from myslice.configengine import ConfigEngine
31
32 #from django.http import HttpResponse HttpResponseRedirect
33 from django.http import HttpResponse
34 #from django.http import HttpResponseRedirect
35 #from django.template import  RequestContext
36 from django.contrib.sessions.backends.db import SessionStore
37
38 def index(request):
39 #class EdelbertoView (View):
40
41 # =================== Old code - to validate =================
42     '''
43     ip = "<html><body>" 
44     ip += "cn: " +  request.META['Shib-inetOrgPerson-cn'] + "</br>"
45     ip += "sn: " +  request.META['Shib-inetOrgPerson-sn'] + "</br>"
46     ip += "eppn: " + request.META['Shib-eduPerson-eduPersonPrincipalName'] + "</br>"
47     ip += "mail: " + request.META['Shib-inetOrgPerson-mail'] + "</br>"
48     ip += "Affiliation br: " + request.META['Shib-brEduPerson-brEduAffiliationType'] + "</br>"
49     ip += "Affiliation edu: " + request.META['Shib-eduPerson-eduPersonAffiliation'] + "</br>"
50     ip += "Auth-Method: " + request.META['Shib-Authentication-Method'] + "</br>"
51     ip += "Identity Provider: " + request.META['Shib-Identity-Provider'] + "</br>"
52     ip += "Application ID: " + request.META['Shib-Application-ID'] + "</br>"
53     ip += "Session ID: " + request.META['Shib-Session-ID'] + "</br>"
54     '''
55 # Test cookie support
56     if request.session.test_cookie_worked():
57     #if session.test_cookie_worked():
58         return HttpResponse("Please enable cookies and try again.")
59         #return
60         print "Please enable cookies and try again."
61     else:
62         request.session['cn'] = request.META['Shib-inetOrgPerson-cn']
63         request.session['sn'] = request.META['Shib-inetOrgPerson-sn']
64         request.session['mail'] = request.META['Shib-inetOrgPerson-mail']
65         request.session['eppn'] = request.META['Shib-eduPerson-eduPersonPrincipalName']
66         #request.session['aff'] = request.META['Shib-brEduPerson-brEduAffiliationType']
67         request.session['aff'] = request.META['Shib-eduPerson-eduPersonAffiliation']
68         request.session['shib'] = request.META['Shib-Session-ID']
69
70         if 'mail' in request.session.keys():
71              print "Cookie: OK -> Content: cn:" + request.session["cn"] + " sn " +request.session["sn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]
72              #ip += "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]  + "</body></html>"
73         else:
74              print "Cookie: nothing/clear"
75              #ip += "Cookie: nothing/clear </body></html>"
76     
77    # return HttpResponse(ip)
78    
79
80     # expose this so we can mention the backend URL on the welcome page
81     def default_env (self):
82         config=Config()
83         return { 
84                  'MANIFOLD_URL':config.manifold_url(),
85                  }
86
87     #def post (self,request):
88     #    env = self.default_env()
89         #username = request.POST.get('username')
90         #password = request.POST.get('password')
91     # if we use ABAC based on 'aff'
92     #if 'aff' in request.session.keys():
93     aff = request.session["aff"]
94     # if we use ABAC - based on 'aff'
95     #if aff == "student":
96     # XXX It's only to test the association of admin and esilva@uff.br
97     if request.session["eppn"] == 'esilva@uff.br':
98         username = 'admin'
99         password = 'admin'
100     # For all users
101     else:
102         username = request.session["mail"]
103  # this is ugly. We generate a simple password with merge of mail and a string.
104         password = request.session["mail"] + "fibre2013"
105      
106         username = username.replace('"','').strip()
107         password = password.replace('"','').strip()
108     # pass request within the token, so manifold session key can be attached to the request session.
109     token = {'username': username, 'password': password, 'request': request}    
110
111         # our authenticate function returns either
112         # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
113         # . a django User in case of success
114         # . or None if the backend could be reached but the authentication failed
115     auth_result = authenticate(token=token)
116         # high-level errors, like connection refused or the like
117     
118     if isinstance (auth_result, ManifoldResult):
119         manifoldresult = auth_result
120         # let's use ManifoldResult.__repr__
121         '''
122         env['state']="%s"%manifoldresult
123         return render_to_response('home-view.html',env, context_instance=RequestContext(request))
124     '''
125         htm =  "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-fibre.cafeexpresso.rnp.br/login-ok\" />"
126         return HttpResponse (htm)    
127         # user was authenticated at the backend
128     elif auth_result is not None:
129         user=auth_result
130     
131     if user.is_active:
132         print "LOGGING IN"
133         login(request, user)
134         htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-fibre.cafeexpresso.rnp.br/login-ok\" />"
135             #return HttpResponseRedirect ('/login-ok')
136         return HttpResponse (htm)
137     else:
138         env['state'] = "Your account is not active, please contact the site admin."
139         return render_to_response('home-view.html',env, context_instance=RequestContext(request))
140     # otherwise
141     else:
142     '''
143         magic = "$1$"
144         password = password
145         # Generate a somewhat unique 8 character salt string
146         salt = str(time.time()) + str(Random().random())
147         salt = md5(salt).hexdigest()[:8]
148
149         if len(password) <= len(magic) or password[0:len(magic)] != magic:
150         password = crypt.crypt(password.encode('latin1'), magic + salt + "$")
151
152         user_params = {
153             'email': username,
154         'password': password
155     }
156     query = Query(action='create', object='local:user', params=user_params)
157
158
159         # Instantiate a TopHat router
160     with Router() as router:
161         router.forward(query)
162     '''
163     #myArgs=[username,password]
164     #os.spawnlp(os.P_WAIT,'/tmp/adduser.py', username, password, '/bin/bash/'i)
165     #command = '/var/www/manifold/manifold/bin/adduser.py ' + username + ' ' + password
166     #command = 'ls -la'
167             #args = shlex.split(command)
168             #p = subprocess.Popen(args, stdin=subprocess.PIPE).communicate()[0]
169         #print command
170         #print args
171         #print p
172     #env['state'] = "Now your CAFe user is associated to your MySlice account - Please logging in CAFe again."
173     #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
174     user_params = { 'email': username, 'password': password }
175     manifold_add_user(request,user_params)
176     
177     #query = Query().get('user').filter_by('email', '=', username).select('user_id')
178     #user = execute_admin_query(request,query)
179     #print "USER_ID:" + user
180     #user_id = user['user_id']
181     #user_id = user[0]
182     #print user_id
183     #splitmail = username.split("@")[0]
184     #user_params = { 'user': splitmail, 'platform': 'myslice' }
185     #user_params = { 'user_id': '2', 'platform_id': '2' }
186     #manifold_add_account(request,user_params)
187
188     # Ugly! Forcing the association of user and platform. This need to be automatic.    
189     splitmail = username.split("@")[0]
190     user = splitmail.replace('"','').strip()
191     hrn = "fibrebr.dummy." + user
192     user_hrn = '{ "user_hrn": "'+ hrn +'" }'
193     #user_params = { 'config': user_hrn, 'auth_type': 'managed' }
194     user_params2 = { 'user_id': '2', 'platform_id': '2', 'config': user_hrn, 'auth_type': 'managed' }
195     manifold_add_account(request,user_params2)
196
197     ##user_id = '3'
198     #manifold_update_account(request,user_params)
199     html = "Now your CAFe user is associated with a MySlice account - Please login in CAFe again."
200     return HttpResponse(html)
201
202      # If we use ABAC - based on 'aff'
203      #   else:
204          #   #env['state'] = "Your affiliation (" + request.session["aff"] + ") at CAFe is not accepted."
205          #   html = "Your CAFe affiliation (" + request.session["aff"] + ") is not accepted. <br> Only \"student\" affiliation."
206          #   return HttpResponse(html)
207             #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
208             
209
210             # login-ok sets state="Welcome to MySlice" in urls.py
211         def get (self, request, state=None):
212             env = self.default_env()
213             env['username']=the_user(request)
214             env['topmenu_items'] = topmenu_items(None, request)
215             if state: env['state'] = state
216             elif not env['username']: env['state'] = "Please sign in"
217             return HttpResponseRedirect ('/login-ok')
218         #return render_to_response('home-view.html',env, context_instance=RequestContext(request))