def sfa_add_authority(request, authority_params): query = Query.create('authority').set(authority_params).select('authority_hrn') results = execute_query(request, query) print "sfa_add_auth results=",results if not results: raise Exception, "Could not create %s. Already exists ?" % authority_params['hrn'] return results
def manifold_add_platform(request, platform_params): query = Query.create('local:platform').set(platform_params).select(['user', 'platform']) results = execute_admin_query(request,query) if not results: raise Exception, "Failed creating manifold platform %s for user: %s" % (platform_params['platform'], platform_params['user']) result, = results return result['platform_id']
def manifold_add_account(request, account_params): query = Query.create('local:account').set(account_params).select(['user', 'platform']) results = execute_admin_query(request,query) if not results: raise Exception, "Failed creating manifold account on platform %s for user: %s" % (account_params['platform'], account_params['user']) result, = results return result['user_id']
def manifold_add_user(request, user_params): # user_params: email, password e.g., user_params = {'email':'*****@*****.**','password':'******'} query = Query.create('local:user').set(user_params).select('email') results = execute_admin_query(request, query) if not results: raise Exception, "Failed creating manifold user: %s" % user_params['email'] result, = results return result['email']
def sfa_add_user(request, user_params): if 'email' in user_params: user_params['user_email'] = user_params['email'] query = Query.create('user').set(user_params).select('user_hrn') results = execute_query(request, query) if not results: raise Exception, "Could not create %s. Already exists ?" % user_params['hrn'] return results
def create(self): query = Query.create(self.type) # No filters for create if self.params : for p in self.params : for k,v in p.iteritems() : logger.debug("param: {} : {}".format(k, v)) query.set({k : v}) logger.debug("query = {}".format(query)) else: raise Exception, "Params are required for create" return execute_query(self.request, query)
def get_session(self, user): assert user, "A user associated to a session should not be NULL" self.clean_sessions() # Generate 32 random bytes bytes = random.sample(xrange(0, 256), 32) # Base64 encode their string representation session_params = { 'session': base64.b64encode("".join(map(chr, bytes))), 'user_id': user['user_id'], 'expires': int(time.time()) + (24 * 60 * 60) } query_session = Query.create('local:session').set(session_params).select('session') try: session, = self.interface.execute_local_query(query_sessions) except: pass return session['session']
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 "ManifoldBackend.authenticate caught ManifoldException, returning corresponding ManifoldResult" return e.manifold_result
from manifold.core.router import Router from manifold.core.query import Query from config import auth import sys, pprint def print_err(err): print '-' * 80 print 'Exception', err['code'], 'raised by', err['origin'], ':', err[ 'description'] for line in err['traceback'].split("\n"): print "\t", line print '' query = Query.create('local:session') ret = Router().forward(query, user=Auth(auth).check()) if ret['code'] != 0: if isinstance(ret['description'], list): # We have a list of errors for err in ret['description']: print_err(err) ret = ret['value'] print "===== RESULTS =====" for r in ret: pprint.pprint(r)
def manifold_details(url, email, password, logger): """ return a tuple with (session, auth, person, slices) associated with these credentials at the manifold backend * session : the session with the manifold API * auth : ready-to use auth to talk to the API again * user : a flat structure with at least the following keys * email, hrn * firstname, lastname in case of failure, return tuple with same size with only None's """ failure_result = None, None, None auth = { 'AuthMethod': 'password', 'Username': email, 'AuthString': password } api = ManifoldAPI(url, auth) sessions_result = api.forward(Query.create('local:session').to_dict()) logger.debug("sessions_result = ", sessions_result) sessions = sessions_result.ok_value() if not sessions: logger.error("GetSession failed: {}".format(sessions_result.error())) return failure_result session = sessions[0] # Change to session authentication api.auth = {'AuthMethod': 'session', 'session': session['session']} # Get account details persons_result = api.forward(Query.get('local:user').to_dict()) logger.debug("persons_result=", persons_result) persons = persons_result.ok_value() if not persons: logger.error("GetPersons failed: {}".format(persons_result.error())) return failure_result person = persons[0] logger.debug("PERSON : {}".format(person)) # get related slices query = Query.get('myslice:user').filter_by( 'user_hrn', '==', '$user_hrn').select(['user_hrn', 'slices']) mf_result = api.forward(query.to_dict()) logger.debug("mf_result=", mf_result) # xxx - needs more work # for now if hrn is not properly filled we want to proceed # however this is wrong; it can happen for example # when credentials upstream have expired and # need to be uploaded again to the manifold end # so it would be best to refuse logging in and to provide this kind of hint # we don't report login_message properly yet though... hrn = "<unknown_hrn>" try: # xxx use ManifoldResult ? # this is a list of dicts that have a 'slices' field val_d_s = mf_result['value'] # in fact there is only one of these dicts because we have specified # myslice:user hrns = [val_d['user_hrn'] for val_d in val_d_s] if hrns: hrn = hrns[0] except Exception as e: logger.exception("mfdetails: Could not retrieve user's slices") # looks like it's useless # # add hrn in person # person['hrn'] = hrn # synthesize our own user structure import json person_config = json.loads(person['config']) user_details = { 'email': person['email'], 'hrn': hrn, 'firstname': person_config['firstname'], 'lastname': person_config['lastname'], } return session, auth, user_details
def main(): argc = len(sys.argv) program_name = sys.argv[0] with Router() as router: ret_gateways = router.forward( Query.get('local:gateway').select('name')) if ret_gateways['code'] != 0: print "W: Could not contact the Manifold server to list available gateways. Check disabled." supported_gateways = None else: gateways = ret_gateways['value'] if not gateways: print "W: Could not contact the Manifold server to list available gateways. Check disabled." supported_gateways = None else: supported_gateways = [gw['name'] for gw in gateways] # Check number of arguments if argc not in [6, 7]: print >> sys.stderr, "%s: Invalid number of arguments (is equal to %d, should be equal to 6 or 7) " % ( program_name, argc) usage(supported_gateways) sys.exit(1) name, longname, gateway, auth_type, config = sys.argv[1:6] if argc == 7: disabled = sys.argv[6] else: disabled = "1" # Check NAME if name != name.lower(): print >> sys.stderr, "%s: Invalid NAME parameter (is '%s', should be '%s')" % ( program_name, name, name.lower()) usage(supported_gateways) sys.exit(1) # Check GATEWAY if supported_gateways and gateway not in supported_gateways: print >> sys.stderr, "%s: Invalid GATEWAY parameter (is '%s', should be in '%s')" % ( program_name, gateway, "', '".join(supported_gateways)) usage(supported_gateways) sys.exit(1) # Check AUTH_TYPE supported_auth_type = ["none", "default", "user"] if auth_type not in supported_auth_type: print >> sys.stderr, "%s: Invalid AUTH_TYPE parameter (is '%s', should be in '%s')" % ( program_name, auth_type, "', '".join(supported_auth_type)) usage(supported_gateways) sys.exit(1) # Check DISABLED if argc == 7: supported_disabled = [ "False", "FALSE", "NO", "0", "True", "TRUE", "YES", "1" ] if str(sys.argv[6]) not in supported_disabled: print >> sys.stderr, "%s: Invalid DISABLED parameter (is '%s', should be in '%s')" % ( program_name, disabled, "', '".join(supported_disabled)) usage(supported_gateways) sys.exit(1) disabled = str(sys.argv[6]) in ["False", "FALSE", "NO", "0"] # why 2 different fields for the same config ? platform_params = { 'platform': name, 'platform_longname': longname, 'gateway_type': gateway, 'auth_type': auth_type, 'config': config, 'disabled': disabled } router.forward(Query.create('local:platform').set(platform_params))
def sfa_add_slice(request, slice_params): query = Query.create('slice').set(slice_params).select('slice_hrn') results = execute_query(request, query) if not results: raise Exception, "Could not create %s. Already exists ?" % slice_params['hrn'] return results
def authenticate(self, token=None): if not token: return None person = {} try: email = token['username'] username = email.split('@')[-1] password = token['password'] request = token['request'] auth = {'AuthMethod': 'password', 'Username': email, 'AuthString': password} api = ManifoldAPI(config.manifold_url(), auth) sessions_result = api.forward(Query.create('local:session').to_dict()) sessions = sessions_result.ok_value() if not sessions: logger.error("GetSession failed: {}".format(sessions_result.error())) return None session = sessions[0] logger.debug("SESSION : {}".format(session.keys())) # Change to session authentication api.auth = {'AuthMethod': 'session', 'session': session['session']} #api.auth = session_auth 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: logger.error("GetPersons failed: {}".format(persons_result.error())) return None person = persons[0] logger.debug("PERSON : {}".format(person)) request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': session['expires']} #logger.info("{} {} <{}> logged in"\ # .format(person['config']['first_name'], person['config']['last_name'], person['config']['email'])) #SessionCache().store_auth(request, session_auth) except ManifoldException as e: logger.error("ManifoldException in Auth Backend: {}".format(e.manifold_result)) except Exception as e: logger.error("Exception in Manifold Auth Backend: {}".format(e)) import traceback logger.error(traceback.format_exc()) return None try: # Check if the user exists in Django's local database user = User.objects.get(email=email) except User.DoesNotExist: # Create a user in Django's local database user = User.objects.create_user(username, email, 'passworddoesntmatter') user.email = person['email'] if 'firstname' in person: user.first_name = person['firstname'] if 'lastname' in person: user.last_name = person['lastname'] user.pi = authority_check_pis (request, user.email) request.session['user'] = {'email':user.email,'pi':user.pi,'firstname':user.first_name,'lastname':user.last_name} return user