コード例 #1
0
def logCheck():
    """Checking local database for logs adn sending it to monitoring server"""
    dbfile = ''.join(
        [os.path.dirname(os.path.abspath(__file__)), "/errors.db"])
    logger.error("[activity] database path: " + dbfile)
    conn = None

    #trying to connect local db adn pull unsent logs
    try:
        conn = lite.connect(dbfile)
        cur = conn.cursor()
        cur.execute("SELECT rowid, log from logs")
        notsent = cur.fetchall()
        for row in notsent:
            #trying to send unsent data from sqlite db
            try:
                urllib2.urlopen(config.activity.server,
                                urllib.urlencode(json.loads(row[1])))
                #delete those who were sent
                cur.execute("""DELETE FROM logs where rowid = %s""" % row[0])
                conn.commit()
            except urllib2.URLError as e:
                # this is just to inform that DB is not working properly
                logger.error('[activity] Error while sending stats')
                logger.error(e.strerror)

    except lite.Error, e:
        #this need to be updated to store information via syslog
        logger.error(
            '[activity] Error while pulling from local sqlite3 db: %s' %
            str(e.args))
        logger.error(e.strerror)
コード例 #2
0
def urls():
    u = []
    for component in list():
        try:
            __import__(component)
            u.append(url(r'^%s/' % component, include('%s.urls' % component)))
        except Exception, e:
            logger.error("Cannot load component ({}): {}".format(component, e))
        else:
            logger.info("Loaded component {}".format(component))
コード例 #3
0
ファイル: sfa_api.py プロジェクト: qursaan/myslice
def sfa_client(request,
               method,
               hrn=None,
               urn=None,
               object_type=None,
               rspec=None,
               recursive=False,
               options=None,
               platforms=None,
               output_format=None,
               admin=False):

    Config = ConfigParser.ConfigParser()
    monitor_file = os.path.abspath(
        os.path.dirname(__file__) + '/../myslice/monitor.ini')
    Config.read(monitor_file)

    if admin:
        user_email, admin_password = config.manifold_admin_user_password()
    else:
        #logger.debug(request.session['user']['email'])
        user_email = request.session['user']['email']

    results = dict()

    if hrn is None:
        hrn = ''
    if urn is None:
        urn = ''
    if object_type is None:
        object_type = ''
    if rspec is None:
        rspec = ''
    else:
        logger.debug("RSPEC = %s" % rspec)
    if recursive is None:
        recursive = False
    if options is None:
        options = dict()
    if platforms is None:
        platforms = list()

    if method not in ['GetVersion', 'ListResources']:
        try:
            if not hrn:
                hrn = urn_to_hrn(urn)
            else:
                urn = hrn_to_urn(hrn, object_type)
        except Exception, e:
            logger.error(e)
            raise Exception, "Provide urn OR hrn + type as parameters of method %s" % method
コード例 #4
0
ファイル: manifoldapi.py プロジェクト: qursaan/myslice
def execute_admin_query(request, query):
    # xxx config
    from myslice.settings import config
    url = config.manifold_url()

    admin_user, admin_password = config.manifold_admin_user_password()
    if not admin_user or not admin_password:
        logger.error(
            """CONFIG: you need to setup admin_user and admin_password in myslice.ini
Some functions won't work properly until you do so""")
    admin_auth = {
        'AuthMethod': 'password',
        'Username': admin_user,
        'AuthString': admin_password
    }

    return _execute_query(url, request, query, admin_auth)
コード例 #5
0
    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
コード例 #6
0
def logout_on_manifold_exception(fun_that_returns_httpresponse):
    def wrapped(request, *args, **kwds):
        try:
            return fun_that_returns_httpresponse(request, *args, **kwds)
        except ManifoldException, manifold_result:
            # xxx we need a means to display this message to user...
            from django.contrib.auth import logout
            # in some unusual cases, this might fail
            try:
                logout(request)
            except:
                pass
            return HttpResponseRedirect('/')
        except Exception, e:
            # xxx we need to sugarcoat this error message in some error template...
            logger.error("Unexpected exception {}".format(e))
            import traceback
            logger.error(traceback.format_exc())
            return HttpResponseRedirect('/')
