cafe plugin
authorLoic & Edelberto <loic.baron@lip6.fr>
Thu, 13 Mar 2014 13:27:42 +0000 (10:27 -0300)
committerLoic & Edelberto <loic.baron@lip6.fr>
Thu, 13 Mar 2014 13:27:42 +0000 (10:27 -0300)
13 files changed:
plugins/cafe [new symlink]
plugins/cafe-1.0/__init__.py [new file with mode: 0644]
plugins/cafe-1.0/cafe [new symlink]
plugins/cafe-1.0/cafe.zip [new file with mode: 0644]
plugins/cafe-1.0/edelberto-120314.py [new file with mode: 0644]
plugins/cafe-1.0/edelberto.py [new file with mode: 0644]
plugins/cafe-1.0/manifoldbackend.py [new file with mode: 0644]
plugins/cafe-1.0/others/edelberto.py-noupdateaccountONLY [new file with mode: 0644]
plugins/cafe-1.0/others/edelberto.py.101113 [new file with mode: 0644]
plugins/cafe-1.0/others/edelberto_context.py [new file with mode: 0644]
plugins/cafe-1.0/others/manifoldbackend.py [new file with mode: 0644]
plugins/cafe-1.0/others/sub.py [new file with mode: 0755]
plugins/cafe-1.0/sub.py [new file with mode: 0755]

