Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into fibre
[myslice.git] / plugins / cafe-1.0 / edelberto-140314.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, execute_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 unfold.loginrequired   import FreeAccessView
28
29 from portal.models      import  PendingUser
30
31 from django.views.generic import View
32 from django.core.context_processors import csrf
33 from django.contrib.auth import authenticate, login, logout
34 from django.template import RequestContext
35 from django.shortcuts import render_to_response
36
37 from manifoldapi.manifoldresult import ManifoldResult
38 from ui.topmenu import topmenu_items, the_user
39 from myslice.configengine import ConfigEngine
40
41 #from django.http import HttpResponse HttpResponseRedirect
42 from django.http import HttpResponse
43 #from django.http import HttpResponseRedirect
44 #from django.template import  RequestContext
45 from django.contrib.sessions.backends.db import SessionStore
46
47 def index(request):
48 #class EdelbertoView (View):
49
50 # XXX We use cookie!
51 # Test cookie support
52     if request.session.test_cookie_worked():
53     #if session.test_cookie_worked():
54         return HttpResponse("Please enable cookies and try again.")
55         #return
56         print "Please enable cookies and try again."
57     else:
58         request.session['cn'] = request.META['Shib-inetOrgPerson-cn']
59         request.session['sn'] = request.META['Shib-inetOrgPerson-sn']
60         request.session['mail'] = request.META['Shib-inetOrgPerson-mail']
61         request.session['eppn'] = request.META['Shib-eduPerson-eduPersonPrincipalName']
62         #request.session['aff'] = request.META['Shib-brEduPerson-brEduAffiliationType']
63         request.session['aff'] = request.META['Shib-eduPerson-eduPersonAffiliation']
64         request.session['shib'] = request.META['Shib-Session-ID']
65
66         if 'mail' in request.session.keys():
67              print "Cookie: OK -> Content: cn:" + request.session["cn"] + " sn " +request.session["sn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]
68              #ip += "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]  + "</body></html>"
69         else:
70              print "Cookie: nothing/clear"
71              #ip += "Cookie: nothing/clear </body></html>"
72
73    # return HttpResponse(ip)
74
75     # expose this so we can mention the backend URL on the welcome page
76     def default_env (self):
77         return {
78                  'MANIFOLD_URL':ConfigEngine().manifold_url(),
79                  }
80
81     # expose this so we can mention the backend URL on the welcome page
82     #def default_env (self):
83     #    config=Config()
84     #    return {
85     #            'MANIFOLD_URL':ConfigEngine().manifold_url(),
86     #            #'MANIFOLD_URL':config.manifold_url(),
87     #             }
88
89     # XXX It's only to test the association of pi and esilva@uff.br
90     if request.session["eppn"] == 'esilva@uff.br':
91         username = 'rezende@ufrj'
92         password = 'fibre2014'
93         print "eppn OK"
94     else:
95         username = request.session["mail"]
96         # this is ugly. We generate a simple password merging mail "fibre" and sn.
97         password = request.session["mail"] + "fibre" + request.session["sn"]
98
99         # If we have " we remove
100         username = username.replace('"','').strip()
101         password = password.replace('"','').strip()
102
103     # pass request within the token, so manifold session key can be attached to the request session.
104     #token = {'username': username, 'password': password, 'request': request}
105     #token = {'username': username, 'password': password}
106
107     # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
108     # . a django User in case of success
109     # . or None if the backend could be reached but the authentication failed
110     print "token CAFe"
111     #print token
112     #auth_result = authenticate(token=token)
113     #auth_result = authenticate(username=username, password=password)
114     auth_result = authenticate(username='rezende@ufrj', password='fibre2014', request=request)
115     print "Auth Result CAFe"
116     print auth_result
117     # high-level errors, like connection refused or the like
118
119     if isinstance (auth_result, ManifoldResult):
120         manifoldresult = auth_result
121         print ManifoldResult
122         print manifoldresult
123         #htm =  "<meta http-equiv=\"refresh\" content=\"0; url=https://200.130.15.182/login\" />"
124         htm = "not authenticated"
125         return HttpResponse (htm)
126         # user was authenticated at the backend
127     elif auth_result is not None:
128         user=auth_result
129
130         # Verifying if user is active to logging in
131         if user.is_active:
132             print "LOGGING IN"
133             login(request, user)
134             
135             #if request.user.is_authenticated():
136             #    env['person'] = username
137             #    env['username'] = username
138             #else:
139             #    env['person'] = None
140
141             htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://200.130.15.182/login\" />"
142             #return HttpResponseRedirect ('/login-ok')
143             return HttpResponse (htm)
144         else:
145             # Today all CAFe accounts are actived
146             htm = "Your account is not active, please contact the site admin."
147             return HttpResponse (htm)
148
149     # otherwise
150     # Creating the user at manifold, myslice and sfa
151     else:
152         user_params = { 'email': username, 'password': password }
153         user_request = {}
154
155         user_request['auth_type'] = 'managed'
156
157         # XXX Common code, dependency ?
158         from Crypto.PublicKey import RSA
159         private = RSA.generate(1024)
160
161         # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
162         # Example: public_key = 'ssh-rsa AAAAB3...'
163         user_request['private_key'] = private.exportKey()
164         user_request['public_key']  = private.publickey().exportKey(format='OpenSSH')
165
166         splitmail = username.split("@")[0]
167         user = splitmail.replace('"','').strip()
168         hrn = "fibre." + user + str(randint(1,100000))
169
170         user_request['user_hrn'] = hrn
171
172         user_request['first_name'] = request.session['cn']
173         user_request['last_name'] = request.session['sn']
174         user_request['authority_hrn'] = "fibre"
175         user_request['email'] = username
176         user_request['password'] = password
177         user_request['public_key'] = user_request['public_key']
178         user_request['private_key'] = user_request['private_key']
179
180         # Verify in django
181         if PendingUser.objects.filter(email__iexact = user_request['email']):
182             htm = "Erro - User with same email from CAFe exists in Django"
183         # verify in manifol
184         user_query = Query().get('local:user').select('user_id','email')
185         user_details = execute_admin_query(request, user_query)
186         for user_detail in user_details:
187             if user_detail['email'] == user_request['email']:
188                 htm = "Erro - user exist in SFA Registry"
189             try:
190                 if user_detail['user_hrn'] == user_request['user_hrn']:
191                     htm =  "Erro - user with the same hrn in SFA Registry"
192             except:
193                 continue
194
195
196         #create_pending_user(user_request, user_request, user_detail)
197
198         htm = "Now your CAFe user is associated with a MySlice account - Please login-ok in CAFe again."
199         return HttpResponse(htm)
200        # return HttpResponse(htm)
201
202    # login-ok sets state="Welcome to MySlice" in urls.py
203     def get (self, request, state=None):
204         env = self.default_env()
205         env['username']=the_user(request)
206         env['topmenu_items'] = topmenu_items(None, request)
207         if state: env['state'] = state
208         elif not env['username']: env['state'] = "Please sign in"
209         return HttpResponseRedirect ('/login-ok')
210     #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
211