cafe plugin
[unfold.git] / plugins / cafe-1.0 / others / edelberto.py.101113
1 #!/usr/bin/env python
2
3 #Edelberto from manifoldauth
4 import os,sys
5 import subprocess
6 import shlex
7 import getpass
8 from hashlib import md5
9 import time
10 from random import Random
11 import crypt
12
13 #from manifold.manifold.core.router import Router
14 from manifold.core.query import Query
15 # add user to manifold
16
17 from django.views.generic import View
18 from django.core.context_processors import csrf
19 #from django.http import HttpResponseRedirect
20 from django.contrib.auth import authenticate, login, logout
21 from django.template import RequestContext
22 from django.shortcuts import render_to_response
23
24 from manifold.manifoldresult import ManifoldResult
25 from ui.topmenu import topmenu_items, the_user
26 from myslice.config import Config
27
28 #from django.http import HttpResponse HttpResponseRedirect
29 from django.http import HttpResponse
30 #from django.http import HttpResponseRedirect
31 #from django.template import  RequestContext
32 from django.contrib.sessions.backends.db import SessionStore
33
34 def index(request):
35 #class EdelbertoView (View):
36
37 # =================== Old code - to validate =================
38     '''
39     ip = "<html><body>" 
40     ip += "cn: " +  request.META['Shib-inetOrgPerson-cn'] + "</br>"
41     ip += "sn: " +  request.META['Shib-inetOrgPerson-sn'] + "</br>"
42     ip += "eppn: " + request.META['Shib-eduPerson-eduPersonPrincipalName'] + "</br>"
43     ip += "mail: " + request.META['Shib-inetOrgPerson-mail'] + "</br>"
44     ip += "Affiliation br: " + request.META['Shib-brEduPerson-brEduAffiliationType'] + "</br>"
45     ip += "Affiliation edu: " + request.META['Shib-eduPerson-eduPersonAffiliation'] + "</br>"
46     ip += "Auth-Method: " + request.META['Shib-Authentication-Method'] + "</br>"
47     ip += "Identity Provider: " + request.META['Shib-Identity-Provider'] + "</br>"
48     ip += "Application ID: " + request.META['Shib-Application-ID'] + "</br>"
49     ip += "Session ID: " + request.META['Shib-Session-ID'] + "</br>"
50     '''
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['mail'] = request.META['Shib-inetOrgPerson-mail']
60         request.session['eppn'] = request.META['Shib-eduPerson-eduPersonPrincipalName']
61         #request.session['aff'] = request.META['Shib-brEduPerson-brEduAffiliationType']
62         request.session['aff'] = request.META['Shib-eduPerson-eduPersonAffiliation']
63         request.session['shib'] = request.META['Shib-Session-ID']
64
65         if 'mail' in request.session.keys():
66              print "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]
67              #ip += "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]  + "</body></html>"
68         else:
69              print "Cookie: nothing/clear"
70              #ip += "Cookie: nothing/clear </body></html>"
71     
72    # return HttpResponse(ip)
73    
74
75     # expose this so we can mention the backend URL on the welcome page
76     def default_env (self):
77         config=Config()
78         return { 
79                  'MANIFOLD_URL':config.manifold_url(),
80                  }
81
82     #def post (self,request):
83     #    env = self.default_env()
84         #username = request.POST.get('username')
85         #password = request.POST.get('password')
86     if 'aff' in request.session.keys():
87         aff = request.session["aff"]
88         if aff == "student":
89             if request.session["eppn"] == 'esilva@uff.br':
90                 username = 'admin'
91                 password = 'fibre2013'
92             else:
93                  username = request.session["mail"]
94                  password = request.session["mail"] + "fibre2013"
95     
96                 # pass request within the token, so manifold session key can be attached to the request session.
97             token = {'username': username, 'password': password, 'request': request}    
98
99                 # our authenticate function returns either
100                     # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
101                     # . a django User in case of success
102                     # . or None if the backend could be reached but the authentication failed
103             auth_result = authenticate(token=token)
104                     # high-level errors, like connection refused or the like
105             if isinstance (auth_result, ManifoldResult):
106                 manifoldresult = auth_result
107                     # let's use ManifoldResult.__repr__
108                 env['state']="%s"%manifoldresult
109                 return render_to_response('home-view.html',env, context_instance=RequestContext(request))
110                     # user was authenticated at the backend
111             elif auth_result is not None:
112                 user=auth_result
113                 if user.is_active:
114                     print "LOGGING IN"
115                     login(request, user)
116                     htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-php.cafeexpresso.rnp.br/login-ok\" />"
117                     #return HttpResponseRedirect ('/login-ok')
118                     return HttpResponse (htm)
119                 else:
120                     env['state'] = "Your account is not active, please contact the site admin."
121                     return render_to_response('home-view.html',env, context_instance=RequestContext(request))
122                 # otherwise
123             else:
124                 '''
125                 magic = "$1$"
126                 password = password
127                 # Generate a somewhat unique 8 character salt string
128                 salt = str(time.time()) + str(Random().random())
129                 salt = md5(salt).hexdigest()[:8]
130
131                 if len(password) <= len(magic) or password[0:len(magic)] != magic:
132                     password = crypt.crypt(password.encode('latin1'), magic + salt + "$")
133
134                 user_params = {
135                     'email': username,
136                     'password': password
137                 }
138                 query = Query(action='create', object='local:user', params=user_params)
139
140
141                     # Instantiate a TopHat router
142                 with Router() as router:
143                     router.forward(query)
144                 '''
145                 #myArgs=[username,password]
146                 #os.spawnlp(os.P_WAIT,'/tmp/adduser.py', username, password, '/bin/bash/')
147                 command = '/var/www/manifold/manifold/bin/adduser.py ' + username + ' ' + password
148                 #command = 'ls -la'
149                 args = shlex.split(command)
150                 p = subprocess.Popen(args, stdin=subprocess.PIPE).communicate()[0]
151                 print command
152                 print args
153                 print p
154                 #env['state'] = "Now your CAFe user is associated to your MySlice account - Please logging in CAFe again."
155                 #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
156                 html = "Now its CAFe user is associated with a MySlice account - Please login in CAFe again."
157                 return HttpResponse(html)
158
159         else:
160             #env['state'] = "Your affiliation (" + request.session["aff"] + ") at CAFe is not accepted."
161             html = "Your CAFe affiliation (" + request.session["aff"] + ") is not accepted. <br> Only \"student\" affiliation."
162             return HttpResponse(html)
163             #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
164             
165
166             # login-ok sets state="Welcome to MySlice" in urls.py
167         def get (self, request, state=None):
168             env = self.default_env()
169             env['username']=the_user(request)
170             env['topmenu_items'] = topmenu_items(None, request)
171             if state: env['state'] = state
172             elif not env['username']: env['state'] = "Please sign in"
173             return HttpResponseRedirect ('/login-ok')
174         #return render_to_response('home-view.html',env, context_instance=RequestContext(request))