Ejemplo n.º 1
0
    def login(self):
        if self.request.POST:
            username = self.request.POST.get('username')
            password = self.request.POST.get('password')
            try:
                user = self.request.userdb.login(username, password)
            except UserDoesNotExist:
                return {
                    'username': username,
                    'message': self.translate(
                        _("Please enter the correct username and password")),
                }

            if user is False:
                return {
                    'username': username,
                    'message': self.translate(_("Please enter the correct username and password")),
                }

            headers = remember(self.request, username)
            created_msg(self.request, self.translate(
                _('Welcome ${username}',
                  mapping={'username': user['username']})
            ), 'info')


            return HTTPFound(location=self.request.route_path('home'),
                             headers=headers)
        else:
            return {}
Ejemplo n.º 2
0
    def login(self):
        if self.request.POST:
            username = self.request.POST.get('username')
            password = self.request.POST.get('password')
            try:
                user = self.request.userdb.login(username, password)
            except UserDoesNotExist:
                return {
                    'username':
                    username,
                    'message':
                    self.translate(
                        _("Please enter the correct username and password")),
                }

            if user is False:
                return {
                    'username':
                    username,
                    'message':
                    self.translate(
                        _("Please enter the correct username and password")),
                }

            headers = remember(self.request, username)
            created_msg(
                self.request,
                self.translate(
                    _('Welcome ${username}',
                      mapping={'username': user['username']})), 'info')
            return HTTPFound(location=self.request.route_path('home'),
                             headers=headers)
        else:
            return {}
Ejemplo n.º 3
0
def settings_save(_context, request):
    data = request.POST.get('data')
    response = Response()
    if data is not None:
        data = json.loads(data)
        for key in data:
            k = key.replace("___", ".")
            setting_data = request.db.settings.find_one({"key": k})
            if setting_data is None:
                setting = create_setting(k)
            else:
                setting = Setting().deserialize(setting_data)

            if isinstance(data[key], str):
                Setting().set_value(setting, 'value', data[key])
            else:
                Setting().set_value(setting, 'value', json.dumps(data[key]))

            # Save in mongoDB
            obj = Setting().serialize(setting)
            if obj['_id'] == colander.null:
                del obj['_id']
                request.db.settings.insert_one(obj)
            else:
                obj['_id'] = ObjectId(obj['_id'])
                request.db.settings.replace_one({'_id': obj['_id']}, obj)

    messages.created_msg(request, _('Settings modified successfully'),
                         'success')
    response.write('SUCCESS')
    return response
Ejemplo n.º 4
0
def settings_save(_context, request):
    data = request.POST.get('data')
    response = Response()
    if data is not None:
        data = json.loads(data)
        for key in data:
            k = key.replace("___", ".")
            setting_data = request.db.settings.find_one({"key": k })
            if setting_data is None:
                setting = create_setting(k)
            else:
                setting = Setting().deserialize(setting_data)
            
            if isinstance(data[key], str) or isinstance(data[key], unicode):
                Setting().set_value(setting, 'value', data[key])
            else:
                Setting().set_value(setting, 'value', json.dumps(data[key]))
            
            # Save in mongoDB
            obj = Setting().serialize(setting)
            if obj['_id'] == colander.null:
                del obj['_id']
            else:
                obj['_id'] = ObjectId(obj['_id'])
            #logger.debug('save= %s'%(obj))
            request.db.settings.save(obj)
                                    
    messages.created_msg(request, _('Settings modified successfully'), 'success')
    response.write('SUCCESS')
    return response
Ejemplo n.º 5
0
def admins_superuser(context, request):
    username = request.matchdict['username']
    if '_superuser' in request.POST:
        is_superuser = True
        message = _('Now the user is a super user')
    elif '_no_superuser' in request.POST:
        is_superuser = False
        message = _('Now the user is not a super user')
        message.translate('es')
    request.userdb.collection.update({'username': username}, {'$set': {'is_superuser': is_superuser}})
    messages.created_msg(request, message, 'success')
    return HTTPFound(location=request.route_url('admins'))