diff --git a/plugins/cafe b/plugins/cafe
new file mode 120000 (symlink)
index 0000000..818c1c6
--- /dev/null
@@ -0,0 +1 @@
+cafe-1.0/
\ No newline at end of file
diff --git a/plugins/cafe-1.0/__init__.py b/plugins/cafe-1.0/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/plugins/cafe-1.0/cafe b/plugins/cafe-1.0/cafe
new file mode 120000 (symlink)
index 0000000..47de4c7
--- /dev/null
@@ -0,0 +1 @@
+cafe/
\ No newline at end of file
diff --git a/plugins/cafe-1.0/cafe.zip b/plugins/cafe-1.0/cafe.zip
new file mode 100644 (file)
index 0000000..b58f144
Binary files /dev/null and b/plugins/cafe-1.0/cafe.zip differ
diff --git a/plugins/cafe-1.0/edelberto-120314.py b/plugins/cafe-1.0/edelberto-120314.py
new file mode 100644 (file)
index 0000000..bbecd5c
--- /dev/null
@@ -0,0 +1,218 @@
+#!/usr/bin/env python
+
+#Edelberto from manifoldauth
+import os,sys
+import subprocess
+import shlex
+import getpass
+from hashlib import md5
+import time
+from random import Random
+import crypt
+
+import re
+#from manifold.manifold.core.router import Router
+from manifold.core.query                import Query
+from manifoldapi.manifoldapi               import execute_admin_query
+from portal.actions                     import manifold_add_user, manifold_add_account, manifold_update_account
+from manifold.core.query import Query
+# add user to manifold
+
+from django.views.generic import View
+from django.core.context_processors import csrf
+#from django.http import HttpResponseRedirect
+from django.contrib.auth import authenticate, login, logout
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+
+from manifold.manifoldresult import ManifoldResult
+from ui.topmenu import topmenu_items, the_user
+from myslice.configengine import ConfigEngine
+
+#from django.http import HttpResponse HttpResponseRedirect
+from django.http import HttpResponse
+#from django.http import HttpResponseRedirect
+#from django.template import  RequestContext
+from django.contrib.sessions.backends.db import SessionStore
+
+def index(request):
+#class EdelbertoView (View):
+
+# =================== Old code - to validate =================
+    '''
+    ip = "<html><body>" 
+    ip += "cn: " +  request.META['Shib-inetOrgPerson-cn'] + "</br>"
+    ip += "sn: " +  request.META['Shib-inetOrgPerson-sn'] + "</br>"
+    ip += "eppn: " + request.META['Shib-eduPerson-eduPersonPrincipalName'] + "</br>"
+    ip += "mail: " + request.META['Shib-inetOrgPerson-mail'] + "</br>"
+    ip += "Affiliation br: " + request.META['Shib-brEduPerson-brEduAffiliationType'] + "</br>"
+    ip += "Affiliation edu: " + request.META['Shib-eduPerson-eduPersonAffiliation'] + "</br>"
+    ip += "Auth-Method: " + request.META['Shib-Authentication-Method'] + "</br>"
+    ip += "Identity Provider: " + request.META['Shib-Identity-Provider'] + "</br>"
+    ip += "Application ID: " + request.META['Shib-Application-ID'] + "</br>"
+    ip += "Session ID: " + request.META['Shib-Session-ID'] + "</br>"
+    '''
+# Test cookie support
+    if request.session.test_cookie_worked():
+    #if session.test_cookie_worked():
+        return HttpResponse("Please enable cookies and try again.")
+        #return
+        print "Please enable cookies and try again."
+    else:
+        request.session['cn'] = request.META['Shib-inetOrgPerson-cn']
+        request.session['sn'] = request.META['Shib-inetOrgPerson-sn']
+        request.session['mail'] = request.META['Shib-inetOrgPerson-mail']
+        request.session['eppn'] = request.META['Shib-eduPerson-eduPersonPrincipalName']
+        #request.session['aff'] = request.META['Shib-brEduPerson-brEduAffiliationType']
+        request.session['aff'] = request.META['Shib-eduPerson-eduPersonAffiliation']
+       request.session['shib'] = request.META['Shib-Session-ID']
+
+        if 'mail' in request.session.keys():
+             print "Cookie: OK -> Content: cn:" + request.session["cn"] + " sn " +request.session["sn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]
+             #ip += "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]  + "</body></html>"
+        else:
+             print "Cookie: nothing/clear"
+             #ip += "Cookie: nothing/clear </body></html>"
+    
+   # return HttpResponse(ip)
+   
+
+    # expose this so we can mention the backend URL on the welcome page
+    def default_env (self):
+        config=Config()
+        return { 
+                 'MANIFOLD_URL':config.manifold_url(),
+                 }
+
+    #def post (self,request):
+    #    env = self.default_env()
+        #username = request.POST.get('username')
+        #password = request.POST.get('password')
+    # if we use ABAC based on 'aff'
+    #if 'aff' in request.session.keys():
+    aff = request.session["aff"]
+    # if we use ABAC - based on 'aff'
+    #if aff == "student":
+    # XXX It's only to test the association of admin and esilva@uff.br
+    if request.session["eppn"] == 'esilva@uff.br':
+        username = 'admin'
+        password = 'admin'
+    # For all users
+    else:
+        username = request.session["mail"]
+ # this is ugly. We generate a simple password with merge of mail and a string.
+        password = request.session["mail"] + "fibre2013"
+     
+        username = username.replace('"','').strip()
+        password = password.replace('"','').strip()
+    # pass request within the token, so manifold session key can be attached to the request session.
+    token = {'username': username, 'password': password, 'request': request}    
+
+        # our authenticate function returns either
+        # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
+        # . a django User in case of success
+        # . or None if the backend could be reached but the authentication failed
+    auth_result = authenticate(token=token)
+        # high-level errors, like connection refused or the like
+    
+    if isinstance (auth_result, ManifoldResult):
+        manifoldresult = auth_result
+        # let's use ManifoldResult.__repr__
+        '''
+        env['state']="%s"%manifoldresult
+        return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+    '''
+        htm =  "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-fibre.cafeexpresso.rnp.br/login-ok\" />"
+        return HttpResponse (htm)    
+        # user was authenticated at the backend
+    elif auth_result is not None:
+        user=auth_result
+    
+    if user.is_active:
+        print "LOGGING IN"
+        login(request, user)
+        htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-fibre.cafeexpresso.rnp.br/login-ok\" />"
+            #return HttpResponseRedirect ('/login-ok')
+        return HttpResponse (htm)
+    else:
+        env['state'] = "Your account is not active, please contact the site admin."
+        return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+    # otherwise
+    else:
+    '''
+        magic = "$1$"
+        password = password
+        # Generate a somewhat unique 8 character salt string
+        salt = str(time.time()) + str(Random().random())
+        salt = md5(salt).hexdigest()[:8]
+
+        if len(password) <= len(magic) or password[0:len(magic)] != magic:
+        password = crypt.crypt(password.encode('latin1'), magic + salt + "$")
+
+        user_params = {
+            'email': username,
+        'password': password
+    }
+    query = Query(action='create', object='local:user', params=user_params)
+
+
+        # Instantiate a TopHat router
+    with Router() as router:
+        router.forward(query)
+    '''
+    #myArgs=[username,password]
+    #os.spawnlp(os.P_WAIT,'/tmp/adduser.py', username, password, '/bin/bash/'i)
+    #command = '/var/www/manifold/manifold/bin/adduser.py ' + username + ' ' + password
+    #command = 'ls -la'
+            #args = shlex.split(command)
+            #p = subprocess.Popen(args, stdin=subprocess.PIPE).communicate()[0]
+        #print command
+        #print args
+        #print p
+    #env['state'] = "Now your CAFe user is associated to your MySlice account - Please logging in CAFe again."
+    #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+    user_params = { 'email': username, 'password': password }
+    manifold_add_user(request,user_params)
+    
+    #query = Query().get('user').filter_by('email', '=', username).select('user_id')
+    #user = execute_admin_query(request,query)
+    #print "USER_ID:" + user
+    #user_id = user['user_id']
+    #user_id = user[0]
+    #print user_id
+    #splitmail = username.split("@")[0]
+    #user_params = { 'user': splitmail, 'platform': 'myslice' }
+    #user_params = { 'user_id': '2', 'platform_id': '2' }
+    #manifold_add_account(request,user_params)
+
+    # Ugly! Forcing the association of user and platform. This need to be automatic.   
+    splitmail = username.split("@")[0]
+    user = splitmail.replace('"','').strip()
+    hrn = "fibrebr.dummy." + user
+    user_hrn = '{ "user_hrn": "'+ hrn +'" }'
+    #user_params = { 'config': user_hrn, 'auth_type': 'managed' }
+    user_params2 = { 'user_id': '2', 'platform_id': '2', 'config': user_hrn, 'auth_type': 'managed' }
+    manifold_add_account(request,user_params2)
+
+    ##user_id = '3'
+    #manifold_update_account(request,user_params)
+    html = "Now your CAFe user is associated with a MySlice account - Please login in CAFe again."
+    return HttpResponse(html)
+
+     # If we use ABAC - based on 'aff'
+     #   else:
+        #   #env['state'] = "Your affiliation (" + request.session["aff"] + ") at CAFe is not accepted."
+        #   html = "Your CAFe affiliation (" + request.session["aff"] + ") is not accepted. <br> Only \"student\" affiliation."
+        #   return HttpResponse(html)
+           #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+           
+
+           # login-ok sets state="Welcome to MySlice" in urls.py
+       def get (self, request, state=None):
+           env = self.default_env()
+           env['username']=the_user(request)
+           env['topmenu_items'] = topmenu_items(None, request)
+           if state: env['state'] = state
+           elif not env['username']: env['state'] = "Please sign in"
+           return HttpResponseRedirect ('/login-ok')
+       #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
diff --git a/plugins/cafe-1.0/edelberto.py b/plugins/cafe-1.0/edelberto.py
new file mode 100644 (file)
index 0000000..a3ec0b4
--- /dev/null
@@ -0,0 +1,172 @@
+#!/usr/bin/env python
+
+from portal.models              import PendingUser
+#from portal.actions             import create_pending_user
+# Edelberto - LDAP
+from portal.actions             import create_pending_user, ldap_create_user
+
+#Edelberto from manifoldauth
+import os,sys
+import subprocess
+import shlex
+import getpass
+from hashlib import md5
+import time
+from random import randint
+import crypt
+
+import re
+#from manifold.manifold.core.router import Router
+from manifold.core.query                import Query
+from manifoldapi.manifoldapi               import execute_admin_query
+#from portal.actions                     import manifold_add_user, manifold_add_account, manifold_update_account
+from portal.actions                     import manifold_add_account, manifold_add_reference_user_accounts, sfa_create_user, create_pending_user
+from manifold.core.query import Query
+# add user to manifold
+
+from portal.models      import  PendingUser
+
+from django.views.generic import View
+from django.core.context_processors import csrf
+from django.contrib.auth import authenticate, login, logout
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+
+from manifold.manifoldresult import ManifoldResult
+from ui.topmenu import topmenu_items, the_user
+from myslice.configengine import ConfigEngine
+
+#from django.http import HttpResponse HttpResponseRedirect
+from django.http import HttpResponse
+#from django.http import HttpResponseRedirect
+#from django.template import  RequestContext
+from django.contrib.sessions.backends.db import SessionStore
+
+def index(request):
+#class EdelbertoView (View):
+
+# XXX We use cookie!
+# Test cookie support
+    if request.session.test_cookie_worked():
+    #if session.test_cookie_worked():
+        return HttpResponse("Please enable cookies and try again.")
+        #return
+        print "Please enable cookies and try again."
+    else:
+        request.session['cn'] = request.META['Shib-inetOrgPerson-cn']
+        request.session['sn'] = request.META['Shib-inetOrgPerson-sn']
+        request.session['mail'] = request.META['Shib-inetOrgPerson-mail']
+        request.session['eppn'] = request.META['Shib-eduPerson-eduPersonPrincipalName']
+        #request.session['aff'] = request.META['Shib-brEduPerson-brEduAffiliationType']
+        request.session['aff'] = request.META['Shib-eduPerson-eduPersonAffiliation']
+       request.session['shib'] = request.META['Shib-Session-ID']
+
+        if 'mail' in request.session.keys():
+             print "Cookie: OK -> Content: cn:" + request.session["cn"] + " sn " +request.session["sn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]
+             #ip += "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]  + "</body></html>"
+        else:
+             print "Cookie: nothing/clear"
+             #ip += "Cookie: nothing/clear </body></html>"
+    
+   # return HttpResponse(ip)
+   
+
+    # XXX It's only to test the association of pi and esilva@uff.br
+        if request.session["eppn"] == 'esilva@uff.br':
+            username = 'rezende@ufrj'
+            password = 'fibre2014'
+            # pass request within the token, so manifold session key can be attached to the request session.
+            token = {'username': username, 'password': password, 'request': request}    
+        # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
+        # For all users - Verifying if he exists in MySlice/Manifold
+        else:
+            username = request.session["mail"]
+            # this is ugly. We generate a simple password merging mail "fibre" and sn.
+            password = request.session["mail"] + "fibre" + request.session["sn"]
+         
+            # If we have " we remove
+            username = username.replace('"','').strip()
+            password = password.replace('"','').strip()
+        
+            # pass request within the token, so manifold session key can be attached to the request session.
+            token = {'username': username, 'password': password, 'request': request}    
+        # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
+        # . a django User in case of success
+        # . or None if the backend could be reached but the authentication failed
+        auth_result = authenticate(token=token)
+        print auth_result
+        print token
+        # high-level errors, like connection refused or the like
+        
+        if isinstance (auth_result, ManifoldResult):
+            manifoldresult = auth_result
+            htm =  "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-fibre.cafeexpresso.rnp.br/login-ok\" />"
+            return HttpResponse (htm)    
+            # user was authenticated at the backend
+        elif auth_result is not None:
+            user=auth_result
+        
+            # Verifying if user is active to logging in
+            if user.is_active:
+                print "LOGGING IN"
+                login(request, user)
+                htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-fibre.cafeexpresso.rnp.br/login-ok\" />"
+                #return HttpResponseRedirect ('/login-ok')
+                return HttpResponse (htm)
+            else:
+                # Today all CAFe accounts are actived
+                htm = "Your account is not active, please contact the site admin."
+                return HttpResponse (htm)
+        
+
+        # otherwise
+        # Creating the user at manifold, myslice and sfa
+        else:
+            user_params = { 'email': username, 'password': password }
+            user_request = {}
+
+            user_request['auth_type'] = 'managed'
+
+            # XXX Common code, dependency ?
+            from Crypto.PublicKey import RSA
+            private = RSA.generate(1024)
+
+            # Example: private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIC...'
+            # Example: public_key = 'ssh-rsa AAAAB3...'
+            user_request['private_key'] = private.exportKey()
+            user_request['public_key']  = private.publickey().exportKey(format='OpenSSH')
+            
+            splitmail = username.split("@")[0]
+            user = splitmail.replace('"','').strip()
+            hrn = "fibre." + user + str(randint(1,100000))
+
+            user_request['user_hrn'] = hrn            
+            
+            user_request['first_name'] = request.session['cn']
+            user_request['last_name'] = request.session['sn']
+            user_request['authority_hrn'] = "fibre"
+            user_request['email'] = username
+            user_request['password'] = password
+            user_request['public_key'] = user_request['public_key']
+            user_request['private_key'] = user_request['private_key']
+           
+            # Verify in django
+            if PendingUser.objects.filter(email__iexact = user_request['email']):
+                htm = "Erro - User with same email from CAFe exists in Django"
+            # verify in manifol
+            user_query = Query().get('local:user').select('user_id','email')
+            user_details = execute_admin_query(request, user_query)
+            for user_detail in user_details:
+                if user_detail['email'] == user_request['email']:
+                    htm = "Erro - user exist in SFA Registry"
+                try:
+                    if user_detail['user_hrn'] == user_request['user_hrn']:
+                        htm =  "Erro - user with the same hrn in SFA Registry"
+                except: 
+                    continue
+        
+            
+            create_pending_user(user_request, user_request, user_detail)
+
+            return HttpResponse(htm)
+        return HttpResponse(htm)
diff --git a/plugins/cafe-1.0/manifoldbackend.py b/plugins/cafe-1.0/manifoldbackend.py
new file mode 100644 (file)
index 0000000..14abb74
--- /dev/null
@@ -0,0 +1,76 @@
+import time
+
+from django.contrib.auth.models import User
+
+from manifold.manifoldapi import ManifoldAPI, ManifoldException, ManifoldResult
+from manifold.core.query        import Query
+
+# Name my backend 'ManifoldBackend'
+class ManifoldBackend:
+
+    # Create an authentication method
+    # This is called by the standard Django login procedure
+    def authenticate(self, token=None):
+        if not token:
+            return None
+
+        try:
+            username = token['username']
+            password = token['password']
+            request = token['request']
+
+            auth = {'AuthMethod': 'password', 'Username': username, 'AuthString': password}
+            api = ManifoldAPI(auth)
+            sessions_result = api.forward(Query.create('local:session').to_dict())
+            print "result"
+            sessions = sessions_result.ok_value()
+            print "ok"
+            if not sessions:
+                print "GetSession failed", sessions_result.error()
+                return
+            print "first", sessions
+            session = sessions[0]
+
+            # Change to session authentication
+            api.auth = {'AuthMethod': 'session', 'session': session['session']}
+            self.api = api
+
+            # Get account details
+            # the new API would expect Get('local:user') instead
+            persons_result = api.forward(Query.get('local:user').to_dict())
+            persons = persons_result.ok_value()
+            if not persons:
+                print "GetPersons failed",persons_result.error()
+                return
+            person = persons[0]
+            print "PERSON=", person
+
+            request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': session['expires']}
+        except ManifoldException, e:
+            print "Caught ManifoldException, returning corresponding ManifoldResult"
+            return e.manifold_result
+        except Exception, e:
+            print "E: manifoldbackend", e
+            import traceback
+            traceback.print_exc()
+            return None
+
+        try:
+            # Check if the user exists in Django's local database
+            user = User.objects.get(username=username)
+        except User.DoesNotExist:
+            # Create a user in Django's local database
+            user = User.objects.create_user(username, username, 'passworddoesntmatter')
+            user.first_name = "DUMMY_FIRST_NAME" #person['first_name']
+            user.last_name = "DUMMY LAST NAME" # person['last_name']
+            user.email = person['email']
+        return user
+
+    # Required for your backend to work properly - unchanged in most scenarios
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None
+
+
diff --git a/plugins/cafe-1.0/others/edelberto.py-noupdateaccountONLY b/plugins/cafe-1.0/others/edelberto.py-noupdateaccountONLY
new file mode 100644 (file)
index 0000000..67fe0f4
--- /dev/null
@@ -0,0 +1,197 @@
+#!/usr/bin/env python
+
+#Edelberto from manifoldauth
+import os,sys
+import subprocess
+import shlex
+import getpass
+from hashlib import md5
+import time
+from random import Random
+import crypt
+
+import re
+#from manifold.manifold.core.router import Router
+from manifold.core.query                import Query
+from manifold.manifoldapi               import execute_admin_query
+from portal.actions                     import manifold_add_user, manifold_add_account, manifold_update_account
+from manifold.core.query import Query
+# add user to manifold
+
+from django.views.generic import View
+from django.core.context_processors import csrf
+#from django.http import HttpResponseRedirect
+from django.contrib.auth import authenticate, login, logout
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+
+from manifold.manifoldresult import ManifoldResult
+from ui.topmenu import topmenu_items, the_user
+from myslice.config import Config
+
+#from django.http import HttpResponse HttpResponseRedirect
+from django.http import HttpResponse
+#from django.http import HttpResponseRedirect
+#from django.template import  RequestContext
+from django.contrib.sessions.backends.db import SessionStore
+
+def index(request):
+#class EdelbertoView (View):
+
+# =================== Old code - to validate =================
+    '''
+    ip = "<html><body>" 
+    ip += "cn: " +  request.META['Shib-inetOrgPerson-cn'] + "</br>"
+    ip += "sn: " +  request.META['Shib-inetOrgPerson-sn'] + "</br>"
+    ip += "eppn: " + request.META['Shib-eduPerson-eduPersonPrincipalName'] + "</br>"
+    ip += "mail: " + request.META['Shib-inetOrgPerson-mail'] + "</br>"
+    ip += "Affiliation br: " + request.META['Shib-brEduPerson-brEduAffiliationType'] + "</br>"
+    ip += "Affiliation edu: " + request.META['Shib-eduPerson-eduPersonAffiliation'] + "</br>"
+    ip += "Auth-Method: " + request.META['Shib-Authentication-Method'] + "</br>"
+    ip += "Identity Provider: " + request.META['Shib-Identity-Provider'] + "</br>"
+    ip += "Application ID: " + request.META['Shib-Application-ID'] + "</br>"
+    ip += "Session ID: " + request.META['Shib-Session-ID'] + "</br>"
+    '''
+# Test cookie support
+    if request.session.test_cookie_worked():
+    #if session.test_cookie_worked():
+        return HttpResponse("Please enable cookies and try again.")
+        #return
+        print "Please enable cookies and try again."
+    else:
+        request.session['cn'] = request.META['Shib-inetOrgPerson-cn']
+        request.session['mail'] = request.META['Shib-inetOrgPerson-mail']
+        request.session['eppn'] = request.META['Shib-eduPerson-eduPersonPrincipalName']
+        #request.session['aff'] = request.META['Shib-brEduPerson-brEduAffiliationType']
+        request.session['aff'] = request.META['Shib-eduPerson-eduPersonAffiliation']
+       request.session['shib'] = request.META['Shib-Session-ID']
+
+        if 'mail' in request.session.keys():
+             print "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]
+             #ip += "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]  + "</body></html>"
+        else:
+             print "Cookie: nothing/clear"
+             #ip += "Cookie: nothing/clear </body></html>"
+    
+   # return HttpResponse(ip)
+   
+
+    # expose this so we can mention the backend URL on the welcome page
+    def default_env (self):
+        config=Config()
+        return { 
+                 'MANIFOLD_URL':config.manifold_url(),
+                 }
+
+    #def post (self,request):
+    #    env = self.default_env()
+        #username = request.POST.get('username')
+        #password = request.POST.get('password')
+    if 'aff' in request.session.keys():
+        aff = request.session["aff"]
+        if aff == "student":
+            if request.session["eppn"] == 'esilva@uff.br':
+                username = 'admin'
+                password = 'fibre2013'
+            else:
+                 username = request.session["mail"]
+                 password = request.session["mail"] + "fibre2013"
+                username = username.replace('"','').strip()
+                password = password.replace('"','').strip()
+               # pass request within the token, so manifold session key can be attached to the request session.
+           token = {'username': username, 'password': password, 'request': request}    
+
+               # our authenticate function returns either
+                   # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
+                   # . a django User in case of success
+                   # . or None if the backend could be reached but the authentication failed
+           auth_result = authenticate(token=token)
+                   # high-level errors, like connection refused or the like
+           if isinstance (auth_result, ManifoldResult):
+               manifoldresult = auth_result
+                   # let's use ManifoldResult.__repr__
+               env['state']="%s"%manifoldresult
+               return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+                   # user was authenticated at the backend
+           elif auth_result is not None:
+               user=auth_result
+               if user.is_active:
+                   print "LOGGING IN"
+                   login(request, user)
+                   htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-php.cafeexpresso.rnp.br/login-ok\" />"
+                   #return HttpResponseRedirect ('/login-ok')
+                   return HttpResponse (htm)
+               else:
+                   env['state'] = "Your account is not active, please contact the site admin."
+                   return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+               # otherwise
+           else:
+               '''
+               magic = "$1$"
+               password = password
+               # Generate a somewhat unique 8 character salt string
+               salt = str(time.time()) + str(Random().random())
+               salt = md5(salt).hexdigest()[:8]
+
+               if len(password) <= len(magic) or password[0:len(magic)] != magic:
+                   password = crypt.crypt(password.encode('latin1'), magic + salt + "$")
+
+               user_params = {
+                   'email': username,
+                   'password': password
+               }
+               query = Query(action='create', object='local:user', params=user_params)
+
+
+                   # Instantiate a TopHat router
+               with Router() as router:
+                   router.forward(query)
+               '''
+               #myArgs=[username,password]
+               #os.spawnlp(os.P_WAIT,'/tmp/adduser.py', username, password, '/bin/bash/'i)
+               #command = '/var/www/manifold/manifold/bin/adduser.py ' + username + ' ' + password
+               #command = 'ls -la'
+                #args = shlex.split(command)
+                #p = subprocess.Popen(args, stdin=subprocess.PIPE).communicate()[0]
+               #print command
+               #print args
+               #print p
+               #env['state'] = "Now your CAFe user is associated to your MySlice account - Please logging in CAFe again."
+               #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+               user_params = { 'email': username, 'password': password }
+               manifold_add_user(request,user_params)
+               
+               #query = Query().get('user').filter_by('email', '=', username).select('user_id')
+               #user = execute_admin_query(request,query)
+               #print "USER_ID:" + user
+               #user_id = user['user_id']
+               #user_id = user[0]
+               #print user_id
+               #splitmail = username.split("@")[0]
+               #user_params = { 'user': splitmail, 'platform': 'myslice' }
+               user_params = { 'user_id': '3', 'platform_id': '2' }
+               manifold_add_account(request,user_params)
+       
+               splitmail = username.split("@")[0]
+               user_hrn = '{"user_hrn": "fibrebr.dummy."'+ splitmail + '"}'
+               user_params = { 'config': user_hrn, 'auth_type':'managed'}
+               manifold_update_account(request,user_params)
+               html = "Now your CAFe user is associated with a MySlice account - Please login in CAFe again."
+               return HttpResponse(html)
+
+        else:
+           #env['state'] = "Your affiliation (" + request.session["aff"] + ") at CAFe is not accepted."
+           html = "Your CAFe affiliation (" + request.session["aff"] + ") is not accepted. <br> Only \"student\" affiliation."
+           return HttpResponse(html)
+           #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+           
+
+           # login-ok sets state="Welcome to MySlice" in urls.py
+       def get (self, request, state=None):
+           env = self.default_env()
+           env['username']=the_user(request)
+           env['topmenu_items'] = topmenu_items(None, request)
+           if state: env['state'] = state
+           elif not env['username']: env['state'] = "Please sign in"
+           return HttpResponseRedirect ('/login-ok')
+       #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
diff --git a/plugins/cafe-1.0/others/edelberto.py.101113 b/plugins/cafe-1.0/others/edelberto.py.101113
new file mode 100644 (file)
index 0000000..93a0a15
--- /dev/null
@@ -0,0 +1,174 @@
+#!/usr/bin/env python
+
+#Edelberto from manifoldauth
+import os,sys
+import subprocess
+import shlex
+import getpass
+from hashlib import md5
+import time
+from random import Random
+import crypt
+
+#from manifold.manifold.core.router import Router
+from manifold.core.query import Query
+# add user to manifold
+
+from django.views.generic import View
+from django.core.context_processors import csrf
+#from django.http import HttpResponseRedirect
+from django.contrib.auth import authenticate, login, logout
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+
+from manifold.manifoldresult import ManifoldResult
+from ui.topmenu import topmenu_items, the_user
+from myslice.config import Config
+
+#from django.http import HttpResponse HttpResponseRedirect
+from django.http import HttpResponse
+#from django.http import HttpResponseRedirect
+#from django.template import  RequestContext
+from django.contrib.sessions.backends.db import SessionStore
+
+def index(request):
+#class EdelbertoView (View):
+
+# =================== Old code - to validate =================
+    '''
+    ip = "<html><body>" 
+    ip += "cn: " +  request.META['Shib-inetOrgPerson-cn'] + "</br>"
+    ip += "sn: " +  request.META['Shib-inetOrgPerson-sn'] + "</br>"
+    ip += "eppn: " + request.META['Shib-eduPerson-eduPersonPrincipalName'] + "</br>"
+    ip += "mail: " + request.META['Shib-inetOrgPerson-mail'] + "</br>"
+    ip += "Affiliation br: " + request.META['Shib-brEduPerson-brEduAffiliationType'] + "</br>"
+    ip += "Affiliation edu: " + request.META['Shib-eduPerson-eduPersonAffiliation'] + "</br>"
+    ip += "Auth-Method: " + request.META['Shib-Authentication-Method'] + "</br>"
+    ip += "Identity Provider: " + request.META['Shib-Identity-Provider'] + "</br>"
+    ip += "Application ID: " + request.META['Shib-Application-ID'] + "</br>"
+    ip += "Session ID: " + request.META['Shib-Session-ID'] + "</br>"
+    '''
+# Test cookie support
+    if request.session.test_cookie_worked():
+    #if session.test_cookie_worked():
+        return HttpResponse("Please enable cookies and try again.")
+        #return
+        print "Please enable cookies and try again."
+    else:
+        request.session['cn'] = request.META['Shib-inetOrgPerson-cn']
+        request.session['mail'] = request.META['Shib-inetOrgPerson-mail']
+        request.session['eppn'] = request.META['Shib-eduPerson-eduPersonPrincipalName']
+        #request.session['aff'] = request.META['Shib-brEduPerson-brEduAffiliationType']
+        request.session['aff'] = request.META['Shib-eduPerson-eduPersonAffiliation']
+       request.session['shib'] = request.META['Shib-Session-ID']
+
+        if 'mail' in request.session.keys():
+             print "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]
+             #ip += "Cookie: OK -> Content: cn:" + request.session["cn"] + " mail: " + request.session["mail"] + " eppn: " + request.session["eppn"]  + "</body></html>"
+        else:
+             print "Cookie: nothing/clear"
+             #ip += "Cookie: nothing/clear </body></html>"
+    
+   # return HttpResponse(ip)
+   
+
+    # expose this so we can mention the backend URL on the welcome page
+    def default_env (self):
+        config=Config()
+        return { 
+                 'MANIFOLD_URL':config.manifold_url(),
+                 }
+
+    #def post (self,request):
+    #    env = self.default_env()
+        #username = request.POST.get('username')
+        #password = request.POST.get('password')
+    if 'aff' in request.session.keys():
+        aff = request.session["aff"]
+        if aff == "student":
+            if request.session["eppn"] == 'esilva@uff.br':
+                username = 'admin'
+                password = 'fibre2013'
+            else:
+                 username = request.session["mail"]
+                 password = request.session["mail"] + "fibre2013"
+    
+               # pass request within the token, so manifold session key can be attached to the request session.
+           token = {'username': username, 'password': password, 'request': request}    
+
+               # our authenticate function returns either
+                   # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
+                   # . a django User in case of success
+                   # . or None if the backend could be reached but the authentication failed
+           auth_result = authenticate(token=token)
+                   # high-level errors, like connection refused or the like
+           if isinstance (auth_result, ManifoldResult):
+               manifoldresult = auth_result
+                   # let's use ManifoldResult.__repr__
+               env['state']="%s"%manifoldresult
+               return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+                   # user was authenticated at the backend
+           elif auth_result is not None:
+               user=auth_result
+               if user.is_active:
+                   print "LOGGING IN"
+                   login(request, user)
+                   htm = "<meta http-equiv=\"refresh\" content=\"0; url=https://sp-php.cafeexpresso.rnp.br/login-ok\" />"
+                   #return HttpResponseRedirect ('/login-ok')
+                   return HttpResponse (htm)
+               else:
+                   env['state'] = "Your account is not active, please contact the site admin."
+                   return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+               # otherwise
+           else:
+               '''
+               magic = "$1$"
+               password = password
+               # Generate a somewhat unique 8 character salt string
+               salt = str(time.time()) + str(Random().random())
+               salt = md5(salt).hexdigest()[:8]
+
+               if len(password) <= len(magic) or password[0:len(magic)] != magic:
+                   password = crypt.crypt(password.encode('latin1'), magic + salt + "$")
+
+               user_params = {
+                   'email': username,
+                   'password': password
+               }
+               query = Query(action='create', object='local:user', params=user_params)
+
+
+                   # Instantiate a TopHat router
+               with Router() as router:
+                   router.forward(query)
+               '''
+               #myArgs=[username,password]
+               #os.spawnlp(os.P_WAIT,'/tmp/adduser.py', username, password, '/bin/bash/')
+               command = '/var/www/manifold/manifold/bin/adduser.py ' + username + ' ' + password
+               #command = 'ls -la'
+                args = shlex.split(command)
+                p = subprocess.Popen(args, stdin=subprocess.PIPE).communicate()[0]
+               print command
+               print args
+               print p
+               #env['state'] = "Now your CAFe user is associated to your MySlice account - Please logging in CAFe again."
+               #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+               html = "Now its CAFe user is associated with a MySlice account - Please login in CAFe again."
+               return HttpResponse(html)
+
+        else:
+           #env['state'] = "Your affiliation (" + request.session["aff"] + ") at CAFe is not accepted."
+           html = "Your CAFe affiliation (" + request.session["aff"] + ") is not accepted. <br> Only \"student\" affiliation."
+           return HttpResponse(html)
+           #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+           
+
+           # login-ok sets state="Welcome to MySlice" in urls.py
+       def get (self, request, state=None):
+           env = self.default_env()
+           env['username']=the_user(request)
+           env['topmenu_items'] = topmenu_items(None, request)
+           if state: env['state'] = state
+           elif not env['username']: env['state'] = "Please sign in"
+           return HttpResponseRedirect ('/login-ok')
+       #return render_to_response('home-view.html',env, context_instance=RequestContext(request))
diff --git a/plugins/cafe-1.0/others/edelberto_context.py b/plugins/cafe-1.0/others/edelberto_context.py
new file mode 100644 (file)
index 0000000..ce884a7
--- /dev/null
@@ -0,0 +1,33 @@
+from django.core.urlresolvers import reverse\r
+from urllib import quote\r
+\r
+from django.conf import settings\r
+import myslice.settings\r
+\r
+def login_link(request):\r
+    """\r
+    This assumes your login link is the Shibboleth login page for your server \r
+    and uses the 'target' url parameter.\r
+    """\r
+    full_path = quote(request.get_full_path())\r
+    #login = reverse('shibboleth:login')\r
+\r
+    LOGIN_URL = getattr(settings, 'LOGIN_URL', None)\r
+\r
+    login = LOGIN_URL\r
+    ll = "%s?target=%s" % (login, full_path)\r
+    return { 'login_link': ll }\r
+\r
+def logout_link(request, *args):\r
+    """\r
+    This assumes your login link is the Shibboleth login page for your server \r
+    and uses the 'target' url parameter.\r
+    e.g: https://sp-php.cafeexpresso.rnp.br/Shibboleth.sso/Login\r
+    """\r
+    from app_settings import LOGOUT_URL, LOGOUT_REDIRECT_URL\r
+    #LOGOUT_REDIRECT_URL specifies a default logout page that will always be used when\r
+    #users logout from Shibboleth.\r
+    target = LOGOUT_REDIRECT_URL or quote(request.build_absolute_uri())\r
+    logout = reverse('shibboleth:logout')\r
+    ll = "%s?target=%s" % (logout, target)\r
+    return { 'logout_link': ll }\r
diff --git a/plugins/cafe-1.0/others/manifoldbackend.py b/plugins/cafe-1.0/others/manifoldbackend.py
new file mode 100644 (file)
index 0000000..14abb74
--- /dev/null
@@ -0,0 +1,76 @@
+import time
+
+from django.contrib.auth.models import User
+
+from manifold.manifoldapi import ManifoldAPI, ManifoldException, ManifoldResult
+from manifold.core.query        import Query
+
+# Name my backend 'ManifoldBackend'
+class ManifoldBackend:
+
+    # Create an authentication method
+    # This is called by the standard Django login procedure
+    def authenticate(self, token=None):
+        if not token:
+            return None
+
+        try:
+            username = token['username']
+            password = token['password']
+            request = token['request']
+
+            auth = {'AuthMethod': 'password', 'Username': username, 'AuthString': password}
+            api = ManifoldAPI(auth)
+            sessions_result = api.forward(Query.create('local:session').to_dict())
+            print "result"
+            sessions = sessions_result.ok_value()
+            print "ok"
+            if not sessions:
+                print "GetSession failed", sessions_result.error()
+                return
+            print "first", sessions
+            session = sessions[0]
+
+            # Change to session authentication
+            api.auth = {'AuthMethod': 'session', 'session': session['session']}
+            self.api = api
+
+            # Get account details
+            # the new API would expect Get('local:user') instead
+            persons_result = api.forward(Query.get('local:user').to_dict())
+            persons = persons_result.ok_value()
+            if not persons:
+                print "GetPersons failed",persons_result.error()
+                return
+            person = persons[0]
+            print "PERSON=", person
+
+            request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': session['expires']}
+        except ManifoldException, e:
+            print "Caught ManifoldException, returning corresponding ManifoldResult"
+            return e.manifold_result
+        except Exception, e:
+            print "E: manifoldbackend", e
+            import traceback
+            traceback.print_exc()
+            return None
+
+        try:
+            # Check if the user exists in Django's local database
+            user = User.objects.get(username=username)
+        except User.DoesNotExist:
+            # Create a user in Django's local database
+            user = User.objects.create_user(username, username, 'passworddoesntmatter')
+            user.first_name = "DUMMY_FIRST_NAME" #person['first_name']
+            user.last_name = "DUMMY LAST NAME" # person['last_name']
+            user.email = person['email']
+        return user
+
+    # Required for your backend to work properly - unchanged in most scenarios
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None
+
+
diff --git a/plugins/cafe-1.0/others/sub.py b/plugins/cafe-1.0/others/sub.py
new file mode 100755 (executable)
index 0000000..ec19a5a
--- /dev/null
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+
+#Edelberto from manifoldauth
+import os,sys
+import subprocess
+import shlex
+import getpass
+from hashlib import md5
+import time
+from random import Random
+import crypt
+       
+username = 'teste'
+password = '123'
+
+command = '/var/www/manifold/manifold/bin/adduser.py ' + username + ' ' + password
+    #command = 'ls -la'
+args = shlex.split(command)
+p = subprocess.Popen(args, stdin=subprocess.PIPE).communicate()[0]
+print command
+print args
+print p
diff --git a/plugins/cafe-1.0/sub.py b/plugins/cafe-1.0/sub.py
new file mode 100755 (executable)
index 0000000..ec19a5a
--- /dev/null
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+
+#Edelberto from manifoldauth
+import os,sys
+import subprocess
+import shlex
+import getpass
+from hashlib import md5
+import time
+from random import Random
+import crypt
+       
+username = 'teste'
+password = '123'
+
+command = '/var/www/manifold/manifold/bin/adduser.py ' + username + ' ' + password
+    #command = 'ls -la'
+args = shlex.split(command)
+p = subprocess.Popen(args, stdin=subprocess.PIPE).communicate()[0]
+print command
+print args
+print p