a3ec0b42667c89071d5c2466feebcd6081230a70
[myslice.git] / plugins / cafe-1.0 / edelberto-120314.py
1 #!/usr/bin/env python
2
3 from portal.models              import PendingUser
4 #from portal.actions             import create_pending_user
5 # Edelberto - LDAP
6 from portal.actions             import create_pending_user, ldap_create_user
7
8 #Edelberto from manifoldauth
9 import os,sys
10 import subprocess
11 import shlex
12 import getpass
13 from hashlib import md5
14 import time
15 from random import randint
16 import crypt
17
18 import re
19 #from manifold.manifold.core.router import Router
20 from manifold.core.query                import Query
21 from manifoldapi.manifoldapi               import execute_admin_query
22 #from portal.actions                     import manifold_add_user, manifold_add_account, manifold_update_account
23 from portal.actions                     import manifold_add_account, manifold_add_reference_user_accounts, sfa_create_user, create_pending_user
24 from manifold.core.query import Query
25 # add user to manifold
26
27 from portal.models      import  PendingUser
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 manifold.manifoldresult import ManifoldResult
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 def index(request):
46 #class EdelbertoView (View):
47
48 # XXX We use cookie!
49 # Test cookie support
50     if request.session.test_cookie_worked():
51     #if session.test_cookie_worked():
52         return HttpResponse("Please enable cookies and try again.")
53         #return
54         print "Please enable cookies and try again."
55     else:
56         request.session['cn'] = request.META['Shib-inetOrgPerson-cn']
57         request.session['sn'] = request.META['Shib-inetOrgPerson-sn']
58         request.session['mail'] = request.META['Shib-inetOrgPerson-mail']
59         request.session['eppn'] = request.META['Shib-eduPerson-eduPersonPrincipalName']
60         #request.session['aff'] = request.META['Shib-brEduPerson-brEduAffiliationType']
61         request.session['aff'] = request.META['Shib-eduPerson-eduPersonAffiliation']
62         request.session['shib'] = request.META['Shib-Session-ID']
63
64         if 'mail' in request.session.keys():
65              print "Cookie: OK -> Content: cn:" + request.session["cn"] + " sn " +request.session["sn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]
66              #ip += "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]  + "</body></html>"
67         else:
68              print "Cookie: nothing/clear"
69              #ip += "Cookie: nothing/clear </body></html>"
70     
71    # return HttpResponse(ip)
72    
73
74     # XXX It's only to test the association of pi and esilva@uff.br
75         if request.session["eppn"] == 'esilva@uff.br':
76             username = 'rezende@ufrj'
77             password = 'fibre2014'
78             # pass request within the token, so manifold session key can be attached to the request session.
79             token = {'username': username, 'password': password, 'request': request}    
80         # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
81         # For all users - Verifying if he exists in MySlice/Manifold
82         else:
83             username = request.session["mail"]
84             # this is ugly. We generate a simple password merging mail "fibre" and sn.
85             password = request.session["mail"] + "fibre" + request.session["sn"]
86          
87             # If we have " we remove
88             username = username.replace('"','').strip()
89             password = password.replace('"','').strip()
90         
91             # pass request within the token, so manifold session key can be attached to the request session.
92             token = {'username': username, 'password': password, 'request': request}    
93         # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
94         # . a django User in case of success
95         # . or None if the backend could be reached but the authentication failed
96         auth_result = authenticate(token=token)
97         print auth_result
98         print token
99         # high-level errors, like connection refused or the like
100         
101         if isinstance (auth_result, ManifoldResult):
102             manifoldresult = auth_result
103             htm =  "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-fibre.cafeexpresso.rnp.br/login-ok\" />"
104             return HttpResponse (htm)    
105             # user was authenticated at the backend
106         elif auth_result is not None:
107             user=auth_result
108         
109             # Verifying if user is active to logging in
110             if user.is_active:
111                 print "LOGGING IN"
112                 login(request, user)
113                 htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-fibre.cafeexpresso.rnp.br/login-ok\" />"
114                 #return HttpResponseRedirect ('/login-ok')
115                 return HttpResponse (htm)
116             else:
117                 # Today all CAFe accounts are actived
118                 htm = "Your account is not active, please contact the site admin."
119                 return HttpResponse (htm)
120         
121
122         # otherwise
123         # Creating the user at manifold, myslice and sfa
124         else:
125             user_params = { 'email': username, 'password': password }
126             user_request = {}
127
128             user_request['auth_type'] = 'managed'
129
130             # XXX Common code, dependency ?
131             from Crypto.PublicKey import RSA
132             private = RSA.generate(1024)
133
134             # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
135             # Example: public_key = 'ssh-rsa AAAAB3...'
136             user_request['private_key'] = private.exportKey()
137             user_request['public_key']  = private.publickey().exportKey(format='OpenSSH')
138             
139             splitmail = username.split("@")[0]
140             user = splitmail.replace('"','').strip()
141             hrn = "fibre." + user + str(randint(1,100000))
142
143             user_request['user_hrn'] = hrn            
144             
145             user_request['first_name'] = request.session['cn']
146             user_request['last_name'] = request.session['sn']
147             user_request['authority_hrn'] = "fibre"
148             user_request['email'] = username
149             user_request['password'] = password
150             user_request['public_key'] = user_request['public_key']
151             user_request['private_key'] = user_request['private_key']
152            
153             # Verify in django
154             if PendingUser.objects.filter(email__iexact = user_request['email']):
155                 htm = "Erro - User with same email from CAFe exists in Django"
156             # verify in manifol
157             user_query = Query().get('local:user').select('user_id','email')
158             user_details = execute_admin_query(request, user_query)
159             for user_detail in user_details:
160                 if user_detail['email'] == user_request['email']:
161                     htm = "Erro - user exist in SFA Registry"
162                 try:
163                     if user_detail['user_hrn'] == user_request['user_hrn']:
164                         htm =  "Erro - user with the same hrn in SFA Registry"
165                 except: 
166                     continue
167         
168             
169             create_pending_user(user_request, user_request, user_detail)
170
171             return HttpResponse(htm)
172         return HttpResponse(htm)