示例#1
0
def dump(obj, path, protocol=0):
    """Dump a binary representation of obj to the file, path"""

    contents = dumps(obj)
    fd = LocalFile(path, "w")
    fd.write(contents)
    fd.close()
示例#2
0
def dump(obj, path, protocol=0):
    """Dump a binary representation of obj to the file, path"""

    contents = dumps(obj)
    fd = LocalFile(path, 'w')
    fd.write(contents)
    fd.close()
示例#3
0
def dump(obj, path, protocol=0):
    """Dump a binary representation of obj to the file, path"""

    contents = dumps(obj)
    fd = distfile.DistFile(path, 'w')
    fd.lock(LOCK_EX)
    fd.write(contents)
    fd.flush()
    fd.unlock()
    fd.close()
示例#4
0
def dump(obj, path, protocol=0):
    """Dump a binary representation of obj to the file, path"""

    contents = dumps(obj)
    fd = distfile.DistFile(path, 'w')
    fd.lock(LOCK_EX)
    fd.write(contents)
    fd.flush()
    fd.unlock()
    fd.close()
示例#5
0
def save_access_request(configuration, request_dir, request):
    """Save the request dictionary as a pickle in request_dir with random
    filename stem and predefined request file extension.
    Returns the nameof the file on success.
    """
    request['created_timestamp'] = datetime.datetime.now()
    try:
        (filehandle, tmpfile) = make_temp_file(suffix=request_ext,
                                               prefix=request_prefix,
                                               dir=request_dir)
        # Prevent exotic characters causing trouble between scripts
        request['request_name'] = os.path.basename(tmpfile)
        os.write(filehandle, dumps(request))
        os.close(filehandle)
    except Exception, err:
        configuration.logger.error("could not save request %s in %s: %s" % \
                                   (request, request_dir, err))
        return False
示例#6
0
def main(client_id, user_arguments_dict):
    """Main function used by front end"""

    (configuration, logger, output_objects, op_name) = \
        initialize_main_variables(client_id, op_header=False, op_menu=False)
    defaults = signature()[1]
    (validate_status, accepted) = validate_input(user_arguments_dict,
            defaults, output_objects, allow_rejects=False)
    if not validate_status:
        logger.warning('%s invalid input: %s' % (op_name, accepted))
        return (accepted, returnvalues.CLIENT_ERROR)

    if not correct_handler('POST'):
        output_objects.append(
            {'object_type': 'error_text', 'text'
             : 'Only accepting POST requests to prevent unintended updates'})
        return (output_objects, returnvalues.CLIENT_ERROR)

    title_entry = find_entry(output_objects, 'title')
    title_entry['text'] = '%s certificate request' % configuration.short_title
    title_entry['skipmenu'] = True
    output_objects.append({'object_type': 'header', 'text'
                          : '%s certificate request' % \
                            configuration.short_title 
                           })

    admin_email = configuration.admin_email
    smtp_server = configuration.smtp_server
    user_pending = os.path.abspath(configuration.user_pending)

    # force name to capitalized form (henrik karlsen -> Henrik Karlsen)
    # please note that we get utf8 coded bytes here and title() treats such
    # chars as word termination. Temporarily force to unicode.

    raw_name = accepted['cert_name'][-1].strip() 
    try:
        cert_name = force_utf8(force_unicode(raw_name).title())
    except Exception:
        cert_name = raw_name.title()
    country = accepted['country'][-1].strip().upper()
    state = accepted['state'][-1].strip().title()
    org = accepted['org'][-1].strip()

    # lower case email address

    email = accepted['email'][-1].strip().lower()
    password = accepted['password'][-1]
    verifypassword = accepted['verifypassword'][-1]

    # keep comment to a single line

    comment = accepted['comment'][-1].replace('\n', '   ')

    # single quotes break command line format - remove

    comment = comment.replace("'", ' ')

    if password != verifypassword:
        output_objects.append({'object_type': 'error_text', 'text'
                              : 'Password and verify password are not identical!'
                              })
        return (output_objects, returnvalues.CLIENT_ERROR)

    # TODO: move this check to conf?

    if not forced_org_email_match(org, email, configuration):
        output_objects.append({'object_type': 'error_text', 'text'
                              : '''Illegal email and organization combination:
Please read and follow the instructions in red on the request page!
If you are a student with only a @*.ku.dk address please just use KU as
organization. As long as you state that you want the certificate for course
purposes in the comment field, you will be given access to the necessary
resources anyway.
'''})
        return (output_objects, returnvalues.CLIENT_ERROR)

    user_dict = {
        'full_name': cert_name,
        'organization': org,
        'state': state,
        'country': country,
        'email': email,
        'comment': comment,
        'password': base64.b64encode(password),
        'expire': int(time.time() + cert_valid_days * 24 * 60 * 60),
        'openid_names': [],
        }
    fill_distinguished_name(user_dict)
    user_id = user_dict['distinguished_name']
    user_dict['authorized'] = (user_id == client_id)
    if configuration.user_openid_providers and configuration.user_openid_alias:
        user_dict['openid_names'] += \
                                  [user_dict[configuration.user_openid_alias]]
    logger.info('got reqcert request: %s' % user_dict)

    # For testing only
    
    if cert_name.upper().find('DO NOT SEND') != -1:
        output_objects.append({'object_type': 'text', 'text'
                          : "Test request ignored!"})
        return (output_objects, returnvalues.OK)

    req_path = None
    try:
        (os_fd, req_path) = tempfile.mkstemp(dir=user_pending)
        os.write(os_fd, dumps(user_dict))
        os.close(os_fd)
    except Exception, err:
        logger.error('Failed to write certificate request to %s: %s'
                      % (req_path, err))
        output_objects.append({'object_type': 'error_text', 'text'
                              : 'Request could not be sent to grid administrators. Please contact them manually on %s if this error persists.'
                               % admin_email})
        return (output_objects, returnvalues.SYSTEM_ERROR)
