4 # XXX We need to clean it!!
5 from portal.models import PendingUser
7 #Edelberto from manifoldauth
12 from hashlib import md5
14 from random import randint
18 #from manifold.manifold.core.router import Router
19 from manifold.core.query import Query
20 from manifoldapi.manifoldapi import execute_admin_query, execute_query
21 #from portal.actions import manifold_add_user, manifold_add_account, manifold_update_account
22 #from portal.actions import manifold_add_account, manifold_add_reference_user_accounts, sfa_create_user, create_pending_user
23 from portal.actions import create_pending_user, create_user
24 from manifold.core.query import Query
25 # add user to manifold
27 from unfold.loginrequired import FreeAccessView
29 from django.views.generic import View
30 from django.core.context_processors import csrf
31 from django.contrib.auth import authenticate, login, logout
32 from django.template import RequestContext
33 from django.shortcuts import render_to_response
35 from manifoldapi.manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
36 from ui.topmenu import topmenu_items, the_user
37 from myslice.configengine import ConfigEngine
39 #from django.http import HttpResponse HttpResponseRedirect
40 from django.http import HttpResponse
41 #from django.http import HttpResponseRedirect
42 #from django.template import RequestContext
43 from django.contrib.sessions.backends.db import SessionStore
45 from portal.homeview import HomeView
47 # View for authenticate the user
48 class EdelbertoView (HomeView):
49 def get(self,request):
50 env = self.default_env()
51 env['theme'] = self.theme
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)
79 # expose this so we can mention the backend URL on the welcome page
80 def default_env (self):
82 'MANIFOLD_URL':ConfigEngine().manifold_url(),
86 # XXX It's only to test the association of pi and esilva@uff.br
87 if request.session["eppn"] == 'esilva@uff.br':
88 username = 'rezende@ufrj'
89 password = 'fibre2014'
91 # If the user is not esilva@uff.br, so run the normal authentication
93 username = request.session["mail"]
94 # XXX this is ugly. We generate a simple password merging mail "fibre" and sn.
95 password = request.session["mail"] + "fibre" + request.session["sn"]
97 # If we have " we remove
98 username = username.replace('"','').strip()
99 password = password.replace('"','').strip()
101 # pass request within the token, so manifold session key can be attached to the request session.
102 token = {'username': username, 'password': password, 'request': request}
104 # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
105 # . a django User in case of success
106 # . or None if the backend could be reached but the authentication failed
107 auth_result = authenticate(token=token)
109 # XXX Error - We need a toke, not send parameters directly!
110 #auth_result = authenticate(username='rezende@ufrj', password='fibre2014', request=request)
111 print "Auth Result CAFe"
112 print type(auth_result)
113 # high-level errors, like connection refused or the like
115 if isinstance (auth_result, ManifoldResult):
116 manifoldresult = auth_result
117 #htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://200.130.15.182/login\" />"
118 htm = "not authenticated"
119 return HttpResponse (htm)
120 # user was authenticated at the backend
121 elif auth_result is not None:
124 # Verifying if user is active to logging in
129 #if request.user.is_authenticated():
130 # env['person'] = username
131 # env['username'] = username
133 # env['person'] = None
135 htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://200.130.15.182/login\" />"
136 #return HttpResponseRedirect ('/login-ok')
137 return HttpResponse (htm)
138 #return render_to_response(self.template,env, context_instance=RequestContext(request))
140 # Today all CAFe accounts are actived
141 htm = "Your account is not active, please contact the site admin."
142 return HttpResponse (htm)
145 # Creating the user at manifold, myslice and sfa
146 # XXX It's the first of CAFe user in MySlice!
148 # Get the username and password
149 user_params = { 'email': username, 'password': password }
152 # set the auth_type = managed
153 user_request['auth_type'] = 'managed'
155 # XXX Generating the key pairs for CAFe user
156 from Crypto.PublicKey import RSA
157 private = RSA.generate(1024)
159 # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
160 # Example: public_key = 'ssh-rsa AAAAB3...'
161 user_request['private_key'] = private.exportKey()
162 user_request['public_key'] = private.publickey().exportKey(format='OpenSSH')
164 # Generate a HRN different for all users (plus random int)
165 # Getting the username
166 splitmail = username.split("@")[0]
167 # Getting the organization. The same of authority
169 org = username.split('@')[1]
170 o = org.split('.')[-2]
171 user = splitmail.replace('"','').strip()
172 # Finally creating the HRN
173 hrn = "fibre." + o + "." + user + str(randint(1,100000))
175 user_request['user_hrn'] = hrn
177 # Others fields we can get from CAFe database
178 user_request['first_name'] = request.session['cn']
179 user_request['last_name'] = request.session['sn']
180 # We need to put the user below its authority
181 user_request['authority_hrn'] = "fibre." + o
182 user_request['email'] = username
183 user_request['password'] = password
184 user_request['public_key'] = user_request['public_key']
185 user_request['private_key'] = user_request['private_key']
187 # Verify in django if user exist
188 if PendingUser.objects.filter(email__iexact = user_request['email']):
189 htm = "Erro - User with same email from CAFe exists in Django"
190 # verify in manifold and SFA if user exist
191 user_query = Query().get('local:user').select('user_id','email')
192 user_details = execute_admin_query(request, user_query)
193 for user_detail in user_details:
194 if user_detail['email'] == user_request['email']:
195 htm = "Erro - user exist in SFA Registry"
197 if user_detail['user_hrn'] == user_request['user_hrn']:
198 htm = "Erro - user with the same hrn in SFA Registry"
202 # first we create a uer with pending flag
203 create_pending_user(user_request, user_request, user_detail)
204 # after we enable this user and put in SFA
205 create_user(user_request, user_request)
207 htm = "Now your CAFe user is associated with a MySlice account - Please return to the home and log in CAFe again."
208 return HttpResponse(htm)