3 #Edelberto from manifoldauth
8 from hashlib import md5
10 from random import Random
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
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
28 from manifold.manifoldresult import ManifoldResult
29 from ui.topmenu import topmenu_items, the_user
30 from myslice.configengine import ConfigEngine
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
39 #class EdelbertoView (View):
41 # =================== Old code - to validate =================
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>"
56 if request.session.test_cookie_worked():
57 #if session.test_cookie_worked():
58 return HttpResponse("Please enable cookies and try again.")
60 print "Please enable cookies and try again."
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']
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>"
74 print "Cookie: nothing/clear"
75 #ip += "Cookie: nothing/clear </body></html>"
77 # return HttpResponse(ip)
80 # expose this so we can mention the backend URL on the welcome page
81 def default_env (self):
84 'MANIFOLD_URL':config.manifold_url(),
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'
96 # XXX It's only to test the association of admin and esilva@uff.br
97 if request.session["eppn"] == 'esilva@uff.br':
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"
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}
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
118 if isinstance (auth_result, ManifoldResult):
119 manifoldresult = auth_result
120 # let's use ManifoldResult.__repr__
122 env['state']="%s"%manifoldresult
123 return render_to_response('home-view.html',env, context_instance=RequestContext(request))
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:
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)
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))
145 # Generate a somewhat unique 8 character salt string
146 salt = str(time.time()) + str(Random().random())
147 salt = md5(salt).hexdigest()[:8]
149 if len(password) <= len(magic) or password[0:len(magic)] != magic:
150 password = crypt.crypt(password.encode('latin1'), magic + salt + "$")
156 query = Query(action='create', object='local:user', params=user_params)
159 # Instantiate a TopHat router
160 with Router() as router:
161 router.forward(query)
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
167 #args = shlex.split(command)
168 #p = subprocess.Popen(args, stdin=subprocess.PIPE).communicate()[0]
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)
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']
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)
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)
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)
202 # If we use ABAC - based on 'aff'
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))
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))