示例#7
0
specified in the configuation for the '%s' resource unit. Please contact the %s
owner and ask if you can be included in the %s.""" % \
                                (vgrid_label, vgrid_name, res_unit['name'],
                                 vgrid_label, vgrid_label))

    # save dictionary to a file

    if outfile == 'AUTOMATIC':

        # save configuration as python dictionary in the resource' private directory

        filename = configuration.resource_home + unique_resource_name\
             + '/config'
    elif outfile:

        # outfile specified (DumpConfig)

        filename = outfile
    else:
        return (True, 'Everything ok')

    try:
        fsock = open(filename, 'w')
        st = dumps(conf, 0)
        fsock.write(st)
        fsock.close()
    except Exception, err:
        return (False, "Fatal error: could not open '" + filename +
                "' for writing!" + '\n Msg: ' + str(err))
    return (True, 'Everything ok, config updated')
示例#8
0
        output_objects.append({
            'object_type':
            'text',
            'text':
            '''Created the user account for you:
Please use the navigation menu to the left to proceed using it.
'''
        })
        return (output_objects, returnvalues.OK)

    # Without auto add we end here and go through the mail-to-admins procedure
    req_path = None
    try:
        (os_fd, req_path) = tempfile.mkstemp(dir=user_pending)
        os.write(os_fd, dumps(user_dict))
        os.close(os_fd)
    except Exception, err:
        logger.error('Failed to write existing certificate request to %s: %s' %
                     (req_path, err))
        output_objects.append(
            {'object_type': 'error_text', 'text'
             : """Request could not be sent to grid administrators. Please