コード例 #7
0
ファイル: forms.py プロジェクト: qursaan/myslice
 def save(self,
          domain_override=None,
          subject_template_name='registration/password_reset_subject.txt',
          email_template_name='registration/password_reset_email.html',
          use_https=False,
          token_generator=default_token_generator,
          from_email=None,
          request=None):
     """
     Generates a one-use only link for resetting password and sends to the
     user.
     """
     from django.core.mail import send_mail, EmailMultiAlternatives
     try:
         for user in self.users_cache:
             if not domain_override:
                 current_site = get_current_site(request)
                 site_name = current_site.name
                 domain = current_site.domain
             else:
                 site_name = domain = domain_override
             c = {
                 'email': user.email,
                 'domain': domain,
                 'site_name': site_name,
                 'uid': int_to_base36(user.pk),
                 'user': user,
                 'token': token_generator.make_token(user),
                 'protocol': use_https and 'https' or 'http',
             }
             subject = loader.render_to_string(subject_template_name, c)
             # Email subject *must not* contain newlines
             subject = ''.join(subject.splitlines())
             email = loader.render_to_string(email_template_name, c)
             send_mail(subject, email, from_email, [user.email])
     except Exception as e:
         logger.error(
             "Failed to send email, please check the mail templates and the SMTP configuration of your server"
         )
コード例 #8
0
ファイル: manifoldapi.py プロジェクト: qursaan/myslice
        def func(*args, **kwds):
            import time
            start = time.time()

            # the message to display
            auth_message = "<AuthMethod not set in {}>".format(self.auth) if 'AuthMethod' not in self.auth \
                           else "[session]" if self.auth['AuthMethod'] == 'session' \
                           else "user:{}".format(self.auth['Username']) if self.auth['AuthMethod'] == 'password' \
                           else "anonymous" if self.auth['AuthMethod'] == 'anonymous' \
                           else "[???]" + "{}".format(self.auth)
            end_message = "MANIFOLD <- {}( {}( {} ) ) with auth={} to {}"\
                          .format(methodName,
                                  args[0]['action'] or '',
                                  args[0]['object'] or '',
                                  auth_message,
                                  self.url)
            try:
                args += ({'authentication': self.auth}, )
                result = getattr(self.server, methodName)(*args, **kwds)
                logger.debug("{} executed in {} seconds -> {}"\
                             .format(end_message, time.time() - start, truncate_result(result)))
                return ResultValue(**result)

            except Exception as error:
                logger.error(
                    "===== xmlrpc catch-all exception: {}".format(error))
                import traceback
                logger.error(traceback.format_exc(limit=3))

                if "Connection refused" in error:
                    raise ManifoldException(
                        ManifoldResult(code=ManifoldCode.SERVER_UNREACHABLE,
                                       output="{} answered {}".format(
                                           self.url, error)))
                # otherwise
                logger.error("{} FAILED - executed in {} seconds"\
                             .format(end_message, time.time() - start))
                logger.error("MANIFOLD {}".format(error))
                raise ManifoldException(
                    ManifoldResult(code=ManifoldCode.SERVER_UNREACHABLE,
                                   output="{}".format(error)))
コード例 #9
0
ファイル: __init__.py プロジェクト: qursaan/myslice
 def template_file (self):
     try:
         return "univbris_topology.html"
     except Exception as e :
         logger.error("error template {}".format(e))
