19be099fdd4278e61311ec7bcdb47a78e44d3fe4
[unfold.git] / plugins / cafe-1.0 / edelberto.py
1 #!/usr/bin/env python
2
3
4 # XXX We need to clean it!!
5 from portal.models              import PendingUser
6
7 #Edelberto from manifoldauth
8 import os,sys
9 import subprocess
10 import shlex
11 import getpass
12 from hashlib import md5
13 import time
14 from random import randint
15 import crypt
16
17 import re
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
26
27 from unfold.loginrequired   import FreeAccessView
28
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
34
35 from manifoldapi.manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
36 from ui.topmenu import topmenu_items, the_user
37 from myslice.configengine import ConfigEngine
38
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
44
45 from portal.homeview import HomeView
46
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
52         print "EdelbertoView"
53     
54     # XXX We use cookie!
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         # Cookies test finish
77        # return HttpResponse(ip)
78     
79         # expose this so we can mention the backend URL on the welcome page
80         def default_env (self):
81             return {
82                      'MANIFOLD_URL':ConfigEngine().manifold_url(),
83                      }
84     
85     
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'
90             print "eppn OK"
91         # If the user is not esilva@uff.br, so run the normal authentication
92         else:
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"]
96     
97             # If we have " we remove
98             username = username.replace('"','').strip()
99             password = password.replace('"','').strip()
100     
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}
103     
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)
108         
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
114     
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:
122             user=auth_result
123     
124             # Verifying if user is active to logging in
125             if user.is_active:
126                 print "LOGGING IN"
127                 login(request, user)
128                 
129                 #if request.user.is_authenticated():
130                 #    env['person'] = username
131                 #    env['username'] = username
132                 #else:
133                 #    env['person'] = None
134     
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))
139             else:
140                 # Today all CAFe accounts are actived
141                 htm = "Your account is not active, please contact the site admin."
142                 return HttpResponse (htm)
143     
144         # otherwise
145         # Creating the user at manifold, myslice and sfa
146         # XXX It's the first of CAFe user in MySlice!
147         else:
148             # Get the username and password
149             user_params = { 'email': username, 'password': password }
150             user_request = {}
151     
152             # set the auth_type = managed
153             user_request['auth_type'] = 'managed'
154     
155             # XXX Generating the key pairs for CAFe user
156             from Crypto.PublicKey import RSA
157             private = RSA.generate(1024)
158     
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')
163     
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 
168             # testbed name
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))
174     
175             user_request['user_hrn'] = hrn
176     
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']
186     
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"
196                 try:
197                     if user_detail['user_hrn'] == user_request['user_hrn']:
198                         htm =  "Erro - user with the same hrn in SFA Registry"
199                 except:
200                     continue
201     
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)
206     
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)