From 238be555dbca3db34c4fbe9decf6b2825b68ef58 Mon Sep 17 00:00:00 2001 From: Loic & Edelberto Date: Thu, 13 Mar 2014 10:27:42 -0300 Subject: [PATCH] cafe plugin --- plugins/cafe | 1 + plugins/cafe-1.0/__init__.py | 0 plugins/cafe-1.0/cafe | 1 + plugins/cafe-1.0/cafe.zip | Bin 0 -> 2974 bytes plugins/cafe-1.0/edelberto-120314.py | 218 ++++++++++++++++++ plugins/cafe-1.0/edelberto.py | 172 ++++++++++++++ plugins/cafe-1.0/manifoldbackend.py | 76 ++++++ .../others/edelberto.py-noupdateaccountONLY | 197 ++++++++++++++++ plugins/cafe-1.0/others/edelberto.py.101113 | 174 ++++++++++++++ plugins/cafe-1.0/others/edelberto_context.py | 33 +++ plugins/cafe-1.0/others/manifoldbackend.py | 76 ++++++ plugins/cafe-1.0/others/sub.py | 22 ++ plugins/cafe-1.0/sub.py | 22 ++ 13 files changed, 992 insertions(+) create mode 120000 plugins/cafe create mode 100644 plugins/cafe-1.0/__init__.py create mode 120000 plugins/cafe-1.0/cafe create mode 100644 plugins/cafe-1.0/cafe.zip create mode 100644 plugins/cafe-1.0/edelberto-120314.py create mode 100644 plugins/cafe-1.0/edelberto.py create mode 100644 plugins/cafe-1.0/manifoldbackend.py create mode 100644 plugins/cafe-1.0/others/edelberto.py-noupdateaccountONLY create mode 100644 plugins/cafe-1.0/others/edelberto.py.101113 create mode 100644 plugins/cafe-1.0/others/edelberto_context.py create mode 100644 plugins/cafe-1.0/others/manifoldbackend.py create mode 100755 plugins/cafe-1.0/others/sub.py create mode 100755 plugins/cafe-1.0/sub.py diff --git a/plugins/cafe b/plugins/cafe new file mode 120000 index 00000000..818c1c65 --- /dev/null +++ b/plugins/cafe @@ -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 index 00000000..e69de29b diff --git a/plugins/cafe-1.0/cafe b/plugins/cafe-1.0/cafe new file mode 120000 index 00000000..47de4c7d --- /dev/null +++ b/plugins/cafe-1.0/cafe @@ -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 index 0000000000000000000000000000000000000000..b58f144bcc4f2eeaedcd5c085d86e162fe356369 GIT binary patch literal 2974 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 Pw={pk{7*-+{ImTFNtJhM literal 0 HcmV?d00001 diff --git a/plugins/cafe-1.0/edelberto-120314.py b/plugins/cafe-1.0/edelberto-120314.py new file mode 100644 index 00000000..bbecd5ce --- /dev/null +++ b/plugins/cafe-1.0/edelberto-120314.py @@ -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 = "" + ip += "cn: " + request.META['Shib-inetOrgPerson-cn'] + "
" + ip += "sn: " + request.META['Shib-inetOrgPerson-sn'] + "
" + ip += "eppn: " + request.META['Shib-eduPerson-eduPersonPrincipalName'] + "
" + ip += "mail: " + request.META['Shib-inetOrgPerson-mail'] + "
" + ip += "Affiliation br: " + request.META['Shib-brEduPerson-brEduAffiliationType'] + "
" + ip += "Affiliation edu: " + request.META['Shib-eduPerson-eduPersonAffiliation'] + "
" + ip += "Auth-Method: " + request.META['Shib-Authentication-Method'] + "
" + ip += "Identity Provider: " + request.META['Shib-Identity-Provider'] + "
" + ip += "Application ID: " + request.META['Shib-Application-ID'] + "
" + ip += "Session ID: " + request.META['Shib-Session-ID'] + "
" + ''' +# 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"] + "" + else: + print "Cookie: nothing/clear" + #ip += "Cookie: nothing/clear " + + # 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 = "" + 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 = "" + #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.
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 index 00000000..a3ec0b42 --- /dev/null +++ b/plugins/cafe-1.0/edelberto.py @@ -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"] + "" + else: + print "Cookie: nothing/clear" + #ip += "Cookie: nothing/clear " + + # 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 = "" + 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 = "" + #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 index 00000000..14abb748 --- /dev/null +++ b/plugins/cafe-1.0/manifoldbackend.py @@ -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 index 00000000..67fe0f42 --- /dev/null +++ b/plugins/cafe-1.0/others/edelberto.py-noupdateaccountONLY @@ -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 = "" + ip += "cn: " + request.META['Shib-inetOrgPerson-cn'] + "
" + ip += "sn: " + request.META['Shib-inetOrgPerson-sn'] + "
" + ip += "eppn: " + request.META['Shib-eduPerson-eduPersonPrincipalName'] + "
" + ip += "mail: " + request.META['Shib-inetOrgPerson-mail'] + "
" + ip += "Affiliation br: " + request.META['Shib-brEduPerson-brEduAffiliationType'] + "
" + ip += "Affiliation edu: " + request.META['Shib-eduPerson-eduPersonAffiliation'] + "
" + ip += "Auth-Method: " + request.META['Shib-Authentication-Method'] + "
" + ip += "Identity Provider: " + request.META['Shib-Identity-Provider'] + "
" + ip += "Application ID: " + request.META['Shib-Application-ID'] + "
" + ip += "Session ID: " + request.META['Shib-Session-ID'] + "
" + ''' +# 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"] + "" + else: + print "Cookie: nothing/clear" + #ip += "Cookie: nothing/clear " + + # 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 = "" + #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.
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 index 00000000..93a0a151 --- /dev/null +++ b/plugins/cafe-1.0/others/edelberto.py.101113 @@ -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 = "" + ip += "cn: " + request.META['Shib-inetOrgPerson-cn'] + "
" + ip += "sn: " + request.META['Shib-inetOrgPerson-sn'] + "
" + ip += "eppn: " + request.META['Shib-eduPerson-eduPersonPrincipalName'] + "
" + ip += "mail: " + request.META['Shib-inetOrgPerson-mail'] + "
" + ip += "Affiliation br: " + request.META['Shib-brEduPerson-brEduAffiliationType'] + "
" + ip += "Affiliation edu: " + request.META['Shib-eduPerson-eduPersonAffiliation'] + "
" + ip += "Auth-Method: " + request.META['Shib-Authentication-Method'] + "
" + ip += "Identity Provider: " + request.META['Shib-Identity-Provider'] + "
" + ip += "Application ID: " + request.META['Shib-Application-ID'] + "
" + ip += "Session ID: " + request.META['Shib-Session-ID'] + "
" + ''' +# 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"] + "" + else: + print "Cookie: nothing/clear" + #ip += "Cookie: nothing/clear " + + # 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 = "" + #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.
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 index 00000000..ce884a7b --- /dev/null +++ b/plugins/cafe-1.0/others/edelberto_context.py @@ -0,0 +1,33 @@ +from django.core.urlresolvers import reverse +from urllib import quote + +from django.conf import settings +import myslice.settings + +def login_link(request): + """ + This assumes your login link is the Shibboleth login page for your server + and uses the 'target' url parameter. + """ + full_path = quote(request.get_full_path()) + #login = reverse('shibboleth:login') + + LOGIN_URL = getattr(settings, 'LOGIN_URL', None) + + login = LOGIN_URL + ll = "%s?target=%s" % (login, full_path) + return { 'login_link': ll } + +def logout_link(request, *args): + """ + This assumes your login link is the Shibboleth login page for your server + and uses the 'target' url parameter. + e.g: https://sp-php.cafeexpresso.rnp.br/Shibboleth.sso/Login + """ + from app_settings import LOGOUT_URL, LOGOUT_REDIRECT_URL + #LOGOUT_REDIRECT_URL specifies a default logout page that will always be used when + #users logout from Shibboleth. + target = LOGOUT_REDIRECT_URL or quote(request.build_absolute_uri()) + logout = reverse('shibboleth:logout') + ll = "%s?target=%s" % (logout, target) + return { 'logout_link': ll } diff --git a/plugins/cafe-1.0/others/manifoldbackend.py b/plugins/cafe-1.0/others/manifoldbackend.py new file mode 100644 index 00000000..14abb748 --- /dev/null +++ b/plugins/cafe-1.0/others/manifoldbackend.py @@ -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 index 00000000..ec19a5aa --- /dev/null +++ b/plugins/cafe-1.0/others/sub.py @@ -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 index 00000000..ec19a5aa --- /dev/null +++ b/plugins/cafe-1.0/sub.py @@ -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 -- 2.43.0