コード例 #10
0
    def get_context_data(self, **kwargs):

        ctx_my_authorities = {}
        ctx_delegation_authorities = {}
        ctx_sub_authorities = {}
        dest = {}

        # The user need to be logged in
        if (self.request.user):

            user_query = Query().get('local:user').filter_by(
                'email', '==', self.request.user.email).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)

            for user_account in user_accounts:

                if user_account['auth_type'] == 'reference':
                    continue  # we hardcoded the myslice platform...

                config = json.loads(user_account['config'])
                creds = []
                if 'authority_credentials' in config:
                    for authority_hrn, credential in config[
                            'authority_credentials'].items():
                        credential_authorities.add(authority_hrn)
                if 'delegated_authority_credentials' in config:
                    for authority_hrn, credential in config[
                            'delegated_authority_credentials'].items():
                        credential_authorities.add(authority_hrn)

            # CACHE PB with fields
            page = Page(self.request)
            metadata = page.get_metadata()
            user_md = metadata.details_by_object('user')
            user_fields = [column['name'] for column in user_md['column']]

            # ** 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(user_fields)
            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')

            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

            # 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

            # Summary all
            queried_pending_authorities = pi_my_authorities | pi_delegation_authorities  #| pi_subauthorities

            # iterate on the requests and check if the authority matches a prefix
            # startswith an authority on which the user is PI
            if len(pi_my_authorities) > 0:
                requests = get_requests(pi_my_authorities)
            else:
                requests = get_requests()
            for r in requests:
                auth_hrn = r['authority_hrn']
                for my_auth in pi_my_authorities:
                    if auth_hrn.startswith(my_auth):
                        dest = ctx_my_authorities
                        r['allowed'] = 'allowed'

                #for my_auth in pi_delegation_authorities:
                #    if auth_hrn.startswith(my_auth):
                #        dest = ctx_delegation_authorities
                #        r['allowed'] = 'allowed'
                if auth_hrn in pi_expired_credential_authorities:
                    r['allowed'] = 'expired'
                if 'allowed' not in r:
                    ## TEMP FIX for allowing new authority registration
                    #r['allowed'] = 'denied'
                    r['allowed'] = 'allowed'

                if not auth_hrn in dest:
                    dest[auth_hrn] = []
                dest[auth_hrn].append(r)

#         env = {}
#         env['my_authorities']   = ctx_my_authorities
#         env['sub_authorities']   = ctx_sub_authorities
#         env['delegation_authorities'] = ctx_delegation_authorities
#
#         # XXX This is repeated in all pages
#         # more general variables expected in the template
#         # the menu items on the top
#         #env['topmenu_items'] = topmenu_items_live('Validation', page)
#         # so we can sho who is logged
#         env['username'] = request.user
#         env['pi'] = "is_pi"
#         env['theme'] = self.theme
#         env['section'] = "Requests"

        context = super(ManagementRequestsView,
                        self).get_context_data(**kwargs)

        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'] = self.request.user
        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
コード例 #11
0
ファイル: sfa_api.py プロジェクト: qursaan/myslice
        #            else:
        #                api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}
        #else:
        #    api_options['geni_rspec_version'] = {'type': 'GENI', 'version': '3'}

        try:
            # Get user config from Manifold
            user_config = get_user_config(request, user_email, pf)
            if 'delegated_user_credential' in user_config:
                logger.debug('delegated_user_credential')
                user_cred = user_config['delegated_user_credential']
            elif 'user_credential' in user_config:
                logger.debug('user_credential')
                user_cred = user_config['user_credential']
            else:
                logger.error("no user credentials for user = ", user_email)
                user_cred = {}

            if object_type:
                if 'delegated_%s_credentials' % object_type in user_config:
                    logger.debug('delegated_%s_credentials' % object_type)
                    for obj_name, cred in user_config[
                            'delegated_%s_credentials' % object_type].items():
                        if obj_name == hrn:
                            object_cred = cred
                elif '%s_credentials' % object_type in user_config:
                    logger.debug('%s_credentials' % object_type)
                    for obj_name, cred in user_config['%s_credentials' %
                                                      object_type].items():
                        if obj_name == hrn:
                            object_cred = cred