Ejemplo n.º 6
0
def admin_delete(context, request):
    if request.method != 'DELETE':
        raise HTTPMethodNotAllowed("Only delete method is accepted")
    username = request.GET.get('username')
    if request.session['auth.userid'] == username:
        forget(request)
    settings = get_current_registry().settings
    api = get_chef_api(settings, request.user)
    success_remove_chef = delete_chef_admin_user(api, username)
    if not success_remove_chef:
        messages.created_msg(request, _('User deleted unsuccessfully from chef'), 'danger')
    request.userdb.delete_users({'username': username})
    messages.created_msg(request, _('User deleted successfully'), 'success')
    return {'ok': 'ok'}
Ejemplo n.º 7
0
def admins_superuser(context, request):
    username = request.matchdict['username']
    if '_superuser' in request.POST:
        is_superuser = True
        message = _('Now the user is a super user')
    elif '_no_superuser' in request.POST:
        is_superuser = False
        message = _('Now the user is not a super user')
        message.translate('es')
    request.userdb.collection.update({'username': username},
                                     {'$set': {
                                         'is_superuser': is_superuser
                                     }})
    messages.created_msg(request, message, 'success')
    return HTTPFound(location=request.route_url('admins'))
Ejemplo n.º 8
0
def admin_delete(context, request):
    if request.method != 'DELETE':
        raise HTTPMethodNotAllowed("Only delete method is accepted")
    username = request.GET.get('username')
    if request.session['auth.userid'] == username:
        forget(request)
    settings = get_current_registry().settings
    api = get_chef_api(settings, request.user)
    success_remove_chef = delete_chef_admin_user(api, username)
    if not success_remove_chef:
        messages.created_msg(request,
                             _('User deleted unsuccessfully from chef'),
                             'danger')
    request.userdb.delete_user({'username': username})
    messages.created_msg(request, _('User deleted successfully'), 'success')
    return {'ok': 'ok'}
Ejemplo n.º 9
0
def updates_repeat(_context, request):
    settings = get_current_registry().settings
    sequence = request.matchdict.get('sequence')
    logger.debug('admins.py ::: updates_repeat - sequence = %s' % sequence)

    # Check sequence number
    to_repeat = request.db.updates.find_one({'_id': sequence})
    if to_repeat is None:
        logging.error('admins.py ::: updates_repeat: ' + \
                      'update not found with sequence=%s'%(sequence))
        raise HTTPNotFound()

    updatefile = os.path.join(to_repeat['path'], to_repeat['name'])
    if not os.path.isfile(updatefile):
        raise HTTPNotFound()

    if re.match(SERIALIZED_UPDATE_PATTERN, to_repeat['name']) is not None:
        logging.error('admins.py ::: updates_repeat: ' + \
                      'update %s is a serialized update!'%(sequence))
        raise HTTPBadRequest()

    if 'repetition' in to_repeat:
        logging.error('admins.py ::: updates_repeat: ' + \
                      'update %s is repetition!'%(sequence))
        raise HTTPBadRequest()

    try:
        # Calculate the next repetition number for this update
        count = request.db.updates.count_documents({
            'name': to_repeat['name'],
            'repetition': {
                '$exists': True
            }
        })

        nrep = 0
        if count > 0:
            cursor = request.db.updates.find(
                {
                    'name': to_repeat['name'],
                    'repetition': {
                        '$exists': True
                    }
                }, {
                    '_id': 1,
                    'repetition': 1
                }).sort('repetition', -1).limit(1)

            latest = int(cursor.next().get('repetition'))
            nrep = (latest + 1)

        logger.debug('admins.py ::: updates_repeat - repetition = %s' % nrep)

        # Copy the zip file
        separator = '_'
        rsequence = '%s%s%s' % (sequence, separator, nrep)
        updatesdir = settings['updates.dir'] + rsequence
        while os.path.exists(updatesdir):
            separator = separator + '_'
            rsequence = '%s%s%s' % (sequence, separator, nrep)
            updatesdir = settings['updates.dir'] + rsequence

        os.mkdir(updatesdir)
        shutil.copy(updatefile, os.path.join(updatesdir, to_repeat['name']))

        # Decompress zip file
        zip_ref = zipfile.ZipFile(updatefile, 'r')
        zip_ref.extractall(updatesdir)
        zip_ref.close()

        # Decompress cookbook zipfile
        cookbookdir = settings['updates.cookbook'].format(rsequence)
        logger.debug('admins.py ::: updates_repeat - ' + \
                     ' cookbookdir = %s' % cookbookdir)
        for cookbook in os.listdir(cookbookdir):
            cookbook = cookbookdir + os.sep + cookbook
            logger.debug("admins.py ::: updates_repeat - cookbook = %s" %
                         cookbook)
            if zipfile.is_zipfile(cookbook):
                zip_ref = zipfile.ZipFile(cookbook, 'r')
                zip_ref.extractall(
                    os.path.join(cookbookdir, settings['chef.cookbook_name']))
                zip_ref.close()

        # Insert update register
        request.db.updates.insert_one({
            '_id': rsequence,
            'name': to_repeat['name'],
            'path': updatesdir,
            'timestamp': int(time.time()),
            'rollback': 0,
            'user': request.user['username'],
            'repetition': nrep
        })

        # Launching task for script execution
        script_runner.delay(request.user, rsequence)

        messages.created_msg(request, _('The update has been repeated!'),
                             'success')

    except:
        e = sys.exc_info()[0]
        logger.error("admins.py ::: updates_repeat - " + \
            "error repeating update: %s"%(str(e)))
        logger.error("Traceback: %s" % (traceback.format_exc()))
        messages.created_msg(
            request, _('There was an error trying to repeat an update'),
            'danger')

    return HTTPFound(request.route_url('updates'))
