def get_user_account(request, user_email, platform_name): """ Returns the user configuration for a given platform. This function does not resolve references. """ user_query = Query().get('local:user').filter_by( 'email', '==', user_email).select('user_id') user_details = execute_admin_query(request, user_query) platform_query = Query().get('local:platform').filter_by( 'platform', '==', platform_name).select('platform_id') platform_details = execute_admin_query(request, platform_query) account_query = Query().get('local:account').filter_by( 'platform_id', '==', platform_details[0]['platform_id']).filter_by( 'user_id', '==', user_details[0]['user_id']).select('user_id', 'platform_id', 'auth_type', 'config') accounts = execute_admin_query(request, account_query) if not accounts: raise Exception, "this account does not exist" if accounts[0]['auth_type'] == 'reference': pf = json.loads(accounts[0]['config'])['reference_platform'] return get_user_account(request, user_email, pf) return accounts[0]
def get_or_post (self, request, method): """ """ errors = [] slice_name ='' #purpose='' #url='' authority_hrn = None authority_name = None # Retrieve the list of authorities authorities = getAuthorities(request, admin=True) ##if self.theme == 'fed4fire' or self.theme == 'onelab': #authorities_query = Query.get('myslice:authority').select('authority_hrn') ##else: ## authorities_query = Query.get('authority').select('name', 'authority_hrn') #authorities = execute_admin_query(request, authorities_query) #if authorities is not None: # authorities = sorted(authorities, key=lambda k: k['authority_hrn']) # #if self.theme != 'fed4fire' or self.theme != 'onelab': # # authorities = sorted(authorities, key=lambda k: k['name']) # Get user_email (XXX Would deserve to be simplified) user_query = Query().get('local:user').select('email','config') user_details = execute_query(request, user_query) user_email = user_details[0].get('email') # getting user_hrn for user_detail in user_details: user_config = json.loads(user_detail['config']) user_authority = user_config.get('authority','N/A') # getting the org from authority # for authority in authorities: # if 'name' in authority and authority['authority_hrn'] == user_authority: # authority_name = authority['name'] # Handle the case when we use only hrn and not name #if authority_name is None: # authority_name = user_authority account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config') account_details = execute_query(request, account_query) platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled') platform_details = execute_query(request, platform_query) user_hrn = None #getting user_hrn from local:account for account_detail in account_details: for platform_detail in platform_details: if platform_detail['platform_id'] == account_detail['platform_id']: # taking user_hrn only from myslice account # NOTE: we should later handle accounts filter_by auth_type= managed OR user if 'myslice' in platform_detail['platform']: account_config = json.loads(account_detail['config']) user_hrn = account_config.get('user_hrn','N/A')
def get(self, request): authority_contacts = {} authority = {'authority_hrn': 'fed4fire.upmc'} if request.user.is_authenticated(): user_local_query = Query().get('local:user').select( 'config').filter_by('email', '==', str(self.request.user)) user_local_details = execute_query(self.request, user_local_query) user_authority = json.loads( user_local_details[0]['config']).get('authority') logger.info( "**************________ management about = {}".format( user_authority)) # XXX Should be done using Metadata # select column.name from local:object where table=='authority' authority_query = Query().get('authority').select( 'authority_hrn', 'name', 'address', 'enabled', 'description', 'scientific', 'city', 'name', 'url', 'country', 'enabled', 'longitude', 'tech', 'latitude', 'pi_users', 'onelab_membership', 'postcode').filter_by('authority_hrn', '==', user_authority) authority_details = execute_query(self.request, authority_query) if authority_details: authority = authority_details[0] if 'scientific' in authority and authority[ 'scientific'] is not None: authority_contacts['scientific'] = [ x.strip()[1:-1] for x in authority['scientific'][1:-1].split(',') ] if 'technical' in authority and authority[ 'technical'] is not None: authority_contacts['technical'] = [ x.strip()[1:-1] for x in authority['tech'][1:-1].split(',') ] if 'legal' in authority and authority['legal'] is not None: authority_contacts['legal'] = [ x.strip().replace('"', '') for x in authority['legal'][1:-1].split(',') ] else: authority_contacts = None authority = None return render_to_response(self.template, { 'theme': self.theme, 'authority': authority, 'authority_contacts': authority_contacts }, context_instance=RequestContext(request))
def __init__(self, id=None, name=None): if id is not None: platform_query = Query().get('local:platform').select( 'platform_id', 'platform', 'gateway_type', 'disabled').filter_by('platform_id', '==', platform_id) if name is not None: platform_query = Query().get('local:platform').select( 'platform_id', 'platform', 'gateway_type', 'disabled').filter_by('platform', '==', platform) self.id = platform_query['platform_id'] self.name = platform_query['platform'] self.type = platform_query['gateway_type'] self.disabled = platform_query['disabled']
def get(self, request, state=None): env = {} pkey = None cert = None account_query = Query().get('local:account').select( 'user_id', 'platform_id', 'auth_type', 'config') account_details = execute_query(self.request, account_query) # Get the accounts of the current logged in user for account_detail in account_details: try: account_config = json.loads(account_detail['config']) if 'user_private_key' in account_config: pkey = account_config['user_private_key'] if 'gid' in account_config: cert = account_config['gid'] except ValueError as e: print('not a JSON') env['supername'] = 'Amira' env['cert'] = cert env['key'] = pkey if request.user.is_authenticated(): env['person'] = self.request.user env['username'] = self.request.user else: env['person'] = None env['username'] = None env['theme'] = self.theme env['section'] = "" return render_to_response(self.template_name, env, context_instance=RequestContext(request))
def __init__ (self, platform_id, user_id): account_query = Query().get('local:account')\ .select('user_id','platform_id','auth_type','config')\ .filter_by('platform_id', '==', platform_id)\ .filter_by('user_id', '==', user_id) account_details = execute_query(self.request, account_query) self.user_id = account_details['user_id'] self.platform_id = account_details['platform_id'] self.auth_type = account_details['auth_type'] self.config = account_details['config'] account_config = json.loads(account_details['config']) self.usr_hrn = account_config.get('user_hrn',None) self.pub_key = account_config.get('user_public_key',None) self.reference = account_config.get ('reference_platform',None) self.user_cred = account_config.get('delegated_user_credential',None) self.user_cred_expiration = get_expiration(self.user_cred) slice_creds = account_config.get('delegated_slice_credentials',None) for slice_name, slice_cred in slice_creds.iteritems(): self.slice_cred_expiration = get_expiration(self.slice_cred) self.auth_cred = account_config.get('delegated_authority_credentials',None) self.auth_cred_expiration = get_expiration(self.auth_cred)
def topmenu_items_live(current, page): request = page.request # XXX TODO This should be triggered only when user is logged in # We might use local storage instead # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2 if request.user.is_authenticated(): query_pi_auths = Query.get('myslice:user').filter_by( 'user_hrn', '==', '$user_hrn').select('user_hrn', 'pi_authorities') page.enqueue_query(query_pi_auths) else: query_pi_auths = Query() # # even though this plugin does not have any html materialization, the corresponding domid # # must exist because it is searched at init-time to create the JS plugin # # so we simply piggy-back the target button created in the topmenu topmenuvalidation = TopmenuValidation( page=page, # see above domid='topmenu-validation', query=query_pi_auths, # this one is the target for a $.show() when the query comes back button_domid="topmenu-validation") # although the result does not matter, rendering is required for the JS init code to make it in the page topmenuvalidation.render(request) return topmenu_items_static(current, request)
def main(): argc = len(sys.argv) if argc != 4: usage() sys.exit(1) email = sys.argv[1] config = sys.argv[2] status = sys.argv[3] password = getpass.getpass("Password: "******"$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': email, 'password': password, 'config': config, 'status': status, } query = Query(action='create', object='local:user', params=user_params) # Instantiate a TopHat router with Router() as router: router.forward(query)
def __init__(self, allowed_capabilities = None): """ Create an Interface instance. Args: platforms: A list of Platforms. allowed_capabilities: A Capabilities instance or None """ # Register the list of Gateways Log.info("Registering gateways") register_gateways() # self.platforms is list(dict) where each dict describes a platform. # See platform table in the Storage. self.platforms = Storage.execute(Query().get("platform").filter_by("disabled", "=", False)) #, format = "object") # self.allowed_capabilities is a Capabilities instance (or None) self.allowed_capabilities = allowed_capabilities # self.data is {String : list(Announce)} dictionnary mapping each # platform name (= namespace) with its corresponding Announces. self.metadata = dict() # self.gateways is a {String : Gateway} which maps a platform name to # the appropriate Gateway instance. self.gateways = dict() self.policy = Policy(self) self.boot()
def get_platforms (self, request): username = self.request.user pf_query = Query().get('local:platform').filter_by('disabled', '==', '0').filter_by('gateway_type', '==', 'sfa').select('platform') res_platforms = execute_query(request, pf_query) platforms = [p['platform'] for p in res_platforms] return platforms
def getUserAuthority(self, request): # Get user_email (XXX Would deserve to be simplified) user_query = Query().get('local:user').select('email', 'config') user_details = execute_query(request, user_query) for user_detail in user_details: user_config = json.loads(user_detail['config']) user_authority = user_config.get('authority', 'N/A') return user_authority
def get_query(self): """ \brief Returns the query representing the data produced by the nodes. \return query representing the data produced by the nodes. """ try: return self.query except: return Query()
def get(self, request, state=None): env = self.default_env() email_list = [] status_list = [] authority_list = [] config = {} user_query = Query().get('local:user').select('email', 'status', 'config') user_details = execute_admin_query(self.request, user_query) for user in user_details: # get email email_list.append(user['email']) # get status if user['status'] == 0: user_status = 'Disabled' elif user['status'] == 1: user_status = 'Validation Pending' elif user['status'] == 2: user_status = 'Enabled' else: user_status = 'N/A' status_list.append(user_status) #get authority if user['config'] is not None: user_config = json.loads(user['config']) user_authority = user_config.get('authority', 'N/A') authority_list.append(user_authority) user_list = [{ 'email': t[0], 'status': t[1], 'authority': t[2] } for t in zip(email_list, status_list, authority_list)] if request.user.is_authenticated(): env['person'] = self.request.user else: env['person'] = None env['theme'] = self.theme env['user_list'] = user_list env['username'] = the_user(request) env['topmenu_items'] = topmenu_items(None, request) if state: env['state'] = state elif not env['username']: env['state'] = None # use one or two columns for the layout - not logged in users will see the login prompt env['layout_1_or_2'] = "layout-unfold2.html" if not env[ 'username'] else "layout-unfold1.html" return render_to_response(self.template, env, context_instance=RequestContext(request))
def get_platforms(request): ret = list() platform_query = Query().get('local:platform').filter_by( 'gateway_type', '==', 'sfa').filter_by('disabled', '==', 0).select('platform') platforms = execute_admin_query(request, platform_query) for p in platforms: ret.append(p['platform']) return ret
def createDatabase(request, slicename): result = {} Config = config(request) server = Config.get('influxdb', 'server') #port = Config.get('influxdb', 'port', 8086) port = 8086 user = Config.get('influxdb', 'user') password = Config.get('influxdb', 'password') dbname = slicename dbuser = request.user.username dbpassword = generatePassword() query = Query().get('user').filter_by('user_email', '==', dbuser).select('slices') slices = execute_query(request, query) if not slicename in slices: result['status'] = 'fail' result['message'] = 'no permissions' return HttpResponse(json.dumps(result), content_type="application/json") client = InfluxDBClient(server, port, user, password, dbname) try: client.create_database(dbname) except Exception as e: print e # Add database user try: client.add_database_user(dbuser, dbpassword) except Exception as e: print e # Make user a database admin client.set_database_admin(dbuser) # Insert an entry in the Influxdb table i = MeasurementsDB(backend='influxdb', server=server, port=port, dbname=dbname, dbuser=dbuser, dbpassword=dbpassword) i.save() result['status'] = 'ok' return HttpResponse(json.dumps(result), content_type="application/json")
def get(self, request, authority_hrn=None, state=None): env = self.default_env() if request.user.is_authenticated(): env['person'] = self.request.user if authority_hrn is None: # CACHE PB with fields page = Page(request) metadata = page.get_metadata() user_md = metadata.details_by_object('user') user_fields = [column['name'] for column in user_md['column']] # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2 user_query = Query().get('myslice:user').select( user_fields).filter_by('user_hrn', '==', '$user_hrn') #user_query = Query().get('myslice:user').select('user_hrn','parent_authority').filter_by('user_hrn','==','$user_hrn') user_details = execute_query(self.request, user_query) try: env['user_details'] = user_details[0] except Exception, e: # If the Query fails, check in local DB try: user_local_query = Query().get('local:user').select( 'config').filter_by('email', '==', str(env['person'])) user_local_details = execute_query( self.request, user_local_query) user_local = user_local_details[0] user_local_config = user_local['config'] user_local_config = json.loads(user_local_config) user_local_authority = user_local_config.get( 'authority') if 'user_details' not in env or 'parent_authority' not in env[ 'user_details'] or env['user_details'][ 'parent_authority'] is None: env['user_details'] = { 'parent_authority': user_local_authority } except Exception, e: env['error'] = "Please check your Credentials"
def getUserHrn(self, request): user_hrn = None account_query = Query().get('local:account').select( 'user_id', 'platform_id', 'auth_type', 'config') account_details = execute_query(request, account_query) platform_query = Query().get('local:platform').select( 'platform_id', 'platform', 'gateway_type', 'disabled') platform_details = execute_query(request, platform_query) # getting user_hrn from local:account for account_detail in account_details: for platform_detail in platform_details: if platform_detail['platform_id'] == account_detail[ 'platform_id']: # taking user_hrn only from myslice account # NOTE: we should later handle accounts filter_by auth_type= managed OR user if 'myslice' in platform_detail['platform']: account_config = json.loads(account_detail['config']) user_hrn = account_config.get('user_hrn', 'N/A') return user_hrn
def create_ref_account(user, platform, ref_platform, router=None): account_params = { 'user': user, 'platform': platform, 'auth_type': 'reference', 'config': '{"reference_platform":"' + ref_platform + '"}' } account_query = Query(action='create', object='local:account', params=account_params) if router is None: with Router() as router: router.forward(account_query) else: router.forward(account_query)
def get_context_data(self, **kwargs): page = Page(self.request) page.add_js_files(["js/common.functions.js"]) platform_query = Query().get('local:platform').filter_by( 'disabled', '==', '0').select('platform', 'platform_longname', 'gateway_type') #platform_query = Query().get('local:platform').select('platform','platform_longname','gateway_type') page.enqueue_query(platform_query) page.expose_js_metadata() platformlist = QueryTable( page=page, title='List', domid='checkboxes', # this is the query at the core of the slice list query=platform_query, query_all=platform_query, checkboxes=False, init_key='platform', datatables_options={ 'iDisplayLength': 10, 'bLengthChange': True, 'bAutoWidth': True, }, ) context = super(PlatformsView, self).get_context_data(**kwargs) context['person'] = self.request.user context['platforms'] = platformlist.render(self.request) # XXX This is repeated in all pages # more general variables expected in the template context['title'] = 'Platforms connected to MySlice' # the menu items on the top context['topmenu_items'] = topmenu_items_live('Platforms', page) # so we can sho who is logged context['username'] = the_user(self.request) context['theme'] = self.theme context.update(page.prelude_env()) context['layout_1_or_2'] = "layout-unfold2.html" if not context[ 'username'] else "layout-unfold1.html" return context
def get_users_in_slice(request, slice_hrn): # select users.user_hrn, users.user_email, users.keys # from myslice:slice # where slice_hrn=='onelab.upmc.r2d2.slice1' users_query = Query().get('myslice:slice').filter_by( 'slice_hrn', '==', slice_hrn).select('users.user_hrn', 'users.user_urn', 'users.user_email', 'users.keys') users = execute_admin_query(request, users_query) rmap = {'user_urn': 'urn', 'user_email': 'email', 'user_hrn': 'hrn'} res = list() for u in users[0]['users']: r_user = dict() for k, v in u.items(): if k in rmap.keys(): r_user[rmap[k]] = v else: r_user[k] = v res.append(r_user) return res
def get(self, request, slicename): if request.user.is_authenticated(): # user_query = Query().get('user').select('user_hrn','parent_authority').filter_by('user_hrn','==','$user_hrn') #user_details = execute_query(self.request, user_query) # if sfa returns None #if user_details[0]['parent_authority'] is None: # find in local DB user_query = Query().get('local:user').select('config') user_details = execute_query(request, user_query) for user_config in user_details: config = json.loads(user_config['config']) config['authority'] = config.get('authority') user_details[0]['parent_authority'] = config['authority'] return render_to_response(self.template, { "slice": slicename, "user_details": user_details[0], "theme": self.theme, "username": request.user, "section": "users" }, context_instance=RequestContext(request))
def make_tdmi_router(): """ Prepare a TDMI router/ Returns: The corresponding Router instance. """ # Fetch tdmi configuration from myslice storage platforms = DBStorage.execute(Query().get("platform").filter_by( Predicate("platform", eq, "tdmi")), format="dict") if len(platforms) == 1: platform = platforms[0] else: # TODO: we should use this account #'db_user' : '*****@*****.**' #'db_password' : 'guest' print """No information found about TDMI in the storage, you should run: manifold-add-platform "tdmi" "Tophat Dedicated Measurement Infrastructure" "TDMI" "none" '{"db_host": "132.227.62.103", "db_port": 5432, "db_user": "******", "db_password": null, "db_name": "tophat", "name" : "TopHat team", "mail_support_address" : "xxx@xxx" }' 1 """ sys.exit(-1) # Our Forwarder does not need any capability since pgsql is return Router(platforms)
def main(): argc = len(sys.argv) if argc != 5: usage() sys.exit(1) user, platform, type, config = sys.argv[1:5] account_params = { 'user': user, 'platform': platform, 'auth_type': type, 'config': config } print "------------<<<", account_params print "U---------------", user print "P---------------", platform query = Query(action='create', object='local:account', params=account_params) print "Q---------------", query # Instantiate a TopHat router with Router() as router: router.forward(query)
def main(): argc = len(sys.argv) if argc < 3: usage() sys.exit(1) print "PLEASE BACKUP THE DB BEFORE USING THIS COMMAND" answer = query_yes_no("Are you sure you want to continue?") if answer: platform = sys.argv[1] ref_platform = sys.argv[2] if argc == 4: user = sys.argv[3] create_ref_account(user, platform, ref_platform) else: # Get ALL active users query = Query().get('local:user').select('email').filter_by( 'status', '==', 2) with Router() as router: results = router.forward(query) for r in results['value']: create_ref_account(r['email'], platform, ref_platform, router) else: print "Exit"
def get(self, request, slicename, state=None): username = self.request.user pf_query = Query().get('local:platform').filter_by( 'disabled', '==', '0').filter_by('gateway_type', '==', 'sfa').select('platform') res_platforms = execute_query(request, pf_query) platforms = [p['platform'] for p in res_platforms] len_platforms = len(platforms) #query_current_resources = Query.get('slice').select('resource','parent_authority').filter_by('slice_hrn','==',slicename) #current_resources = execute_query(request, query_current_resources) #parent_authority = current_resources[0]['parent_authority'] # #split_slicename = slicename.split('.') #ple_slicename = hash_loginbase(parent_authority) + '_' + split_slicename[-1] #ple_resource_list=[] #nitos_resource_list=[] #nitos_paris_resource_list=[] #iotlab_resource_list=[] #try: # for resources in current_resources: # list_res = resources['resource'] # for res in list_res: # split_list = res.split('+') # split the resource urn # if [s for s in split_list if 'ple' in s]: # find ple resources # res_hrn = split_list[-1] # last element is resource hrn # ple_resource_list.append(res_hrn) # if [s for s in split_list if 'omf:paris.fit-nitos.fr' in s]: # find nitos_paris resources # res_hrn = split_list[-1] # last element is resource hrn # nitos_paris_resource_list.append(res_hrn) # if [s for s in split_list if 'iotlab' in s]: # find iotlab resources # res_hrn = split_list[-1] # last element is resource hrn # iotlab_resource_list.append(res_hrn) # if [s for s in split_list if 'omf:nitos.indoor' in s]: # find nitos_indoor resources # res_hrn = split_list[-1] # last element is resource hrn # nitos_resource_list.append(res_hrn) # if [s for s in split_list if 'omf:nitos.outdoor' in s]: # find nitos_outdoor resources # res_hrn = split_list[-1] # last element is resource hrn # nitos_resource_list.append(res_hrn) #except Exception as e: # logger.error("Exception in slicetabexperiment.py in OneLab resource search {}".format(e)) # ##logger.debug("list of ple res hrns") ##logger.debug(ple_resource_list) ##logger.debug("list of nit_paris res hrns") ##logger.debug(nitos_paris_resource_list) ##logger.debug("list of iotLab res hrns") ##logger.debug(iotlab_resource_list) ##logger.debug("list of nitos res hrns") ##logger.debug(nitos_resource_list) #all_users = list() ##get all iotlab users #all_users = list() #try: # engine = ConfigEngine() # userData = "Basic " + (engine.iotlab_admin_user() + ":" + engine.iotlab_admin_password()).encode("base64").rstrip() # req = urllib2.Request(engine.iotlab_url()) # req.add_header('Accept', 'application/json') # req.add_header("Content-type", "application/x-www-form-urlencoded") # req.add_header('Authorization', userData) # # make the request and print the results # res = urllib2.urlopen(req) # all_users = json.load(res) #except urllib2.URLError as e: # logger.error("There is a problem in getting iotlab users {}".format(e.reason)) ##getting the login from email ##initial value no-account == contact_admin #iot_login = '******' #username = str(username) #for user in all_users: # if user['email'] == username: # iot_login = user['login'] env = { 'theme': self.theme, 'slicename': slicename, 'platforms': platforms, 'len_platforms': len_platforms, #'ple_slicename':ple_slicename, #'username':username, #'ple_resources':ple_resource_list, #'nitos_resources': nitos_resource_list, #'nitos_paris_resources':nitos_paris_resource_list, #'iotlab_resources':iotlab_resource_list, #'iot_login':iot_login, 'request': self.request, } return render_to_response(self.template, env, context_instance=RequestContext(request))
def password_reset(request, is_admin_site=False, template_name='password_reset_form.html', email_template_name='password_reset_email.html', subject_template_name='registration/password_reset_subject.txt', password_reset_form=PasswordResetForm, token_generator=default_token_generator, post_reset_redirect=None, from_email=None, current_app=None, extra_context=None): themeview = ThemeView() themeview.template_name = template_name if post_reset_redirect is None: post_reset_redirect = reverse('portal.django_passresetview.password_reset_done') if request.method == "POST": form = password_reset_form(request.POST) if form.is_valid(): ### email check in manifold DB ### email = form.cleaned_data['email'].lower() # email inserted on the form user_query = Query().get('local:user').select('user_id','email') user_details = execute_admin_query(request, user_query) flag = 0 for user_detail in user_details: if user_detail['email']==email: flag = 1 break if flag == 0: messages.error(request, 'Sorry, this email is not registered.') context = { 'form': form, 'theme': themeview.theme } return TemplateResponse(request, themeview.template, context,current_app=current_app) ### end of email check in manifold ### opts = { 'use_https': request.is_secure(), 'token_generator': token_generator, 'from_email': from_email, 'email_template_name': email_template_name, 'subject_template_name': subject_template_name, 'request': request, } if is_admin_site: opts = dict(opts, domain_override=request.get_host()) form.save(**opts) return HttpResponseRedirect(post_reset_redirect) else: form = password_reset_form() context = { 'form': form, 'theme': themeview.theme } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, themeview.template, context, current_app=current_app)
def get_or_post(self, request, method): errors = [] # List authorities already in the Registry in order to avoid duplicates # Using cache manifold-tables to get the list of authorities faster authorities_query = Query.get('authority').select( 'name', 'authority_hrn') authorities = execute_admin_query(request, authorities_query) if authorities is not None: authorities = sorted(authorities) root_authorities = sorted( [a for a in authorities if '.' not in a['authority_hrn']]) page = Page(request) page.add_js_files( ["js/jquery.validate.js", "js/join.js", "js/jquery.qtip.min.js"]) page.add_css_files([ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css" ]) page.add_css_files([ "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ]) if method == 'POST': # xxx tocheck - if authorities is empty, it's no use anyway # (users won't be able to validate the form anyway) # List local users in Manifold DB in order ot avoid duplicates user_query = Query().get('local:user').select('user_id', 'email') list_users = execute_admin_query(self.request, user_query) reg_root_authority_hrn = request.POST.get('root_authority_hrn', '').lower() reg_site_name = request.POST.get('site_name', '') reg_site_authority = request.POST.get('site_authority', '').lower() reg_site_abbreviated_name = request.POST.get( 'site_abbreviated_name', '').lower() reg_site_url = request.POST.get('site_url', '') reg_site_latitude = request.POST.get('site_latitude', '') reg_site_longitude = request.POST.get('site_longitude', '') reg_fname = request.POST.get('pi_first_name', '') reg_lname = request.POST.get('pi_last_name', '') reg_auth = 'onelab.' + reg_site_abbreviated_name reg_email = request.POST.get('pi_email', '').lower() reg_phone = request.POST.get('pi_phone', '') #prepare user_hrn split_email = reg_email.split("@")[0] split_email = split_email.replace(".", "_") # Replace + by _ => more convenient for testing and validate with a real email split_email = split_email.replace("+", "_") user_hrn = reg_auth + '.' + split_email UserModel = get_user_model() reg_address_line1 = request.POST.get('address_line1', '') reg_address_line2 = request.POST.get('address_line2', '') reg_address_line3 = request.POST.get('address_line3', '') reg_address_city = request.POST.get('address_city', '') reg_address_postalcode = request.POST.get('address_postalcode', '') reg_address_state = request.POST.get('address_state', '') reg_address_country = request.POST.get('address_country', '') #POST value validation if (re.search(r'^[\w+\s.@+-]+$', reg_fname) == None): errors.append( 'First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.' ) if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None): errors.append( 'Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.' ) if (re.search(r'^[A-Za-z0-9_ ]*$', reg_site_name) == None): errors.append( 'Name of organization may contain only letters, numbers, and underscore.' ) if (re.search(r'^[A-Za-z ]*$', reg_address_city) == None): errors.append('City may contain only letters.') if (re.search(r'^[A-Za-z ]*$', reg_address_country) == None): errors.append('Country may contain only letters.') if (re.search(r'^[A-Za-z0-9]*$', reg_site_abbreviated_name) == None): errors.append( 'Shortname may contain only letters and numbers') if (re.search(r'^[0-9]*$', reg_phone) == None): errors.append('Phone number may contain only numbers.') #if (re.search(r'^\w+$', reg_site_authority) == None): # errors.append('Site Authority may contain only letters or numbers.') # checking in django_db !! if PendingUser.objects.filter(email__iexact=reg_email): errors.append( 'Email is pending for validation. Please provide a new email address.' ) if PendingAuthority.objects.filter( site_abbreviated_name__iexact=reg_site_abbreviated_name): errors.append('This site is pending for validation.') #if PendingAuthority.objects.filter(site_name__iexact=reg_site_name): # errors.append('This site is pending for validation.') if UserModel._default_manager.filter(email__iexact=reg_email): errors.append( 'This email is not usable. Please contact the administrator or try with another email.' ) for user_detail in list_users: if user_detail['email'] == reg_email: errors.append( 'Email already registered in Manifold. Please provide a new email address.' ) # XXX TODO: Factorize with portal/accountview.py # XXX TODO: Factorize with portal/registrationview.py # XXX TODO: Factorize with portal/joinview.py # if 'generate' in request.POST['question']: from Crypto.PublicKey import RSA private = RSA.generate(1024) private_key = private.exportKey() public_key = private.publickey().exportKey(format='OpenSSH') # Saving to DB auth_type = 'managed' if not errors: reg_password = request.POST['pi_password'] a = PendingAuthority( site_name=reg_site_name, site_authority=reg_auth, site_abbreviated_name=reg_site_abbreviated_name, site_url=reg_site_url, site_latitude=reg_site_latitude, site_longitude=reg_site_longitude, address_line1= reg_email, # XXX field name must be renamed. Email needed 4 rejection email. address_line2=reg_address_line2, address_line3=reg_address_line3, address_city=reg_address_city, address_postalcode=reg_address_postalcode, address_state=reg_address_state, address_country=reg_address_country, authority_hrn=reg_root_authority_hrn, ) a.save() reg_password = request.POST['pi_password'] salt = randint(1, 100000) if request.is_secure(): current_site = 'https://' else: current_site = 'http://' current_site += request.META['HTTP_HOST'] email_hash = md5(str(salt) + reg_email).hexdigest() user_request = { 'first_name': reg_fname, 'last_name': reg_lname, 'organization': reg_site_name, 'authority_hrn': reg_auth, 'email': reg_email, 'password': reg_password, 'public_key': public_key, 'private_key': private_key, 'current_site': current_site, 'email_hash': email_hash, 'user_hrn': user_hrn, 'pi': [reg_auth], 'auth_type': 'managed', 'validation_link': current_site + '/portal/email_activation/' + email_hash } create_pending_user(request, user_request, user_detail) # saves the user to django auth_user table [needed for password reset] #user = User.objects.create_user(reg_email, reg_email, reg_password) #creating user to manifold local:user #user_config = '{"first_name":"'+ reg_fname + '", "last_name":"'+ reg_lname + '", "authority_hrn":"'+ reg_auth + '"}' #user_params = {'email': reg_email, 'password': reg_password, 'config': user_config, 'status': 1} #manifold_add_user(request,user_params) #creating local:account in manifold #user_id = user_detail['user_id']+1 # the user_id for the newly created user in local:user #account_params = {'platform_id': 5, 'user_id': user_id, 'auth_type': auth_type, 'config': account_config} #manifold_add_account(request,account_params) # Send email try: ctx = { 'site_name': reg_site_name, 'authority_hrn': reg_root_authority_hrn + '.' + reg_site_authority, 'site_abbreviated_name': reg_site_abbreviated_name, 'site_url': reg_site_url, 'address_city': reg_address_city, 'address_country': reg_address_country, 'first_name': reg_fname, 'last_name': reg_lname, 'authority_hrn': reg_auth, 'email': reg_email, 'user_hrn': user_hrn, 'public_key': public_key, } #recipients = authority_get_pi_emails(request,reg_auth) self.template_name = 'authority_request_email.html' html_content = render_to_string(self.template, ctx) self.template_name = 'authority_request_email.txt' text_content = render_to_string(self.template, ctx) self.template_name = 'authority_request_email_subject.txt' subject = render_to_string(self.template, ctx) subject = subject.replace('\n', '') #theme.template_name = 'email_default_sender.txt' #sender = render_to_string(theme.template, ctx) #sender = sender.replace('\n', '') sender = reg_email msg = EmailMultiAlternatives(subject, text_content, sender, ['*****@*****.**']) msg.attach_alternative(html_content, "text/html") msg.send() except Exception, e: logger.error( "Failed to send email, please check the mail templates and the SMTP configuration of your server" ) import traceback logger.error(traceback.format_exc()) self.template_name = 'join_complete.html' # log institution activity activity.institution.joined(self.request) return render(request, self.template, {'theme': self.theme})
""" class account { user user; platform platform; CAPABILITY(fullquery); KEY(user,platform); }; """ # XXX infinite number of fields can be stored # XXX local table / all local fields, no normalization if __name__ == '__main__': import pprint from manifold.core.query import Query from manifold.input.sql import SQLParser l = ConfGateway() sql_queries = [ 'SELECT dummy FROM account WHERE email == "*****@*****.**" && platform == "ple"', # manifold-add-account 'INSERT INTO account SET email = "*****@*****.**", platform = "ple", auth_type = "sfa", dummy = "dummycontent"', ] for sql in sql_queries: q = Query(SQLParser().parse(sql)) print "query:", q records = l.forward(q) pprint.pprint(records) print "-" * 80
def get_context_data(self, **kwargs): pi = "" # We might have slices on different registries with different user accounts # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn #messages.info(self.request, 'You have logged in') page = Page(self.request) ctx_my_authorities = {} ctx_delegation_authorities = {} ctx_sub_authorities = {} dest = {} # The user need to be logged in if the_user(self.request): # Who can a PI validate: # His own authorities + those he has credentials for. # In MySlice we need to look at credentials also. # XXX This will have to be asynchroneous. Need to implement barriers, # for now it will be sufficient to have it working statically # get user_id to later on query accounts # XXX Having real query plan on local tables would simplify all this # XXX $user_email is still not available for local tables #user_query = Query().get('local:user').filter_by('email', '==', '$user_email').select('user_id') user_query = Query().get('local:user').filter_by( 'email', '==', the_user(self.request)).select('user_id') user, = execute_query(self.request, user_query) user_id = user['user_id'] # Query manifold to learn about available SFA platforms for more information # In general we will at least have the portal # For now we are considering all registries all_authorities = [] platform_ids = [] sfa_platforms_query = Query().get('local:platform').filter_by( 'gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type') sfa_platforms = execute_query(self.request, sfa_platforms_query) for sfa_platform in sfa_platforms: logger.info("SFA PLATFORM > {}".format( sfa_platform['platform'])) if not 'auth_type' in sfa_platform: continue auth = sfa_platform['auth_type'] if not auth in all_authorities: all_authorities.append(auth) platform_ids.append(sfa_platform['platform_id']) logger.warning("W: Hardcoding platform myslice") # There has been a tweak on how new platforms are referencing a # so-called 'myslice' platform for storing authentication tokens. # XXX This has to be removed in final versions. myslice_platforms_query = Query().get('local:platform').filter_by( 'platform', '==', 'myslice').select('platform_id') myslice_platforms = execute_query(self.request, myslice_platforms_query) if myslice_platforms: myslice_platform, = myslice_platforms platform_ids.append(myslice_platform['platform_id']) # We can check on which the user has authoritity credentials = PI rights credential_authorities = set() credential_authorities_expired = set() # User account on these registries user_accounts_query = Query.get('local:account').filter_by( 'user_id', '==', user_id).filter_by('platform_id', 'included', platform_ids).select('auth_type', 'config') user_accounts = execute_query(self.request, user_accounts_query) #print "=" * 80 #print user_accounts #print "=" * 80 for user_account in user_accounts: logger.debug("USER ACCOUNT {}".format(user_account)) if user_account['auth_type'] == 'reference': continue # we hardcoded the myslice platform... config = json.loads(user_account['config']) creds = [] logger.debug("CONFIG KEYS {}".format(config.keys())) if 'authority_credentials' in config: logger.debug("*** AC {}".format( config['authority_credentials'].keys())) for authority_hrn, credential in config[ 'authority_credentials'].items(): #if credential is not expired: credential_authorities.add(authority_hrn) #else # credential_authorities_expired.add(authority_hrn) if 'delegated_authority_credentials' in config: logger.debug("*** DAC {}".format( config['delegated_authority_credentials'].keys())) for authority_hrn, credential in config[ 'delegated_authority_credentials'].items(): #if credential is not expired: credential_authorities.add(authority_hrn) #else # credential_authorities_expired.add(authority_hrn) logger.debug( 'credential_authorities = {}'.format(credential_authorities)) logger.debug('credential_authorities_expired = {}'.format( credential_authorities_expired)) # # Using cache manifold-tables to get the list of authorities faster # all_authorities_query = Query.get('authority').select('name', 'authority_hrn') # all_authorities = execute_query(self.request, all_authorities_query) # ** Where am I a PI ** # For this we need to ask SFA (of all authorities) = PI function pi_authorities_query = Query.get('myslice:user').filter_by( 'user_hrn', '==', '$user_hrn').select('pi_authorities') pi_authorities_tmp = execute_query(self.request, pi_authorities_query) pi_authorities = set() try: for pa in pi_authorities_tmp: pi_authorities |= set(pa['pi_authorities']) except Exception as e: logger.error('No pi_authorities') # TODO: exception if no parent_authority # try: # for pa in pi_authorities_tmp: # pi_authorities |= set(pa['pi_authorities']) # except: # # include all sub-authorities of the PI # # if PI on ple, include all sub-auths ple.upmc, ple.inria and so on... # pi_subauthorities = set() # for authority in all_authorities: # authority_hrn = authority['authority_hrn'] # for my_authority in pi_authorities: # if authority_hrn.startswith(my_authority) and authority_hrn not in pi_subauthorities: # pi_subauthorities.add(authority_hrn) #print "pi_authorities =", pi_authorities #print "pi_subauthorities =", pi_subauthorities # My authorities + I have a credential pi_credential_authorities = pi_authorities & credential_authorities pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired pi_expired_credential_authorities = pi_authorities & credential_authorities_expired # Authorities I've been delegated PI rights pi_delegation_credential_authorities = credential_authorities - pi_authorities pi_delegation_expired_authorities = credential_authorities_expired - pi_authorities #print "pi_credential_authorities =", pi_credential_authorities #print "pi_no_credential_authorities =", pi_no_credential_authorities #print "pi_expired_credential_authorities =", pi_expired_credential_authorities #print "pi_delegation_credential_authorities = ", pi_delegation_credential_authorities #print "pi_delegation_expired_authorities = ", pi_delegation_expired_authorities # Summary intermediary pi_my_authorities = pi_credential_authorities | pi_no_credential_authorities | pi_expired_credential_authorities pi_delegation_authorities = pi_delegation_credential_authorities | pi_delegation_expired_authorities #print "--" #print "pi_my_authorities = ", pi_my_authorities #print "pi_delegation_authorities = ", pi_delegation_authorities #print "pi_subauthorities = ", pi_subauthorities # Summary all queried_pending_authorities = pi_my_authorities | pi_delegation_authorities #| pi_subauthorities #print "----" #print "queried_pending_authorities = ", queried_pending_authorities # iterate on the requests and check if the authority matches a prefix startswith an authority on which the user is PI requests = get_requests() # requests = get_requests(queried_pending_authorities) for request in requests: auth_hrn = request['authority_hrn'] for my_auth in pi_my_authorities: if auth_hrn.startswith(my_auth): dest = ctx_my_authorities request['allowed'] = 'allowed' for my_auth in pi_delegation_authorities: if auth_hrn.startswith(my_auth): dest = ctx_delegation_authorities request['allowed'] = 'allowed' if auth_hrn in pi_expired_credential_authorities: request['allowed'] = 'expired' if 'allowed' not in request: request['allowed'] = 'denied' #print "authority for this request", auth_hrn # if auth_hrn in pi_my_authorities: # dest = ctx_my_authorities # # # define the css class # if auth_hrn in pi_credential_authorities: # request['allowed'] = 'allowed' # elif auth_hrn in pi_expired_credential_authorities: # request['allowed'] = 'expired' # else: # pi_no_credential_authorities # request['allowed'] = 'denied' # # elif auth_hrn in pi_delegation_authorities: # dest = ctx_delegation_authorities # # if auth_hrn in pi_delegation_credential_authorities: # request['allowed'] = 'allowed' # else: # pi_delegation_expired_authorities # request['allowed'] = 'expired' # # elif auth_hrn in pi_subauthorities: # dest = ctx_sub_authorities # # if auth_hrn in pi_subauthorities: # request['allowed'] = 'allowed' # else: # pi_delegation_expired_authorities # request['allowed'] = 'denied' # # else: # continue if not auth_hrn in dest: dest[auth_hrn] = [] dest[auth_hrn].append(request) context = super(ValidatePendingView, self).get_context_data(**kwargs) logger.debug("testing") logger.debug(ctx_my_authorities) context['my_authorities'] = ctx_my_authorities context['sub_authorities'] = ctx_sub_authorities context['delegation_authorities'] = ctx_delegation_authorities # XXX This is repeated in all pages # more general variables expected in the template context['title'] = 'Test view that combines various plugins' # the menu items on the top context['topmenu_items'] = topmenu_items_live('Validation', page) # so we can sho who is logged context['username'] = the_user(self.request) context['pi'] = "is_pi" context['theme'] = self.theme context['section'] = "Requests" # XXX We need to prepare the page for queries #context.update(page.prelude_env()) return context
def get_query(self): """ \brief Returns the query representing the data produced by the nodes. \return query representing the data produced by the nodes. """ return Query(self.child.get_query())