Exemple #1
0
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]
Exemple #2
0
def dispatch(request, action):

    results = []
    error = None
    try:
        if request.method == 'POST':
            req_items = request.POST
        elif request.method == 'GET':
            req_items = request.GET

        for el in req_items.items():
            if el[0].startswith('slice_hrn'):
                slice_hrn = el[1]
            elif el[0].startswith('initscript_code'):
                initscript_code = el[1]

        if (action == 'get'):
            # select initscript_code from initscript where slice_hrn=='onelab.upmc.express'
            query = Query.get('initscript').filter_by(
                'slice_hrn', '==', slice_hrn).select('initscript_code')
            results = execute_admin_query(request, query)

        if (action == 'update'):
            # UPDATE initscript SET initscript_code='test3' where slice_hrn=='onelab.upmc.express'
            params = {'initscript_code': initscript_code}
            query = Query.update('initscript').filter_by(
                'slice_hrn', '==', slice_hrn).set(params)
            results = execute_admin_query(request, query)

            if results[0]['initscript_code'] == 1:
                results[0]['initscript_code'] = initscript_code
            else:
                error = "Error in update return value"

        if (action == 'delete'):
            # delete from initscript where slice_hrn=='onelab.upmc.express'
            query = Query.delete('initscript').filter_by(
                'slice_hrn', '==', slice_hrn)
            results = execute_admin_query(request, query)

            if results[0]['initscript_code'] == 1:
                results[0]['initscript_code'] = ""
            else:
                error = "Error in delete return value"
    except Exception, e:
        error = str(e)
Exemple #3
0
    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))
Exemple #4
0
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 is_ple_enabled(self, pending_user):
        pending_authorities = PendingAuthority.objects.filter(
            site_authority__iexact=pending_user.authority_hrn)
        if pending_authorities:
            return False
        pending_user_email = pending_user.email
        try:
            query = Query.get('myplcuser').filter_by(
                'email', '==', pending_user_email).select('enabled')
            results = execute_admin_query(self.request, query)
            for result in results:
                # User is enabled in PLE
                if 'enabled' in result and result['enabled'] == True:
                    return True
        except Exception as e:
            logger.error("Exception in myplc query = {}".format(e))

        return False
Exemple #6
0
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
Exemple #7
0
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)
Exemple #8
0
    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})
