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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 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.47.0