contact them manually on %s if this error persists.""" % \
             admin_email})
        return (output_objects, returnvalues.SYSTEM_ERROR)

    logger.info('Wrote existing certificate sign up request to %s' % req_path)
    tmp_id = req_path.replace(user_pending, '')
    user_dict['tmp_id'] = tmp_id
示例#9
0
def main(client_id, user_arguments_dict):
    """Main function used by front end"""

    (configuration, logger, output_objects, op_name) = initialize_main_variables(
        client_id, op_header=False, op_menu=False
    )
    defaults = signature()[1]
    logger.debug("in extoidaction: %s" % user_arguments_dict)
    (validate_status, accepted) = validate_input(user_arguments_dict, defaults, output_objects, allow_rejects=False)
    if not validate_status:
        return (accepted, returnvalues.CLIENT_ERROR)

    # Unfortunately OpenID does not use POST
    # if not correct_handler('GET'):
    #    output_objects.append(
    #        {'object_type': 'error_text', 'text'
    #         : 'Only accepting POST requests to prevent unintended updates'})
    #    return (output_objects, returnvalues.CLIENT_ERROR)

    title_entry = find_entry(output_objects, "title")
    title_entry["text"] = "%s OpenID sign up" % configuration.short_title
    title_entry["skipmenu"] = True
    output_objects.append({"object_type": "header", "text": "%s OpenID sign up" % configuration.short_title})

    admin_email = configuration.admin_email
    smtp_server = configuration.smtp_server
    user_pending = os.path.abspath(configuration.user_pending)

    # force name to capitalized form (henrik karlsen -> Henrik Karlsen)

    id_url = os.environ["REMOTE_USER"].strip()
    openid_prefix = configuration.user_openid_providers[0].rstrip("/") + "/"
    raw_login = id_url.replace(openid_prefix, "")
    full_name = accepted["openid.sreg.full_name"][-1].strip().title()
    country = accepted["openid.sreg.country"][-1].strip().upper()
    state = accepted["state"][-1].strip().title()
    organization = accepted["openid.sreg.organization"][-1].strip()
    organizational_unit = accepted["openid.sreg.organizational_unit"][-1].strip()
    locality = accepted["openid.sreg.locality"][-1].strip()

    # lower case email address

    email = accepted["openid.sreg.email"][-1].strip().lower()
    password = accepted["password"][-1]
    # verifypassword = accepted['verifypassword'][-1]

    # keep comment to a single line

    comment = accepted["comment"][-1].replace("\n", "   ")

    # single quotes break command line format - remove

    comment = comment.replace("'", " ")

    user_dict = {
        "full_name": full_name,
        "organization": organization,
        "organizational_unit": organizational_unit,
        "locality": locality,
        "state": state,
        "country": country,
        "email": email,
        "password": password,
        "comment": comment,
        "expire": int(time.time() + oid_valid_days * 24 * 60 * 60),
        "openid_names": [raw_login],
    }
    fill_distinguished_name(user_dict)
    user_id = user_dict["distinguished_name"]
    if configuration.user_openid_providers and configuration.user_openid_alias:
        user_dict["openid_names"].append(user_dict[configuration.user_openid_alias])

    req_path = None
    try:
        (os_fd, req_path) = tempfile.mkstemp(dir=user_pending)
        os.write(os_fd, dumps(user_dict))
        os.close(os_fd)
    except Exception, err:
        logger.error("Failed to write certificate request to %s: %s" % (req_path, err))
        output_objects.append(
            {
                "object_type": "error_text",
                "text": "Request could not be sent to grid administrators. Please contact them manually on %s if this error persists."
                % admin_email,
            }
        )
        return (output_objects, returnvalues.SYSTEM_ERROR)
示例#10
0
def main(client_id, user_arguments_dict):
    """Main function used by front end"""

    (configuration, logger, output_objects, op_name) = \
        initialize_main_variables(client_id, op_header=False, op_menu=False)
    defaults = signature()[1]
    logger.debug('in extoidaction: %s' % user_arguments_dict)
    (validate_status, accepted) = validate_input(user_arguments_dict,
            defaults, output_objects, allow_rejects=False)
    if not validate_status:
        return (accepted, returnvalues.CLIENT_ERROR)

    # Unfortunately OpenID does not use POST
    #if not safe_handler(configuration, 'post', op_name, client_id,
    #                    get_csrf_limit(configuration), accepted):
    #    output_objects.append(
    #        {'object_type': 'error_text', 'text': '''Only accepting
#CSRF-filtered POST requests to prevent unintended updates'''
    #         })
    #    return (output_objects, returnvalues.CLIENT_ERROR)

    title_entry = find_entry(output_objects, 'title')
    title_entry['text'] = '%s OpenID account sign up' % configuration.short_title
    title_entry['skipmenu'] = True
    output_objects.append({'object_type': 'header', 'text'
                          : '%s OpenID account sign up' % \
                            configuration.short_title 
                           })

    admin_email = configuration.admin_email
    smtp_server = configuration.smtp_server
    user_pending = os.path.abspath(configuration.user_pending)

    # force name to capitalized form (henrik karlsen -> Henrik Karlsen)

    id_url = os.environ['REMOTE_USER'].strip()
    openid_prefix = configuration.user_ext_oid_provider.rstrip('/') + '/'
    raw_login = id_url.replace(openid_prefix, '')
    full_name = accepted['openid.sreg.full_name'][-1].strip().title()
    country = accepted['openid.sreg.country'][-1].strip().upper()
    state = accepted['state'][-1].strip().title()
    organization = accepted['openid.sreg.organization'][-1].strip()
    organizational_unit = accepted['openid.sreg.organizational_unit'][-1].strip()
    locality = accepted['openid.sreg.locality'][-1].strip()

    # lower case email address

    email = accepted['openid.sreg.email'][-1].strip().lower()
    password = accepted['password'][-1]
    #verifypassword = accepted['verifypassword'][-1]

    # keep comment to a single line

    comment = accepted['comment'][-1].replace('\n', '   ')

    # single quotes break command line format - remove

    comment = comment.replace("'", ' ')

    user_dict = {
        'full_name': full_name,
        'organization': organization,
        'organizational_unit': organizational_unit,
        'locality': locality,
        'state': state,
        'country': country,
        'email': email,
        'password': password,
        'comment': comment,
        'expire': int(time.time() + oid_valid_days * 24 * 60 * 60),
        'openid_names': [raw_login],
        'auth': ['extoid'],
        }
    fill_distinguished_name(user_dict)
    user_id = user_dict['distinguished_name']
    if configuration.user_openid_providers and configuration.user_openid_alias:
        user_dict['openid_names'].append(
            user_dict[configuration.user_openid_alias])

    req_path = None
    try:
        (os_fd, req_path) = tempfile.mkstemp(dir=user_pending)
        os.write(os_fd, dumps(user_dict))
        os.close(os_fd)
    except Exception, err:
        logger.error('Failed to write OpenID account request to %s: %s'
                      % (req_path, err))
        output_objects.append({'object_type': 'error_text', 'text'
                              : 'Request could not be sent to grid administrators. Please contact them manually on %s if this error persists.'
                               % admin_email})
        return (output_objects, returnvalues.SYSTEM_ERROR)
示例#11
0
                 : '''Could not create the user account for you:
Please report this problem to the grid administrators (%s).''' % \
                 admin_email})
            return (output_objects, returnvalues.SYSTEM_ERROR)

        output_objects.append({'object_type': 'text', 'text'
                                   : '''Created the user account for you:
Please use the navigation menu to the left to proceed using it.
'''})
        return (output_objects, returnvalues.OK)

    # Without auto add we end here and go through the mail-to-admins procedure
    req_path = None
    try:
        (os_fd, req_path) = tempfile.mkstemp(dir=user_pending)
        os.write(os_fd, dumps(user_dict))
        os.close(os_fd)
    except Exception, err:
        logger.error('Failed to write existing certificate request to %s: %s'
                     % (req_path, err))
        output_objects.append(
            {'object_type': 'error_text', 'text'
             : """Request could not be sent to grid administrators. Please
contact them manually on %s if this error persists.""" % \
             admin_email})
        return (output_objects, returnvalues.SYSTEM_ERROR)

    logger.info('Wrote existing certificate sign up request to %s' % req_path)
    tmp_id = req_path.replace(user_pending, '')
    user_dict['tmp_id'] = tmp_id
示例#12
0
                            "Your resource is not allowed in the vgrid '%s' specified in the configuation for the '%s' execution unit. Please contact the vgrid owner and ask if you can be included in the vgrid."
                             % (vgrid_name, exe['name']))

    # save dictionary to a file

    if outfile == 'AUTOMATIC':

        # save configuration as python dictionary in the resource' private directory

        filename = configuration.resource_home + unique_resource_name\
             + '/config'
    elif outfile:

        # outfile specified (DumpConfig)

        filename = outfile
    else:
        return (True, 'Everything ok')
        
    try:
        fsock = open(filename, 'w')
        st = dumps(conf, 0)
        fsock.write(st)
        fsock.close()
    except Exception, err:
        return (False, "Fatal error: could not open '" + filename
                 + "' for writing!" + '\n Msg: ' + str(err))
    return (True, 'Everything ok, config updated')