コード例 #12
0
def _proxy(url, request, format):
    """the view associated with /manifold/proxy/ with the query passed using POST"""
    
    # expecting a POST
    if request.method != 'POST':
        logger.error("MANIFOLDPROXY unexpected method {} -- exiting".format(request.method))
        return HttpResponse ({"ret":0}, content_type="application/json")
    # we only support json for now
    # if needed in the future we should probably cater for
    # format_in : how is the query encoded in POST
    # format_out: how to serve the results
    if format != 'json':
        logger.error("MANIFOLDPROXY unexpected format {} -- exiting".format(format))
        return HttpResponse ({"ret":0}, content_type="application/json")
    try:
        # translate incoming POST request into a query object
        #logger.debug("MANIFOLDPROXY request.POST {}".format(request.POST))

        manifold_query = Query()
        #manifold_query = ManifoldQuery()
        manifold_query.fill_from_POST(request.POST)
        # retrieve session for request

        # We allow some requests to use the ADMIN user account
        if (manifold_query.get_from() == 'local:user' and manifold_query.get_action() == 'create') \
                or (manifold_query.get_from() == 'local:platform' and manifold_query.get_action() == 'get'):
            admin_user, admin_password = config.manifold_admin_user_password()
            manifold_api_session_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
        else:
            if 'manifold' in request.session:
                manifold_api_session_auth = request.session['manifold']['auth']
            else:
            #manifold_api_session_auth = SessionCache().get_auth(request)
            #if not manifold_api_session_auth:
                return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
                
        if debug_empty and manifold_query.action.lower()=='get':
            return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
                
        # actually forward
        manifold_api= ManifoldAPI(url, auth=manifold_api_session_auth)

        # for the benefit of the python code, manifoldAPI raises an exception if something is wrong
        # however in this case we want to propagate the complete manifold result to the js world

        result = manifold_api.forward(manifold_query.to_dict())

        # XXX TEMP HACK
        if 'description' in result and result['description'] \
                and isinstance(result['description'], (tuple, list, set, frozenset)):
            result [ 'description' ] = [ ResultValue.to_html (x) for x in result['description'] ]
        
        #
        # register activity
        #
        # resource reservation
        if (manifold_query.action.lower() == 'update') :
            logger.debug(result['value'][0])
            if 'resource' in result['value'][0] :
                for resource in result['value'][0]['resource'] :
                    activity.slice.resource(request, 
                            { 
                                'slice' :           result['value'][0]['slice_hrn'], 
                                'resource' :        resource['hostname'], 
                                'resource_type' :   resource['type'],
                                'facility' :        resource['facility_name'],
                                'testbed' :         resource['testbed_name']
                            }
                    )
        
        json_answer=json.dumps(result)

        return HttpResponse (json_answer, content_type="application/json")

    except Exception as e:
        logger.error("MANIFOLDPROXY {}".format(e))
        import traceback
        logger.error(traceback.format_exc())
        return HttpResponse ({"ret":0}, content_type="application/json")
コード例 #13
0
def csrf_failure(request, reason=""):
    logger.error("CSRF failure with reason '{}'".format(reason))
    return HttpResponseForbidden (json.dumps (failure_answer), content_type="application/json")
コード例 #14
0
def logWrite(request, action, message, objects=None):

    if not apikey:
        logger.info("===============>> activity: no apikey")
        return
    if not secret:
        logger.info("===============>> activity: no secret")
        return

    timestamp = time.mktime(datetime.datetime.today().timetuple())
    ip = getClientIp(request)
    log = {
        "timestamp":
        timestamp,
        "client_ip":
        ip,
        "host":
        request.get_host(),
        "referrer":
        request.META.get('HTTP_REFERER'),
        "user":
        request.user.username,
        "action":
        action,
        "message":
        message,
        "apikey":
        apikey,
        "signature":
        sign(secret, "%s%s%s%s" % (timestamp, ip, request.user, action)),
        "slice":
        None,
        "resource":
        None,
        "resource_type":
        None,
        "facility":
        None,
        "testbed":
        None,
    }

    if objects is not None:
        for o in objects:
            if (o in log):
                log[o] = objects[o]

    try:
        result = urllib2.urlopen(server, urllib.urlencode(log))
        logger.info("===============>> activity: {} <{}> {}".format(
            action, request.user, message))
        content = result.read()

        #checking for not sent data and sending it (50% probability)
        if random.randint(0, 100) < 50:
            logCheck()

    except urllib2.URLError as e:
        logger.error(
            "===============>> activity: connection to {} impossible, could not log action"
            .format(server))
        logger.error(e.strerror)

        dbfile = ''.join(
            [os.path.dirname(os.path.abspath(__file__)), "/errors.db"])
        logger.error("===============>> activity: database path: " + dbfile)
        conn = None
        try:
            conn = lite.connect(dbfile)
            cur = conn.cursor()
            cur.execute("""INSERT INTO logs(log) values('%s')""" %
                        json.dumps(log))
            conn.commit()
        except lite.Error, e:
            # this means that writing log into db also failed :(
            # Last chance to preserve log is to send it to system syslog
            # however there is no mechanism to pull it from this log - just manually.
            logger.error('[activity] Error while inserting into sql db: %s' %
                         str(e.args))
            logger.error("[activity] data to send: '%s'" % json.dumps(log))
        if conn:
            conn.close()