Ejemplo n.º 10
0
def settings_save(context, request):
    data = request.POST.get('data')
    settings = request.db.settings.find()
    response = Response()
    if data is not None:
        data = json.loads(data)
        for key in data:
            k = key.replace("___", ".")
            setting_data = request.db.settings.find_one({"key": k })
            if setting_data is None:
                setting = create_setting(k)
            else:
                setting = Setting().deserialize(setting_data)
            
            if isinstance(data[key], str) or isinstance(data[key], unicode):
                Setting().set_value(setting, 'value', data[key])
            else:
                Setting().set_value(setting, 'value', json.dumps(data[key]))
            
            # Save in mongoDB
            obj = Setting().serialize(setting)
            if obj['_id'] == colander.null:
                del obj['_id']
            else:
                obj['_id'] = ObjectId(obj['_id'])
            #logger.debug('save= %s'%(obj))
            request.db.settings.save(obj)
            
            # If saving "software_profiles", save them also in "software_profiles" collection
            if key == "software_profiles":
                collection = request.db.software_profiles
                # Update the software profiles
                for new_profile in data[key]:
                    name = new_profile['name']
                    db_profile = collection.find_one({'name': name})
                    
                    if not db_profile:
                        collection.insert(new_profile)
                        logger.debug("Created profile: %s" % name)

                    elif new_profile['packages'] != db_profile['packages']:
                        collection.update({'name': name}, new_profile)
                        logger.debug("Updated profile: %s" % name)

                # Check if the user is trying to delete a software profile
                sp_policy = request.db.policies.find_one({"slug" : "package_profile_res"})
                if not sp_policy:
                    messages.created_msg(request, _('Software Profiles policy not found'), 'warning')
                    response.write('SUCCESS')
                    return response
                    
                db_profiles = collection.find()
                for profile in db_profiles:
                    profile_found = False
                    for new_profile in data[key]:
                        if new_profile['name'] == profile['name']:
                            profile_found = True
                            
                    if not profile_found:
                        # Check if we can delete the software profile
                        # (the software profile is not in use)
                        logger.debug("Try to delete: %s - %s"%(str(profile['_id']), profile['name']))
                        obj_related_list = "policies.%s.object_related_list"%(str(sp_policy['_id']))
                        profile_id = str(profile['_id'])
                        nnodes = request.db.nodes.find({obj_related_list : profile_id}).count()
                        logger.debug("Found %s nodes"%(nnodes))
                        
                        if nnodes == 0:
                            # It it's not used we can delete it
                            collection.remove({"_id": profile['_id']})
                        else:
                            # It's used, so we can't delete it
                            messages.created_msg(request, _('Software Profile in use: %s')%(profile['name']), 'warning')
                            response.write('SUCCESS')
                            return response
                        
                        
                        
    messages.created_msg(request, _('Settings modified successfully'), 'success')
    response.write('SUCCESS')
    return response