Exemple #9
0
                split_email = user_request['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_request['user_hrn'] = user_request['authority_hrn'] \
                         + '.' + split_email
                
                # Validate input
                UserModel = get_user_model()
                if (re.search(r'^[\w+\s.@+-]+$', user_request['first_name']) == None):
                    errors.append('First name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
                if (re.search(r'^[\w+\s.@+-]+$', user_request['last_name']) == None):
                    errors.append('Last name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
                # Does the user exist in Manifold?
                user_query  = Query().get('local:user').select('user_id','email')
                user_details = execute_admin_query(wsgi_request, user_query)
                for user_detail in user_details:
                    if user_detail['email'] == user_request['email']:
                        errors.append('Email already registered. <a href="/">Login</a> with your existing account. <a href="/portal/pass_reset/">Forgot your password?</a>')

                # Does the user exist in sfa? [query is very slow!!]
                #user_query  = Query().get('user').select('user_hrn','user_email')
                # XXX Test based on the user_hrn is quick

                # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
                user_query  = Query().get('myslice:user').select('user_hrn','user_email').filter_by('user_hrn','==',user_request['user_hrn'])
                user_details_sfa = execute_admin_query(wsgi_request, user_query)

                for user in user_details_sfa:
                    if user['user_email'] == user_request['email']:
                        errors.append('Email already registered in OneLab registry. <a href="/contact">Contact OneLab support</a> or use another email.')
Exemple #10
0
    def get_context_data(self, **kwargs):

        page = Page(self.request)
        page.add_js_files([
            "js/jquery.validate.js", "js/my_account.register.js",
            "js/my_account.edit_profile.js", "js/jquery-ui.js"
        ])
        page.add_css_files([
            "css/onelab.css", "css/account_view.css", "css/plugin.css",
            "css/jquery-ui.css"
        ])

        for key, value in kwargs.iteritems():
            if key == "email":
                selected_email = value

        user_query = Query().get('local:user').filter_by(
            'email', '==', selected_email).select('user_id', 'config', 'email',
                                                  'status')
        user_details = execute_admin_query(self.request, user_query)

        # not always found in user_details...
        config = {}
        for user_detail in user_details:
            user_id = user_detail['user_id']
            user_email = user_detail['email']
            # different significations of user_status
            if user_detail['status'] == 0:
                user_status = 'Disabled'
            elif user_detail['status'] == 1:
                user_status = 'Validation Pending'
            elif user_detail['status'] == 2:
                user_status = 'Enabled'
            else:
                user_status = 'N/A'
            #email = user_detail['email']
            if user_detail['config']:
                config = json.loads(user_detail['config'])
                authority_hrn = config.get('authority', 'Unknown Authority')

        platform_query = Query().get('local:platform').select(
            'platform_id', 'platform', 'gateway_type', 'disabled')
        account_query = Query().get('local:account').filter_by(
            'user_id', '==', user_id).select('user_id', 'platform_id',
                                             'auth_type', 'config')
        platform_details = execute_query(self.request, platform_query)
        account_details = execute_admin_query(self.request, account_query)

        # initial assignment needed for users having account.config = {}
        platform_name = ''
        account_type = ''
        account_usr_hrn = ''
        account_pub_key = ''
        account_priv_key = ''
        account_reference = ''
        my_users = ''
        my_slices = ''
        my_auths = ''
        ref_acc_list = ''
        principal_acc_list = ''
        user_status_list = []
        platform_name_list = []
        platform_name_secondary_list = []
        platform_access_list = []
        platform_no_access_list = []
        total_platform_list = []
        account_type_list = []
        account_type_secondary_list = []
        account_reference_list = []
        delegation_type_list = []
        user_cred_exp_list = []
        slice_list = []
        auth_list = []
        slice_cred_exp_list = []
        auth_cred_exp_list = []
        usr_hrn_list = []
        pub_key_list = []

        for platform_detail in platform_details:
            if 'sfa' in platform_detail['gateway_type']:
                total_platform = platform_detail['platform']
                total_platform_list.append(total_platform)

            for account_detail in account_details:
                if platform_detail['platform_id'] == account_detail[
                        'platform_id']:
                    platform_name = platform_detail['platform']
                    if 'config' in account_detail and account_detail[
                            'config'] is not '':
                        account_config = json.loads(account_detail['config'])
                        account_usr_hrn = account_config.get('user_hrn', 'N/A')
                        account_pub_key = account_config.get(
                            'user_public_key', 'N/A')
                        account_reference = account_config.get(
                            'reference_platform', 'N/A')

                    # credentials of myslice platform
                    if 'myslice' in platform_detail['platform']:
                        acc_user_cred = account_config.get(
                            'delegated_user_credential', 'N/A')
                        acc_slice_cred = account_config.get(
                            'delegated_slice_credentials', 'N/A')
                        acc_auth_cred = account_config.get(
                            'delegated_authority_credentials', 'N/A')
                        #usr_hrn of myslice platform. used to check pi or no
                        account_usr_hrn_myslice = account_config.get(
                            'user_hrn', 'N/A')

                        if 'N/A' not in acc_user_cred:
                            exp_date = re.search('<expires>(.*)</expires>',
                                                 acc_user_cred)
                            if exp_date:
                                user_exp_date = exp_date.group(1)
                                user_cred_exp_list.append(user_exp_date)

                            my_users = [{
                                'cred_exp': t[0]
                            } for t in zip(user_cred_exp_list)]

                        if 'N/A' not in acc_slice_cred:
                            for key, value in acc_slice_cred.iteritems():
                                slice_list.append(key)
                                # get cred_exp date
                                exp_date = re.search('<expires>(.*)</expires>',
                                                     value)
                                if exp_date:
                                    exp_date = exp_date.group(1)
                                    slice_cred_exp_list.append(exp_date)

                            my_slices = [{
                                'slice_name': t[0],
                                'cred_exp': t[1]
                            } for t in zip(slice_list, slice_cred_exp_list)]

                        if 'N/A' not in acc_auth_cred:
                            for key, value in acc_auth_cred.iteritems():
                                auth_list.append(key)
                                #get cred_exp date
                                exp_date = re.search('<expires>(.*)</expires>',
                                                     value)
                                if exp_date:
                                    exp_date = exp_date.group(1)
                                    auth_cred_exp_list.append(exp_date)

                            my_auths = [{
                                'auth_name': t[0],
                                'cred_exp': t[1]
                            } for t in zip(auth_list, auth_cred_exp_list)]

                    # for reference accounts
                    if 'reference' in account_detail['auth_type']:
                        account_type = 'Reference'
                        delegation = 'N/A'
                        platform_name_secondary_list.append(platform_name)
                        account_type_secondary_list.append(account_type)
                        account_reference_list.append(account_reference)
                        ref_acc_list = [{
                            'platform_name': t[0],
                            'account_type': t[1],
                            'account_reference': t[2]
                        } for t in zip(platform_name_secondary_list,
                                       account_type_secondary_list,
                                       account_reference_list)]

                    elif 'managed' in account_detail['auth_type']:
                        account_type = 'Principal'
                        delegation = 'Automatic'
                    else:
                        account_type = 'Principal'
                        delegation = 'Manual'
                    # for principal (auth_type=user/managed) accounts
                    if 'reference' not in account_detail['auth_type']:
                        platform_name_list.append(platform_name)
                        account_type_list.append(account_type)
                        delegation_type_list.append(delegation)
                        usr_hrn_list.append(account_usr_hrn)
                        pub_key_list.append(account_pub_key)
                        user_status_list.append(user_status)
                        # combining 5 lists into 1 [to render in the template]
                        principal_acc_list = [{
                            'platform_name': t[0],
                            'account_type': t[1],
                            'delegation_type': t[2],
                            'usr_hrn': t[3],
                            'usr_pubkey': t[4],
                            'user_status': t[5],
                        } for t in zip(platform_name_list, account_type_list,
                                       delegation_type_list, usr_hrn_list,
                                       pub_key_list, user_status_list)]
                    # to hide private key row if it doesn't exist
                    if 'myslice' in platform_detail['platform']:
                        account_config = json.loads(account_detail['config'])
                        account_priv_key = account_config.get(
                            'user_private_key', 'N/A')
                    if 'sfa' in platform_detail['gateway_type']:
                        platform_access = platform_detail['platform']
                        platform_access_list.append(platform_access)

        # Removing the platform which already has access
        for platform in platform_access_list:
            total_platform_list.remove(platform)
        # we could use zip. this one is used if columns have unequal rows
        platform_list = [{
            'platform_no_access': t[0]
        } for t in itertools.izip_longest(total_platform_list)]

        ## check pi or no
        pi_status = self.request.session['user']['pi']

        context = super(UserView, self).get_context_data(**kwargs)
        context['principal_acc'] = principal_acc_list
        context['ref_acc'] = ref_acc_list
        context['platform_list'] = platform_list
        context['my_users'] = my_users
        context['my_slices'] = my_slices
        context['my_auths'] = my_auths
        context['user_status'] = user_status
        context['user_email'] = user_email
        context['firstname'] = config.get('firstname', "?")
        context['lastname'] = config.get('lastname', "?")
        context['fullname'] = context['firstname'] + ' ' + context['lastname']
        context['authority'] = config.get('authority', "Unknown Authority")
        context['user_private_key'] = account_priv_key
        context['pi'] = pi_status

        # 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('My Account', page)
        # so we can sho who is logged
        context['username'] = the_user(self.request)
        context['theme'] = self.theme
        #        context ['firstname'] = config['firstname']
        prelude_env = page.prelude_env()
        context.update(prelude_env)
        return context
Exemple #11
0
def user_process(request, **kwargs):

    for key, value in kwargs.iteritems():
        if key == "email":
            selected_email = value

    redirect_url = "/portal/user/" + selected_email

    user_query = Query().get('local:user').filter_by(
        'email', '==', selected_email).select('user_id', 'email', 'password',
                                              'config')
    user_details = execute_admin_query(request, user_query)

    # getting the user_id from the session
    for user_detail in user_details:
        user_id = user_detail['user_id']
        user_email = user_detail['email']

    account_query = Query().get('local:account').filter_by(
        'user_id', '==', user_id).select('user_id', 'platform_id', 'auth_type',
                                         'config')
    account_details = execute_admin_query(request, account_query)

    platform_query = Query().get('local:platform').select(
        'platform_id', 'platform')
    platform_details = execute_admin_query(request, platform_query)

    for account_detail in account_details:
        for platform_detail in platform_details:
            # Add reference account to the platforms
            if 'add_' + platform_detail['platform'] in request.POST:
                platform_id = platform_detail['platform_id']
                user_params = {
                    'platform_id': platform_id,
                    'user_id': user_id,
                    'auth_type': "reference",
                    'config': '{"reference_platform": "myslice"}'
                }
                manifold_add_account(request, user_params)
                messages.info(
                    request,
                    'Reference Account is added to the selected platform successfully!'
                )
                return HttpResponseRedirect(redirect_url)

            # Delete reference account from the platforms
            if 'delete_' + platform_detail['platform'] in request.POST:
                platform_id = platform_detail['platform_id']
                user_params = {'user_id': user_id}
                manifold_delete_account(request, platform_id, user_id,
                                        user_params)
                messages.info(
                    request,
                    'Refeence Account is removed from the selected platform')
                return HttpResponseRedirect(redirect_url)

            if platform_detail['platform_id'] == account_detail['platform_id']:
                if 'myslice' in platform_detail['platform']:
                    account_config = json.loads(account_detail['config'])
                    acc_slice_cred = account_config.get(
                        'delegated_slice_credentials', 'N/A')
                    acc_auth_cred = account_config.get(
                        'delegated_authority_credentials', 'N/A')

                    # adding the slices and corresponding credentials to list
                    if 'N/A' not in acc_slice_cred:
                        slice_list = []
                        slice_cred = []
                        for key, value in acc_slice_cred.iteritems():
                            slice_list.append(key)
                            slice_cred.append(value)
                        # special case: download each slice credentials separately
                        for i in range(0, len(slice_list)):
                            if 'dl_' + slice_list[i] in request.POST:
                                slice_detail = "Slice name: " + slice_list[
                                    i] + "\nSlice Credentials: \n" + slice_cred[
                                        i]
                                response = HttpResponse(
                                    slice_detail, content_type='text/plain')
                                response[
                                    'Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
                                return response

                    # adding the authority and corresponding credentials to list
                    if 'N/A' not in acc_auth_cred:
                        auth_list = []
                        auth_cred = []
                        for key, value in acc_auth_cred.iteritems():
                            auth_list.append(key)
                            auth_cred.append(value)
                        # special case: download each slice credentials separately
                        for i in range(0, len(auth_list)):
                            if 'dl_' + auth_list[i] in request.POST:
                                auth_detail = "Authority: " + auth_list[
                                    i] + "\nAuthority Credentials: \n" + auth_cred[
                                        i]
                                response = HttpResponse(
                                    auth_detail, content_type='text/plain')
                                response[
                                    'Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
                                return response

    if 'submit_name' in request.POST:
        edited_first_name = request.POST['fname']
        edited_last_name = request.POST['lname']

        config = {}
        for user_config in user_details:
            if user_config['config']:
                config = json.loads(user_config['config'])
                config['firstname'] = edited_first_name
                config['lastname'] = edited_last_name
                config['authority'] = config.get('authority',
                                                 'Unknown Authority')
                updated_config = json.dumps(config)
                user_params = {'config': updated_config}
            else:  # it's needed if the config is empty
                user_config[
                    'config'] = '{"firstname":"' + edited_first_name + '", "lastname":"' + edited_last_name + '", "authority": "Unknown Authority"}'
                user_params = {'config': user_config['config']}
        # updating config local:user in manifold
        manifold_update_user(request, user_email, user_params)
        # this will be depricated, we will show the success msg in same page
        # Redirect to same page with success message
        messages.success(request, 'Sucess: First Name and Last Name Updated.')
        return HttpResponseRedirect(redirect_url)

    elif 'submit_auth' in request.POST:
        edited_auth = request.POST['authority']

        config = {}
        for user_config in user_details:
            if user_config['config']:
                config = json.loads(user_config['config'])
                config['firstname'] = config.get('firstname', 'N/A')
                config['lastname'] = config.get('lastname', 'N/A')
                config['authority'] = edited_auth
                updated_config = json.dumps(config)
                user_params = {'config': updated_config}
            else:  # it's needed if the config is empty
                user_config[
                    'config'] = '{"firstname": "N/A", "lastname":"N/A", "authority":"' + edited_auth + '"}'
                user_params = {'config': user_config['config']}
        # updating config local:user in manifold
        manifold_update_user(request, user_email, user_params)
        # this will be depricated, we will show the success msg in same page
        # Redirect to same page with success message
        messages.success(request, 'Sucess: Authority Updated.')
        return HttpResponseRedirect(redirect_url)

# XXX TODO: Factorize with portal/registrationview.py

    elif 'generate' in request.POST:
        for account_detail in account_details:
            for platform_detail in platform_details:
                if platform_detail['platform_id'] == account_detail[
                        'platform_id']:
                    if 'myslice' in platform_detail['platform']:
                        from Crypto.PublicKey import RSA
                        private = RSA.generate(1024)
                        private_key = json.dumps(private.exportKey())
                        public = private.publickey()
                        public_key = json.dumps(
                            public.exportKey(format='OpenSSH'))
                        # updating manifold local:account table
                        account_config = json.loads(account_detail['config'])
                        # preserving user_hrn
                        user_hrn = account_config.get('user_hrn', 'N/A')
                        keypair = '{"user_public_key":' + public_key + ', "user_private_key":' + private_key + ', "user_hrn":"' + user_hrn + '"}'
                        updated_config = json.dumps(account_config)
                        # updating manifold
                        user_params = {
                            'config': keypair,
                            'auth_type': 'managed'
                        }
                        manifold_update_account(request, user_id, user_params)
                        # updating sfa
                        #public_key = public_key.replace('"', '');
                        #user_pub_key = {'keys': public_key}
                        #sfa_update_user(request, user_hrn, user_pub_key)
                        messages.success(
                            request,
                            'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.'
                        )
                        return HttpResponseRedirect(redirect_url)
        else:
            messages.error(
                request,
                'Account error: You need an account in myslice platform to perform this action'
            )
            return HttpResponseRedirect(redirect_url)

    elif 'upload_key' in request.POST:
        for account_detail in account_details:
            for platform_detail in platform_details:
                if platform_detail['platform_id'] == account_detail[
                        'platform_id']:
                    if 'myslice' in platform_detail['platform']:
                        up_file = request.FILES['pubkey']
                        file_content = up_file.read()
                        file_name = up_file.name
                        file_extension = os.path.splitext(file_name)[1]
                        allowed_extension = ['.pub', '.txt']
                        if file_extension in allowed_extension and re.search(
                                r'ssh-rsa', file_content):
                            account_config = json.loads(
                                account_detail['config'])
                            # preserving user_hrn
                            user_hrn = account_config.get('user_hrn', 'N/A')
                            file_content = '{"user_public_key":"' + file_content + '", "user_hrn":"' + user_hrn + '"}'
                            #file_content = re.sub("\r", "", file_content)
                            #file_content = re.sub("\n", "\\n",file_content)
                            file_content = ''.join(file_content.split())
                            #update manifold local:account table
                            user_params = {
                                'config': file_content,
                                'auth_type': 'user'
                            }
                            manifold_update_account(request, user_id,
                                                    user_params)
                            # updating sfa
                            #user_pub_key = {'keys': file_content}
                            #sfa_update_user(request, user_hrn, user_pub_key)
                            messages.success(
                                request,
                                'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials'
                            )
                            return HttpResponseRedirect(redirect_url)
                        else:
                            messages.error(
                                request,
                                'RSA key error: Please upload a valid RSA public key [.txt or .pub].'
                            )
                            return HttpResponseRedirect(redirect_url)
        else:
            messages.error(
                request,
                'Account error: You need an account in myslice platform to perform this action'
            )
            return HttpResponseRedirect(redirect_url)

    elif 'dl_pubkey' in request.POST:
        for account_detail in account_details:
            for platform_detail in platform_details:
                if platform_detail['platform_id'] == account_detail[
                        'platform_id']:
                    if 'myslice' in platform_detail['platform']:
                        account_config = json.loads(account_detail['config'])
                        public_key = account_config['user_public_key']
                        response = HttpResponse(public_key,
                                                content_type='text/plain')
                        response[
                            'Content-Disposition'] = 'attachment; filename="pubkey.txt"'
                        return response
                        break
        else:
            messages.error(
                request,
                'Account error: You need an account in myslice platform to perform this action'
            )
            return HttpResponseRedirect(redirect_url)

    elif 'dl_pkey' in request.POST:
        for account_detail in account_details:
            for platform_detail in platform_details:
                if platform_detail['platform_id'] == account_detail[
                        'platform_id']:
                    if 'myslice' in platform_detail['platform']:
                        account_config = json.loads(account_detail['config'])
                        if 'user_private_key' in account_config:
                            private_key = account_config['user_private_key']
                            response = HttpResponse(private_key,
                                                    content_type='text/plain')
                            response[
                                'Content-Disposition'] = 'attachment; filename="privkey.txt"'
                            return response
                        else:
                            messages.error(
                                request,
                                'Download error: Private key is not stored in the server'
                            )
                            return HttpResponseRedirect(redirect_url)

        else:
            messages.error(
                request,
                'Account error: You need an account in myslice platform to perform this action'
            )
            return HttpResponseRedirect(redirect_url)

#    elif 'delete' in request.POST:
#        for account_detail in account_details:
#            for platform_detail in platform_details:
#                if platform_detail['platform_id'] == account_detail['platform_id']:
#                    if 'myslice' in platform_detail['platform']:
#                        account_config = json.loads(account_detail['config'])
#                        if 'user_private_key' in account_config:
#                            for key in account_config.keys():
#                                if key == 'user_private_key':
#                                    del account_config[key]
#
#                            updated_config = json.dumps(account_config)
#                            user_params = { 'config': updated_config, 'auth_type':'user'}
#                            manifold_update_account(request,user_params)
#                            messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
#                            messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
#                            return HttpResponseRedirect("/portal/account/")
#                        else:
#                            messages.error(request, 'Delete error: Private key is not stored in the server')
#                            return HttpResponseRedirect(redirect_url)
#
#        else:
#            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
#            return HttpResponseRedirect(redirect_url)

#clear all creds
    elif 'clear_cred' in request.POST:
        clear_user_creds(request, user_email)
        messages.success(request, 'All Credentials cleared')
        return HttpResponseRedirect(redirect_url)

    #make a user PI
    elif 'makepi' in request.POST:
        # getting user's authority_hrn
        config = {}
        for user_config in user_details:
            if user_config['config']:
                user_config = json.loads(user_config['config'])
                authority_hrn = user_config.get('authority',
                                                'Unknown Authority')

        #getting user_hrn
        for account_detail in account_details:
            for platform_detail in platform_details:
                if platform_detail['platform_id'] == account_detail[
                        'platform_id']:
                    if 'myslice' in platform_detail['platform']:
                        account_config = json.loads(account_detail['config'])
                        user_hrn = account_config.get('user_hrn', 'N/A')

        authority_add_pis(request, authority_hrn, user_hrn)
        clear_user_creds(request, user_email)
        messages.success(request, 'User upgraded to PI')
        return HttpResponseRedirect(redirect_url)

    elif 'removepi' in request.POST:
        # getting user's authority_hrn
        config = {}
        for user_config in user_details:
            if user_config['config']:
                user_config = json.loads(user_config['config'])
                authority_hrn = user_config.get('authority',
                                                'Unknown Authority')
        #getting user_hrn
        for account_detail in account_details:
            for platform_detail in platform_details:
                if platform_detail['platform_id'] == account_detail[
                        'platform_id']:
                    if 'myslice' in platform_detail['platform']:
                        account_config = json.loads(account_detail['config'])
                        user_hrn = account_config.get('user_hrn', 'N/A')
        authority_remove_pis(request, authority_hrn, user_hrn)
        clear_user_creds(request, user_email)
        messages.success(request, 'PI downgraded to user')
        return HttpResponseRedirect(redirect_url)

    # Download delegated_user_cred
    elif 'dl_user_cred' in request.POST:
        if 'delegated_user_credential' in account_config:
            user_cred = account_config['delegated_user_credential']
            response = HttpResponse(user_cred, content_type='text/plain')
            response[
                'Content-Disposition'] = 'attachment; filename="user_cred.txt"'
            return response
        else:
            messages.error(
                request,
                'Download error: User credential  is not stored in the server')
            return HttpResponseRedirect(redirect_url)

    else:
        messages.info(request, 'Under Construction. Please try again later!')
        return HttpResponseRedirect(redirect_url)
Exemple #12
0
    def get (self, request, state=None):
        env = self.default_env()
                
        #####    *** Reputation Plugin-specific START       ***     ############
        #The following 'if' is a dirty way for bypassing the JS AJAX cross-domain prevention policy...not pretty
        if request.GET.has_key(u'slicedata[user_eval][overall]'):
            dict_to_send = {}
            dict_to_send['eid'] = str(request.GET[u'slicedata[id]'])
            dict_to_send['slice_hrn'] = str(request.GET[u'slicedata[slice_hrn]'])
            dict_to_send['user_hrn'] = str(request.GET[u'slicedata[user_hrn]'])
            dict_to_send['start_tunix'] = str(request.GET[u'slicedata[start_tunix]'])
            dict_to_send['end_tunix'] = str(request.GET[u'slicedata[end_tunix]'])
            dict_to_send['start_t'] = str(request.GET[u'slicedata[start_t]'])
            dict_to_send['end_t'] = str(request.GET[u'slicedata[end_t]'])
            dict_to_send['testbeds'] = ast.literal_eval(str(request.GET[u'testbeds']))
            dict_to_send['user_eval'] = {}
            dict_to_send['user_eval']['reuse'] = str(request.GET[u'slicedata[user_eval][reuse]'])
            dict_to_send['user_eval']['availability'] = str(request.GET[u'slicedata[user_eval][availability]'])
            dict_to_send['user_eval']['pay'] = str(request.GET[u'slicedata[user_eval][pay]'])
            dict_to_send['user_eval']['support'] = str(request.GET[u'slicedata[user_eval][support]'])
            dict_to_send['user_eval']['overall'] = str(request.GET[u'slicedata[user_eval][overall]'])
            dict_to_send['user_eval']['link_quality'] = str(request.GET[u'slicedata[user_eval][link_quality]'])
            dict_to_send['user_eval']['problems'] = str(request.GET[u'slicedata[user_eval][problems]'])
            dict_to_send['user_eval']['quality'] = str(request.GET[u'slicedata[user_eval][quality]'])
            
            slicedata_received = json_to_rest('http://survivor.lab.netmode.ntua.gr:4567/reputation/json', dict_to_send )
                        
            return HttpResponse(json.dumps(slicedata_received), content_type = response_content_type(self.request))

                
        slices_users = []
        
        #get slices
        userslice_query = Query().get('slice').select('slice_urn', 'slice_hrn', 'users', 'resource', 'lease', 'slice_last_updated')
        slice_details = execute_query(self.request, userslice_query)
        
        #get local users
        local_user_query  = Query().get('local:user').select('email','status','config')
        local_user_details = execute_admin_query(self.request, local_user_query)
                   
        #get users - create dict[email]=hrn
        user_query  = Query().get('user').select('user_hrn','user_urn','user_email')
        user_details = execute_admin_query(self.request, user_query)
        users_hrn = {}
        for item in user_details:
            users_hrn[item['user_email']] = item['user_hrn']
        
        #get currenct username (email)
        if request.user.is_authenticated():
            cur_username = request.user.username  
        
        #get a list of all the slices for the logged in user
        testbeds = []
        #env['slices_users'] = json.dumps(slice_details, ensure_ascii=False)
        for slice in slice_details:
            
            if users_hrn[cur_username] in slice['users']:
                slices_users.append({'slice_hrn':slice['slice_hrn'], 'user':cur_username, 'user_hrn':users_hrn[cur_username] \
                                     , 'resource':slice['resource'], 'lease':slice['lease'], 'slice_last_updated':slice['slice_last_updated']  })  
                
                             
        #env['slices_users'] = slices_users  ### For logging
        #####create slicelist for template & JSON
        experiments,testbeds =  slice_to_exp(slices_users)
            
        all_exp = []
        iddata = []
                          
        for exp in experiments:
            experiment = {}
            experiment['slice_hrn'] = experiments[exp]['slice_hrn']
            experiment['user_hrn'] = users_hrn[cur_username]
            experiment['start_tunix'] = experiments[exp]['start']
            experiment['end_tunix'] = experiments[exp]['end']
            experiment['start_t'] = unix_to_timestamp(experiments[exp]['start'])
            experiment['end_t'] = unix_to_timestamp(experiments[exp]['end'])
            experiment['testbeds'] = {}
            for exp_node in experiments[exp]['nodes']:
                list_testbeds = [ key for key,val in testbeds.items()]
                for tkey in list_testbeds:
                    if exp_node in testbeds[tkey]:
                        if tkey in experiment['testbeds']:
                            if exp_node not in experiment['testbeds'][tkey]:
                                experiment['testbeds'][tkey].append(exp_node)
                        else:
                            experiment['testbeds'][tkey] = [exp_node]
            tempid = hashlib.sha1(str(experiment)).hexdigest()                    
            experiment['id'] = tempid
            
            iddata.append(tempid)
            all_exp.append(experiment)
            env['logging_test'] = json.dumps(all_exp, ensure_ascii=False)
            env['slices_users'] = json.dumps(all_exp, ensure_ascii=False)
        ###### Check which experiments have not been rated yet. Pop from all_exp any experiment that has already been rated
        
        unrated_exp = json_to_rest('http://survivor.lab.netmode.ntua.gr:4567/reputation/qid', iddata)    
        
        for item in all_exp:
            if item['id'] in unrated_exp:
                pass
            else:
                all_exp.pop(all_exp.index(item))

        ###### Get Reputation values from Reputation DB
        reps = json_to_rest('http://survivor.lab.netmode.ntua.gr:4567/reputation/showrep', "a")
        #env['logging_test'] = reps    
        
        #create a services list and a dict containing the services for each testbed
        serv_per_tb = {}
        services = []
        for item in reps:
            serv_per_tb[item['testbed']]=[]
            for serv in item['services']:
                if serv.keys()[0] not in services:
                    services.append(serv.keys()[0])
                    serv_per_tb[item['testbed']].append(serv.keys()[0])        
        
        #in json, sevices are in the form: 'services':[{'serv1':x}, {'serv2':y}], so we transform it to 'services':[x,y] based on
        # the services dict above. If for a specific service there is no applicable value, we put N/A            
        for testbed in reps:
            d = list(testbed['services'])
            del testbed['services']
            testbed['services'] = []
            for s in services:
                set_v = 0
                for i in d:
                    try:
                        testbed['services'].append(i[s])
                        set_v=1
                    except:
                        pass
                if set_v == 0 :
                    testbed['services'].append('N/A')
                
        ###### Pass variables to template
        #env['logging_test'] = json.dumps(all_exp, ensure_ascii=False)
        env['serv_per_tb'] = json.dumps(serv_per_tb, ensure_ascii=False)
        env['reputation'] = reps
        env['rep_serv'] = services
        env['slicelist'] = all_exp
        env['json_data'] = json.dumps(all_exp, ensure_ascii=False)
        
        ######    *** Reputation Plugin-specific END       ***     ############
        
        
        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))
    


    

                    
                    
                    
                    
            
Exemple #13
0
                'type'              : 'slice',
                'id'                : None,
                'user_hrn'          : user_hrn,
                'email'             : user_email,
                'timestamp'         : time.time(),
                'authority_hrn'     : authority_hrn,
                'organization'      : request.POST.get('org_name', ''),
                'slice_name'        : slice_name,
                #'url'               : request.POST.get('url', ''),
                #'purpose'           : request.POST.get('purpose', ''),
                'current_site'      : current_site
            }

            # slice name is unique among all authorities 
            slice_query = Query().get('myslice:slice').select('slice_hrn')
            slice_details_sfa = execute_admin_query(request, slice_query)
            for _slice in slice_details_sfa:
                split_list = _slice['slice_hrn'].split('.')
                sfa_slice_name = split_list[-1]
                if sfa_slice_name == slice_name:
                    errors.append('Slice already exists. Please use a different slice name.')
>>>>>>> onelab
            

            # What kind of slice name is valid?
<<<<<<< HEAD
            if (slice_name is None or slice_name == ''):
                self.errors.append('Slice Name is mandatory')
    
            if (purpose is None or purpose == ''):
                self.errors.append('Purpose is mandatory')
Exemple #14
0
def get_platform_config(request, platform_name):
    platform_query = Query().get('local:platform').filter_by(
        'platform', '==', platform_name).select('platform', 'config')
    platforms = execute_admin_query(request, platform_query)

    return json.loads(platforms[0]['config']) if platforms[0]['config'] else {}