コード例 #15
0
ファイル: accountview.py プロジェクト: qursaan/myslice
def account_process(request):
    from sfa.trust.credential               import Credential
    from sfa.trust.certificate              import Keypair

    user_query  = Query().get('local:user').select('user_id','email','password','config')
    user_details = execute_query(request, user_query)
    
    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')
    platform_details = execute_query(request, platform_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']                                             
        try:
            if user_email == request.user.email:                                          
                authorize_query = True                                                    
            else:                                                                         
                logger.error("SECURITY: {} tried to update {}".format(user_email, request.user.email))
                messages.error(request, 'You are not authorized to modify another user.') 
                return HttpResponseRedirect("/portal/account/")                               
        except Exception as e:
            logger.error("exception in account_process {}".format(e))

    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\
               or request.POST['button_value'] == 'add_'+platform_detail['platform']:
                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("/portal/account/")

            # Delete reference account from the platforms
            if 'delete_'+platform_detail['platform'] in request.POST\
               or request.POST['button_value'] == 'delete_'+platform_detail['platform']:
                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, 'Reference Account is removed from the selected platform')
                return HttpResponseRedirect("/portal/account/")

            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 or request.POST['button_value'] == 'dl_'+slice_list[i]:
                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 or request.POST['button_value'] == 'dl_'+auth_list[i]:
                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

    account_detail = get_myslice_account(request)
             
    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":"{}", "lastname":"{}", "authority": "Unknown Authority"}}'\
                                        .format(edited_first_name, edited_last_name)
                user_params = {'config': user_config['config']} 
        # updating config local:user in manifold       
        manifold_update_user(request, 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("/portal/account/")       
    
    elif 'submit_pass' in request.POST:
        edited_password = request.POST['password']
        
        for user_pass in user_details:
            user_pass['password'] = edited_password
        #updating password in local:user
        user_params = { 'password' : user_pass['password']}
        manifold_update_user(request, request.user.email, user_params)
#        return HttpResponse('Success: Password Changed!!')
        messages.success(request, 'Success: Password Updated.')
        return HttpResponseRedirect("/portal/account/")

# XXX TODO: Factorize with portal/registrationview.py
# XXX TODO: Factorize with portal/registrationview.py
# XXX TODO: Factorize with portal/joinview.py

    elif 'generate' in request.POST:
        try:
            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)
            result_sfa_user = sfa_get_user(request, user_hrn, public_key)
            try:
                if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
                    # updating manifold
                    updated_config = json.dumps(account_config) 
                    user_params = { 'config': keypair, 'auth_type':'managed'}
                    manifold_update_account(request, user_id, user_params)
                    messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
                else:
                    raise Exception,"Keys are not matching"
            except Exception as e:
                messages.error(request, 'Error: An error occured during the update of your public key at the Registry, or your public key is not matching the one stored.')
                logger.error("Exception in accountview {}".format(e))
            return HttpResponseRedirect("/portal/account/")
        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")
                       
    elif 'upload_key' in request.POST:
        try:
            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("/portal/account/")
            else:
                messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
                return HttpResponseRedirect("/portal/account/")

        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")

    elif 'dl_pubkey' in request.POST or request.POST['button_value'] == 'dl_pubkey':
        try:
            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
        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")
               
    elif 'dl_pkey' in request.POST or request.POST['button_value'] == 'dl_pkey':
        try:
            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("/portal/account/")

        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")
    
    elif 'delete' in request.POST or request.POST['button_value'] == 'delete':
        try:
            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_id, 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("/portal/account/")
                          
        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
            return HttpResponseRedirect("/portal/account/")
    
    # download identity for jfed
    elif 'dl_identity' in request.POST or request.POST['button_value'] == 'dl_identity':
        try:
            jfed_identity = get_jfed_identity(request)
            if jfed_identity is not None:
                response = HttpResponse(jfed_identity, content_type='text/plain')
                response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
                return response
            else:
                messages.error(request, 'Download error: Private key is not stored in the server')
                return HttpResponseRedirect("/portal/account/")

        except Exception as e:
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
            return HttpResponseRedirect("/portal/account/")

    # Download sfi_config
    elif 'dl_sfi_config' in request.POST or request.POST['button_value'] == 'dl_sfi_config':
        platform_detail = get_myslice_platform(request)
        platform_config = json.loads(platform_detail['config'])
        account_detail = get_myslice_account(request)
        account_config = json.loads(account_detail['config'])

        user_hrn = account_config.get('user_hrn','N/A')
        t_user_hrn = user_hrn.split('.')
        authority_hrn = t_user_hrn[0] + '.' + t_user_hrn[1]
        registry = get_registry_url(request)
        import socket
        hostname = socket.gethostbyaddr(socket.gethostname())[0]
        admin_user = platform_config.get('user','N/A')
        manifold_host = ConfigEngine().manifold_url()
        if 'localhost' in manifold_host:
            manifold_host = manifold_host.replace('localhost',hostname)
        sfi_config  = '[sfi]\n'
        sfi_config += 'auth = '+ authority_hrn +'\n'
        sfi_config += 'user = '******'\n'
        sfi_config += 'registry = '+ registry +'\n'
        sfi_config += 'sm = http://sfa3.planet-lab.eu:12346/\n\n'
        sfi_config += '[myslice]\n'
        sfi_config += 'backend = '+ manifold_host +'\n'
        sfi_config += 'delegate  = '+ admin_user +'\n'
        sfi_config += 'platform  = myslice\n'
        sfi_config += 'username  = '******'\n'
        response = HttpResponse(sfi_config, content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename="sfi_config"'
        return response

    #clear all creds
    elif 'clear_cred' in request.POST or request.POST['button_value'] == 'clear_cred':
        try:
            result = clear_user_creds(request, user_email)
            if result is not None: 
                messages.success(request, 'All Credentials cleared')
            else:
                messages.error(request, 'Delete error: Credentials are not stored in the server')
        except Exception as e:
            logger.error("Exception in accountview.py in clear_user_creds {}".format(e))
            messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
        return HttpResponseRedirect("/portal/account/")

    # Download delegated_user_cred
    elif 'dl_user_cred' in request.POST or request.POST['button_value'] == 'dl_user_cred':
        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("/portal/account/")

    # Download user_cert
    elif 'dl_user_cert' in request.POST or request.POST['button_value'] == 'dl_user_cert':
        if 'user_credential' in account_config:
            user_cred = account_config['user_credential']
            obj_cred = Credential(string=user_cred)
            obj_gid = obj_cred.get_gid_object()
            str_cert = obj_gid.save_to_string()
            response = HttpResponse(str_cert, content_type='text/plain')
            response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
            return response

        elif 'delegated_user_credential' in account_config:
            user_cred = account_config['delegated_user_credential']
            obj_cred = Credential(string=user_cred)
            obj_gid = obj_cred.get_gid_object()
            str_cert = obj_gid.save_to_string()
            response = HttpResponse(str_cert, content_type='text/plain')
            response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
            return response
        else:
            messages.error(request, 'Download error: User credential is not stored in the server')
            return HttpResponseRedirect("/portal/account/")

    # Download user p12 = private_key + Certificate
    elif 'dl_user_p12' in request.POST or request.POST['button_value'] == 'dl_user_p12':
        if 'user_credential' in account_config and 'user_private_key' in account_config:
            user_cred = account_config['user_credential']
            obj_cred = Credential(string=user_cred)
            obj_gid = obj_cred.get_gid_object()
            str_cert = obj_gid.save_to_string()
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)

            user_private_key = account_config['user_private_key'].encode('ascii')
            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)

            p12 = crypto.PKCS12()
            p12.set_privatekey(pkey)
            p12.set_certificate(cert)       
            pkcs12 = p12.export()

            response = HttpResponse(pkcs12, content_type='text/plain')
            response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
            return response

        elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
            user_cred = account_config['delegated_user_credential']
            obj_cred = Credential(string=user_cred)
            obj_gid = obj_cred.get_gid_object()
            str_cert = obj_gid.save_to_string()
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)

            user_private_key = account_config['user_private_key'].encode('ascii')
            pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)

            p12 = crypto.PKCS12()
            p12.set_privatekey(pkey)
            p12.set_certificate(cert)       
            pkcs12 = p12.export()

            response = HttpResponse(pkcs12, content_type='text/plain')
            response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
            return response
        else:
            messages.error(request, 'Download error: User private key or credential is not stored in the server')
            return HttpResponseRedirect("/portal/account/")

    else:
        messages.info(request, 'Under Construction. Please try again later!')
        return HttpResponseRedirect("/portal/account/")