Ejemplo n.º 11
0
 def created_msg(self, msg, msg_type='success'):
     messages.created_msg(self.request, msg, msg_type)
Ejemplo n.º 12
0
 def created_msg(self, msg, msg_type='success'):
     messages.created_msg(self.request, msg, msg_type)
Ejemplo n.º 13
0
def settings_save(context, request):
    data = request.POST.get('data')
    settings = request.db.settings.find()
    response = Response()
    if data is not None:
        data = json.loads(data)
        for key in data:
            k = key.replace("___", ".")
            setting_data = request.db.settings.find_one({"key": k })
            if setting_data is None:
                setting = create_setting(k)
            else:
                setting = Setting().deserialize(setting_data)
            
            if isinstance(data[key], str) or isinstance(data[key], unicode):
                Setting().set_value(setting, 'value', data[key])
            else:
                Setting().set_value(setting, 'value', json.dumps(data[key]))
            
            # Save in mongoDB
            obj = Setting().serialize(setting)
            if obj['_id'] == colander.null:
                del obj['_id']
            else:
                obj['_id'] = ObjectId(obj['_id'])
            #logger.debug('save= %s'%(obj))
            request.db.settings.save(obj)
            
            # If saving "software_profiles", save them also in "software_profiles" collection
            if key == "software_profiles":
                collection = request.db.software_profiles
                # Update the software profiles
                for new_profile in data[key]:
                    name = new_profile['name']
                    db_profile = collection.find_one({'name': name})
                    
                    if not db_profile:
                        collection.insert(new_profile)
                        logger.debug("Created profile: %s" % name)

                    elif new_profile['packages'] != db_profile['packages']:
                        collection.update({'name': name}, new_profile)
                        logger.debug("Updated profile: %s" % name)

                # Check if the user is trying to delete a software profile
                sp_policy = request.db.policies.find_one({"slug" : "package_profile_res"})
                if not sp_policy:
                    messages.created_msg(request, _('Software Profiles policy not found'), 'warning')
                    response.write('SUCCESS')
                    return response
                    
                db_profiles = collection.find()
                for profile in db_profiles:
                    profile_found = False
                    for new_profile in data[key]:
                        if new_profile['name'] == profile['name']:
                            profile_found = True
                            
                    if not profile_found:
                        # Check if we can delete the software profile
                        # (the software profile is not in use)
                        logger.debug("Try to delete: %s - %s"%(str(profile['_id']), profile['name']))
                        obj_related_list = "policies.%s.object_related_list"%(str(sp_policy['_id']))
                        profile_id = str(profile['_id'])
                        nnodes = request.db.nodes.find({obj_related_list : profile_id}).count()
                        logger.debug("Found %s nodes"%(nnodes))
                        
                        if nnodes == 0:
                            # It it's not used we can delete it
                            collection.remove({"_id": profile['_id']})
                        else:
                            # It's used, so we can't delete it
                            messages.created_msg(request, _('Software Profile in use: %s')%(profile['name']), 'warning')
                            response.write('SUCCESS')
                            return response
                        
                        
                        
    messages.created_msg(request, _('Settings modified successfully'), 'success')
    response.write('SUCCESS')
    return response