コード例 #16
0
    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
コード例 #17
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})
コード例 #18
0
ファイル: manifoldbackend.py プロジェクト: qursaan/myslice
    def authenticate(self, token=None):
        if not token:
            return None
        
        person = {}

        try:
            email = token['username']
            username = email.split('@')[-1]
            password = token['password']
            request = token['request']

            auth = {'AuthMethod': 'password', 'Username': email, 'AuthString': password}
            api = ManifoldAPI(config.manifold_url(), auth)
            sessions_result = api.forward(Query.create('local:session').to_dict())
            sessions = sessions_result.ok_value()
            if not sessions:
                logger.error("GetSession failed: {}".format(sessions_result.error()))
                return None
            session = sessions[0]
            logger.debug("SESSION : {}".format(session.keys()))
            
            # Change to session authentication
            api.auth = {'AuthMethod': 'session', 'session': session['session']}
            #api.auth = session_auth
            self.api = api

            # Get account details
            # the new API would expect Get('local:user') instead
            persons_result = api.forward(Query.get('local:user').to_dict())
            persons = persons_result.ok_value()
            if not persons:
                logger.error("GetPersons failed: {}".format(persons_result.error()))
                return None
            person = persons[0]
            logger.debug("PERSON : {}".format(person))
            
            request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': session['expires']}

            #logger.info("{} {} <{}> logged in"\
            #    .format(person['config']['first_name'], person['config']['last_name'], person['config']['email']))

            #SessionCache().store_auth(request, session_auth)

        except ManifoldException as e:
            logger.error("ManifoldException in Auth Backend: {}".format(e.manifold_result))
        except Exception as e:
            logger.error("Exception in Manifold Auth Backend: {}".format(e))
            import traceback
            logger.error(traceback.format_exc())
            return None

        try:
            # Check if the user exists in Django's local database
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            # Create a user in Django's local database
            user = User.objects.create_user(username, email, 'passworddoesntmatter')
            user.email = person['email']

        if 'firstname' in person:
            user.first_name = person['firstname']
        if 'lastname' in person:
            user.last_name = person['lastname']

        user.pi = authority_check_pis (request, user.email)
        request.session['user'] = {'email':user.email,'pi':user.pi,'firstname':user.first_name,'lastname':user.last_name}
        return user