Пример #1
0
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            if identity.in_group("issuer"):
                forward_url= url("issuer")
            elif identity.in_group("bidder"):
                forward_url= url("bidder")
            elif identity.in_group("admin"):
                forward_url = url("admin")           
            raise redirect(forward_url)

        forward_url=None
        previous_url= request.path

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= request.headers.get("Referer", "/")
            
        response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)
Пример #2
0
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            if identity.in_group("issuer"):
                forward_url = url("issuer")
            elif identity.in_group("bidder"):
                forward_url = url("bidder")
            elif identity.in_group("admin"):
                forward_url = url("admin")
            raise redirect(forward_url)

        forward_url = None
        previous_url = request.path

        if identity.was_login_attempted():
            msg = _("The credentials you supplied were not correct or "
                    "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg = _("You must provide your credentials before accessing "
                    "this resource.")
        else:
            msg = _("Please log in.")
            forward_url = request.headers.get("Referer", "/")

        response.status = 403
        return dict(message=msg,
                    previous_url=previous_url,
                    logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)
 def test_not_any(self):
     """Test the Not Any predicate."""
     yes = in_group('edit')
     no1, no2 = in_group('guest'), in_group('user')
     met = self.met
     assert not met(NotAny(yes))
     assert met(NotAny(no1, no2))
     assert not met(NotAny(no1, yes, no2))
 def test_all(self):
     """Test the All predicate."""
     yes1, yes2 = in_group('admin'), in_group('edit')
     no = in_group('guest')
     met = self.met
     assert not met(All(no))
     assert met(All(yes1, yes2))
     assert not met(All(yes1, no, yes2))
Пример #5
0
 def dump(self):
     person = People.by_username(identity.current.user_name)
     if identity.in_group(admin_group) or \
         identity.in_group(system_group):
         asterisk_attrs = {}
         for attr in Configs.query.filter_by(application='asterisk').all():
             if attr.person_id not in asterisk_attrs:
                 asterisk_attrs[attr.person_id] = {}
             asterisk_attrs[attr.person_id][attr.attribute] = attr.value
         return dict(asterisk_attrs=asterisk_attrs)
     return dict()
Пример #6
0
 def dump(self):
     dump_list = []
     person = People.by_username(identity.current.user_name)
     if identity.in_group(admin_group) or \
         identity.in_group(system_group):
         yubikey_attrs = {}
         for attr in Configs.query.filter_by(application='yubikey').all():
             if attr.person_id not in yubikey_attrs:
                 yubikey_attrs[attr.person_id] = {}
             yubikey_attrs[attr.person_id][attr.attribute] = attr.value
         for user_id in yubikey_attrs:
             if yubikey_attrs[user_id]['enabled'] == u'1':
                 dump_list.append('%s:%s' % (People.by_id(user_id).username, yubikey_attrs[user_id]['prefix']))
         return '\n'.join(dump_list)
     return '# Sorry, must be in an admin group to get these'
Пример #7
0
 def dump(self):
     dump_list = []
     person = People.by_username(identity.current.user_name)
     if identity.in_group(admin_group) or \
         identity.in_group(system_group):
         yubikey_attrs = {}
         for attr in Configs.query.filter_by(application='yubikey').all():
             if attr.person_id not in yubikey_attrs:
                 yubikey_attrs[attr.person_id] = {}
             yubikey_attrs[attr.person_id][attr.attribute] = attr.value
         for user_id in yubikey_attrs:
             if yubikey_attrs[user_id]['enabled'] == u'1':
                 dump_list.append('%s:%s' % (People.by_id(user_id).username, yubikey_attrs[user_id]['prefix']))
         return '\n'.join(dump_list)
     return '# Sorry, must be in an admin group to get these'
Пример #8
0
    def saveuser(self,oldname,name,address,college,water,notes,password,email,adjustment):
        if(oldname):
		try:
			u=User.by_user_name(oldname)
		except SQLObjectNotFound:
			flash("Error: Tried to edit a nonexistent player")
			raise redirect(url("/scoresname"))
		#u.user_name=name #don't give too much opportunity to break things
		u.address=address
		u.college=college
		u.water=water
		u.notes=notes
		if(password):
			u.password=password
		u.email_address=email
		if(adjustment!=u.adjustment and not identity.in_group('admin')):
			flash("Error: Tried to change a score adjustment while not umpire")
			raise redirect(url('/scoresname'))
		u.adjustment=adjustment
	else:
		u=User(user_name=name,address=address,college=college,water=water,notes=notes,password=password,email_address=email,score=0.0,adjustment=adjustment)
		p=Pseudonym(name=name,player=u)
	self.updatescores()
	flash("Player updated!")
	raise redirect(url("/scoresname"))
Пример #9
0
    def cp_on_http_error(self, status, message):
        """Handle HTTP errors by sending an error page and email."""

        try:
            cherrypy._cputil._cp_on_http_error(status, message)
            error_msg = self.get_error_message(status, message)
            url = "%s %s" % (cherrypy.request.method, cherrypy.request.path)
            log.exception("CherryPy %s error (%s) for request '%s'", status, error_msg, url)

            if status != 404:
                buf = StringIO.StringIO()
                traceback.print_exc(file=buf)
                details = buf.getvalue()
                buf.close()
            else:
                details = "404 error"

            data = dict(
                status=status,
                message=message,
                error_msg=error_msg,
                admin=identity.in_group(self.admin_group_name),
                url=url,
                details=details,
            )

            if status != 404 or config.get("error_catcher.send_email_on_404"):
                try:
                    self.send_exception_email(status, url, details)
                    data["email_sent"] = True
                except Exception, exc:
                    log.exception("Error email failed: %s", exc)
                    data["email_sent"] = False
            else:
 def disabled_fields(self, site=None):
     disabled_fields = []
     if not identity.in_group(admin_group):
         disabled_fields.append('admin_active')
     if site is not None:
         if not site.is_siteadmin(identity):
             for a in ['password', 'user_active', 'private']:
                 disabled_fields.append(a)
         
     return disabled_fields
    def disabled_fields(self, host=None):
        disabled_fields = []
        if not identity.in_group(admin_group):
            disabled_fields.append('admin_active')

        if host is not None:
            site = host.my_site()
            if not site.is_siteadmin(identity):
                for a in ['user_active', 'private', 'robot_email']:
                    disabled_fields.append(a)
        return disabled_fields
Пример #12
0
 def index(self, tg_errors=None, **kw):
     if tg_errors:          
         log.info('***********************************************************')
         log.info('TG_ERRORS: ' + str(tg_errors))
         log.info('KEYWORDS: ' + str(kw))
         log.info('***********************************************************')
         
         return self.__Issuer(tg_errors, **kw)        
     
     if(identity.in_group("issuer")):                        
         return self.__Issuer(**kw)        
     
     return {}
Пример #13
0
    def cp_on_http_error(self, status, message):
        """Handle HTTP errors by sending an error page and email."""

        try:
            cherrypy._cputil._cp_on_http_error(status, message)
            error_msg = self.get_error_message(status, message)
            url = "%s %s" % (cherrypy.request.method, cherrypy.request.path)
            headers = pprint.pformat(cherrypy.request.headers, indent=3)

            params = dict(cherrypy.request.params)
            for param in ["cvv", "cc_number"]:
                if param in params:
                    params[param] = "HIDDEN"
            for key in params.keys():
                if "password" in key.lower():
                    params[key] = "HIDDEN"
            params = pprint.pformat(params, indent=3)

            log.exception("CherryPy %s error (%s) for request '%s'", status,
              error_msg, url)

            if status != 404:
                buf = StringIO.StringIO()
                traceback.print_exc(file=buf)
                details = buf.getvalue()
                buf.close()
            else:
                details = '404 error'

            if identity.current.user:
                user = identity.current.user
            else:
                user = "******"

            data = dict(
                status = status,
                message = message,
                error_msg = error_msg,
                admin = identity.in_group(self.admin_group_name),
                url = url,
                details = details,
            )

            if status != 404 or turbogears.config.get('error_catcher.send_email_on_404'):
                try:
                    self.send_exception_email(status, url, details, user, headers, params)
                    data['email_sent'] = True
                except Exception, exc:
                    log.exception('Error email failed: %s', exc)
                    data['email_sent'] = False
            else:
Пример #14
0
class RestrictedArea(Controller, SecureResource):

    require = in_group('peon')

    [expose()]

    def index(self):
        return "restricted_index"

    [expose()]
    [identity.require(in_group('admin'))]

    def in_admin_group(self):
        return 'in_admin_group'

    [expose()]
    [identity.require(in_group('other'))]

    def in_other_group(self):
        return 'in_other_group'

    [expose()]

    def in_admin_group_explicit_check(self):
        if 'admin' not in identity.current.groups:
            raise identity.IdentityFailure("You need to be an Admin")
        else:
            return 'in_admin_group'

    [expose()]

    def in_other_group_explicit_check(self):
        if 'other' not in identity.current.groups:
            raise identity.IdentityException
        else:
            return 'in_other_group'
    def update(self, site, tg_errors=None, **kwargs):
        siteadmin_check(site, identity)

        if tg_errors is not None:
            submit_action = "/site/%s/update" % site.id
            turbogears.flash("Error updating Site: %s" % createErrorString(tg_errors))
            return dict(form=site_form, values=site, action=submit_action,
                        disabled_fields=self.disabled_fields())

        if not identity.in_group(admin_group) and kwargs.has_key('admin_active'):
            del kwargs['admin_active']
        site.set(**kwargs)
        site.sync()
        turbogears.flash("Site Updated")
        raise turbogears.redirect("/site/%s" % site.id)
    def update(self, host, tg_errors=None, **kwargs):
        siteadmin_check(host.my_site(), identity)

        if tg_errors is not None:
            submit_action = "/host/%s/update" % host.id
            turbogears.flash("Error updating Host: %s" % createErrorString(tg_errors))
            return dict(form=host_form, values=host, action=submit_action,
                        disabled_fields=self.disabled_fields(host=host), page_title="Host", site=host.site)


        if not identity.in_group(admin_group) and kwargs.has_key('admin_active'):
            del kwargs['admin_active']

        host.set(**kwargs)
        host.sync()
        turbogears.flash("Host Updated")
        raise turbogears.redirect("/host/%s" % host.id)
    def create(self, tg_errors=None, **kwargs):
        if not identity.in_group(admin_group) and kwargs.has_key('admin_active'):
            del kwargs['admin_active']
        kwargs['createdBy'] = identity.current.user_name

        if tg_errors is not None:
            turbogears.flash("Error creating Site: %s" % createErrorString(tg_errors))
            raise turbogears.redirect("/site/0/create")

        try:
            site = Site(**kwargs)
            SiteAdmin(site=site, username=identity.current.user_name)
        except: # probably sqlite IntegrityError but we can't catch that for some reason... 
            turbogears.flash("Error:Site %s already exists" % kwargs['name'])
            raise turbogears.redirect("/site/0/create")
        else:
            turbogears.flash("Site created.")
            raise turbogears.redirect("/site/%s" % site.id)
    def do_create(self, host, kwargs):
        max_ipv4_netblock_size = config.get('mirrormanager.max_ipv4_netblock_size', '/16')
        max_ipv6_netblock_size = config.get('mirrormanager.max_ipv6_netblock_size', '/32')

        emsg = "Error: IPv4 netblocks larger than %s, and IPv6 netblocks larger than %s can only be created by mirrormanager administrators.  Please ask the mirrormanager administrators for assistance." % (max_ipv4_netblock_size, max_ipv6_netblock_size)

        ipv4_block = IPy.IP('10.0.0.0%s' % max_ipv4_netblock_size)
        ipv6_block = IPy.IP('fec0::%s'   % max_ipv6_netblock_size)
        try:
            ip = IPy.IP(kwargs['netblock'])
            if ((ip.version() == 4 and ip.len() > ipv4_block.len()) or \
                    (ip.version() == 6 and ip.len() > ipv6_block.len())) and \
                    not identity.in_group(admin_group):
                raise InvalidData, emsg
        except ValueError:
            # also accept DNS hostnames
            pass
        
        HostNetblock(host=host, netblock=kwargs['netblock'], name=kwargs['name'])
Пример #19
0
    def index(self, program=None):
        program = util.session("current_program", identity.current.user.programID, program)
        if identity.in_group("global_admin") and int(program) == 0:
            userlist = User.select()
            program = identity.current.user.programID
        elif int(program) == 0:
            program = identity.current.user.programID
            userlist = User.selectBy(programID=program)
        else:
            userlist = User.selectBy(programID=program)
        programlist = Program.select()

        return dict(
            program=Program.get(program),
            programlist=programlist,
            curProg=self.curProg,
            userlist=userlist,
            shaded=util.shaded,
        )
Пример #20
0
class Root(controllers.RootController):
    def __init__(self):
        self.app = MenuApp()
        grooconfig.loadMenus(self.app)
        self.menus = Menus(self.app)

    @expose(template=".templates.menu")
    @identity.require(identity.in_group("admin"))
    def index(self, *args, **kw):
        redirect(tg.url('/menus'))

    @expose(template="grooserv.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous and identity.was_login_attempted() \
                and not identity.get_identity_errors():
            redirect(tg.url(forward_url or previous_url or '/', kw))

        forward_url = None
        previous_url = request.path

        if identity.was_login_attempted():
            msg = _("The credentials you supplied were not correct or "
                    "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg = _("You must provide your credentials before accessing "
                    "this resource.")
        else:
            msg = _("Please log in.")
            forward_url = request.headers.get("Referer", "/")

        response.status = 403
        return dict(message=msg,
                    previous_url=previous_url,
                    logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)

    @expose()
    def logout(self):
        identity.current.logout()
        redirect("/")
    def create(self, siteid=None, tg_errors=None, **kwargs):
        if not identity.in_group(admin_group) and kwargs.has_key('admin_active'):
            del kwargs['admin_active']
        site = Site.get(siteid)
        submit_action = "/host/0/create?siteid=%s" % site.id
        errordict = dict(form=host_form, values=None, action=submit_action, disabled_fields=self.disabled_fields(),
                         page_title="Create Host", site=site)

        # handle the validation error
        if tg_errors:
            turbogears.flash("Error creating Host: %s" % (createErrorString(tg_errors)))
            return errordict

        try:
            host = Host(site=site, **kwargs)
        except: # probably sqlite IntegrityError but we can't catch that for some reason... 
            turbogears.flash("Error:Host %s already exists" % kwargs['name'])
            return errordict
        
        
        turbogears.flash("Host created.")
        raise turbogears.redirect("/host/%s" % host.id)
Пример #22
0
 def saveuser(self, oldname, name, address, college, water, notes, password,
              email, adjustment):
     if (oldname):
         try:
             u = User.by_user_name(oldname)
         except SQLObjectNotFound:
             flash("Error: Tried to edit a nonexistent player")
             raise redirect(url("/scoresname"))
         #u.user_name=name #don't give too much opportunity to break things
         u.address = address
         u.college = college
         u.water = water
         u.notes = notes
         if (password):
             u.password = password
         u.email_address = email
         if (adjustment != u.adjustment and not identity.in_group('admin')):
             flash(
                 "Error: Tried to change a score adjustment while not umpire"
             )
             raise redirect(url('/scoresname'))
         u.adjustment = adjustment
     else:
         u = User(user_name=name,
                  address=address,
                  college=college,
                  water=water,
                  notes=notes,
                  password=password,
                  email_address=email,
                  score=0.0,
                  adjustment=adjustment)
         p = Pseudonym(name=name, player=u)
     self.updatescores()
     flash("Player updated!")
     raise redirect(url("/scoresname"))
Пример #23
0
    def fas_client(self, data=None, force_refresh=None):
        admin_group = config.get('admingroup', 'accounts')
        system_group = config.get('systemgroup', 'fas-system')
        thirdparty_group = config.get('thirdpartygroup', 'thirdparty')

        privs = {
            'admin': False,
            'system': False,
            'thirdparty': False,
        }

        if identity.in_group(admin_group):
            privs['admin'] = privs['system'] = privs['thirdparty'] = True
        elif identity.in_group(system_group):
            privs['system'] = privs['thirdparty'] = True
        elif identity.in_group(thirdparty_group):
            privs['thirdparty'] = True

        if data == 'group_data':
            groups = None
            if not force_refresh:
                groups = mc.get('group_data')
            if not groups:
                groups = {}
                groupjoin = [GroupsTable.outerjoin(PersonRolesTable,
                    PersonRolesTable.c.group_id == GroupsTable.c.id)]

                group_query = select([GroupsTable.c.id, GroupsTable.c.name,
                    GroupsTable.c.group_type, PersonRolesTable.c.person_id,
                    PersonRolesTable.c.role_status, PersonRolesTable.c.role_type],
                    from_obj=groupjoin)

                results = group_query.execute()

                for id, name, group_type, person_id, role_status, role_type in results:
                    if name not in groups:
                        groups[name] = {
                            'id': id,
                            'administrators': [],
                            'sponsors': [],
                            'users': [],
                            'type': group_type
                        }

                    if role_status != 'approved':
                        continue

                    if role_type == 'administrator':
                        groups[name]['administrators'].append(person_id)
                    elif role_type == 'sponsor':
                        groups[name]['sponsors'].append(person_id)
                    elif role_type == 'user':
                        groups[name]['users'].append(person_id)

                # Save cache - valid for 15 minutes
                mc.set('group_data', groups, 900)

            return dict(success=True, data=groups)
        elif data == 'user_data':
            people = {}
            people_list = select([
                PeopleTable.c.id,
                PeopleTable.c.username,
                PeopleTable.c.password,
                PeopleTable.c.human_name,
                PeopleTable.c.ssh_key,
                PeopleTable.c.email,
                PeopleTable.c.privacy,
                PeopleTable.c.alias_enabled
                ], PeopleTable.c.status == 'active').execute()
            for id, username, password, human_name, ssh_key, email, privacy, alias_enabled in people_list:
                people[id] = {
                    'username': username,
                    'password': password,
                    'human_name': human_name,
                    'ssh_key': ssh_key,
                    'email': email,
                    'alias_enabled': alias_enabled
                }

                if privacy:
                    # If they have privacy enabled, set their human_name to
                    # their username
                    people[id]['human_name'] = username

                if not privs['system']:
                    people[id]['password'] = '******'
                if not privs['thirdparty']:
                    people[id]['ssh_key'] = ''
            return dict(success=True, data=people)
        return dict(success=False, data={})
Пример #24
0
    def is_admin(self):
	return identity.in_group('admin')
Пример #25
0
    def is_validated(self):
	return identity.in_group('validated')
Пример #26
0
    def is_guest(self):
	return identity.in_group('guest')
 def disabled_fields(self, host=None):
     disabled_fields = []
     if not identity.in_group(admin_group):
         disabled_fields.append('admin_active')
         disabled_fields.append('always_up2date')
     return disabled_fields
Пример #28
0
class IssuerController(controllers.Controller,identity.SecureResource):
    require=identity.in_group("issuer")  
    
    #auction = AuctionController()
    @expose()
    def index(self, tg_errors=None, **kw):
        if tg_errors:          
            log.info('***********************************************************')
            log.info('TG_ERRORS: ' + str(tg_errors))
            log.info('KEYWORDS: ' + str(kw))
            log.info('***********************************************************')
            
            return self.__Issuer(tg_errors, **kw)        
        
        if(identity.in_group("issuer")):                        
            return self.__Issuer(**kw)        
        
        return {}

    expose()
    def __Issuer(self):
        
        a_fields = auction_fields[:]

        auction_grid = DataGrid(fields=a_fields)
        
        auctions = session.query(Auction)      
        
        return dict(tg_template="kid:mookii.templates.issuer",
                    auction_grid = auction_grid,
                    auctions = auctions,
                    Issuer_tabber=Tabber(),
                    now=datetime.today().strftime("%A, %d %b %Y")
                    )

    def default(self):
        raise redirect("index")

    @expose(template='kid:mookii.controllers.IssuerController.templates.list')
    #@paginate('records')
    def list(self, **kw):
        """List records in model"""
        records = session.query(Auction)

        return dict(records = records, modelname=self.modelname)

    @expose(template="kid:mookii.controllers.IssuerController.templates.paginate1")
    @paginate('auctions')
    def paginate1(self):
        
    
        auctions = session.query(Auction)
        return dict(auctions=auctions)


    @expose(template="kid:mookii.controllers.IssuerController.templates.paginate2")
    @paginate('auctions', default_order='auction_date')
    def paginate2(self):
        
        auction_list = PaginateDataGrid(
            fields=[
                PaginateDataGrid.Column('auction_date', 'auction_date', 'Auction Date'),
                PaginateDataGrid.Column('time_start', 'time_start', 'Start of Auction'),
                PaginateDataGrid.Column('cut_off', 'cut_off', 'End of Auction'),
                PaginateDataGrid.Column('status', 'status', 'Auction Status'),
                PaginateDataGrid.Column('created', 'created', 'Created'),
                ])

        sortable_auction_list = PaginateDataGrid(
            fields=[
                PaginateDataGrid.Column('auction_date', 'auction_date', 'Auction Date',
                                        options=dict(sortable=True, reverse_order=True)),
                PaginateDataGrid.Column('status', 'status', 'Auction Status',
                                        options=dict(sortable=True, reverse_order=True)),            
            ])
    
        auctions = session.query(Auction)
        return dict(auctions=auctions, list = sortable_auction_list)    
Пример #29
0
class AdminController(Controller, SecureResource):
    """
    The bodhi administration controller
    """
    require = identity.in_group("releng")

    @expose(template='bodhi.templates.admin')
    def index(self):
        return dict()

    @expose(template='bodhi.templates.masher', allow_json=True)
    def masher(self):
        """ Display the current status of the Masher """
        if config.get('masher'):
            data = self._masher_request('/admin/masher')
            if not data:
                data = {
                    'masher_str': 'Unable to contact the masher',
                    'tags': []
                }
            return dict(masher_str=data['masher_str'], tags=data['tags'])
        else:
            from bodhi.masher import masher
            tags = []
            for release in Release.select():
                tags.append(release.stable_tag)
                tags.append(release.testing_tag)
            return dict(masher_str=str(masher), tags=tags)

    @expose(template='bodhi.templates.text')
    def lastlog(self):
        """ Return the last mash log """
        from bodhi.masher import masher
        (logfile, data) = masher.lastlog()
        return dict(title=logfile, text=data)

    @expose(allow_json=True)
    def mash_tag(self, tag, **kw):
        """ Kick off a mash for a given tag """
        log.debug("mash_tag(%s)" % locals())
        if config.get('masher'):
            data = self._masher_request('/admin/mash_tag', tag=tag)
            if not data:
                flash_log("Mash request failed.  There may be an "
                          "existing mash that needs to be resumed first.")
            else:
                flash_log("Mash request %s" % data.get('success', 'failed'))
        else:
            from bodhi.masher import masher
            masher.mash_tags([tag])
            flash_log("Mashing tag: %s" % tag)
        raise redirect('/admin/masher')

    @expose(template='bodhi.templates.push', allow_json=True)
    def push(self):
        """ List updates tagged with a push/unpush/move request """
        updates = []
        resume = False
        mash = self._current_mash()
        if not mash:
            flash_log("A masher exception has occured.")
            return dict(updates=[], resume=False)
        if mash['mashing']:
            flash_log('The masher is currently pushing updates')
        else:
            for update in mash.get('updates', []):
                try:
                    updates.append(PackageUpdate.byTitle(update))
                except SQLObjectNotFound:
                    log.warning("Cannot find update %s in push queue" % update)
            if updates:
                flash_log('There is an updates push ready to be resumed')
                resume = True
            else:
                # Get a list of all updates with a request that aren't
                # unapproved security updates, or for a locked release
                requests = PackageUpdate.select(
                    PackageUpdate.q.request != None)

                # Come F13+, bodhi will not have locked releases.  It will
                # implement the 'No Frozen Rawhide' proposal, and treat 'locked'
                # releases as pending.
                #requests = filter(lambda update: not update.release.locked,
                #                  PackageUpdate.select(
                #                      PackageUpdate.q.request != None))
                for update in requests:
                    # Disable security approval requirement
                    #if update.type == 'security' and not update.approved:
                    #    continue
                    updates.append(update)
        return dict(updates=updates, resume=resume)

    @expose(allow_json=True)
    @validate(validators={'resume': validators.StringBool()})
    def mash(self, updates=None, resume=False, **kw):
        """ Mash a list of PackageUpdate objects.

        If this instance is deployed with a remote masher, then it simply
        proxies the request.  If we are the masher, then send these updates to
        our Mash instance.  This will then start a thread that takes care of
        handling all of the update requests, composing fresh repositories,
        generating and sending update notices, closing bugs, etc.
        """
        if not updates:
            updates = []
        if not isinstance(updates, list):
            if isinstance(updates, basestring):
                log.debug("Doing json hack")
                try:
                    updates = json.loads(
                        updates.replace("u'", "\"").replace("'", "\""))
                except:
                    log.debug("Didn't work, assuming it's a single update...")
                    updates = [updates]
            else:
                updates = [updates]

        # If we're not The Masher, then proxy this request to it
        if config.get('masher'):
            data = self._masher_request(
                '/admin/mash', updates=updates, resume=resume) or {}
            flash_log('Push request %s' %
                      (data.get('success') and 'succeeded' or 'failed'))
            raise redirect('/admin/masher')

        from bodhi.masher import masher
        masher.queue([PackageUpdate.byTitle(title) for title in updates],
                     resume=resume)
        if request_format() == 'json':
            return dict(success=True)
        flash("Updates queued for mashing")
        raise redirect('/admin/masher')

    def _current_mash(self):
        """ Return details about the mash in process """
        if config.get('masher', None):
            return self._masher_request('/admin/current_mash')

        from bodhi.masher import masher
        mash_data = {'mashing': False, 'updates': []}
        mashed_dir = config.get('mashed_dir')
        masher_lock_id = config.get('masher_lock_id', 'FEDORA')
        mash_lock = join(mashed_dir, 'MASHING-%s' % masher_lock_id)
        if exists(mash_lock):
            mash_lock = file(mash_lock)
            mash_state = pickle.load(mash_lock)
            mash_lock.close()
            mash_data['mashing'] = masher.mashing
            log.debug('mash_state = %s' % repr(mash_state))
            mash_data['updates'] = mash_state['updates']
        return mash_data

    @expose(allow_json=True)
    def current_mash(self):
        """ Return details about the mash in process """
        return self._current_mash()

    def _get_mash_status(self):
        """ Return details about the mash in process """

    def _masher_request(self, method, **kwargs):
        """
        Call a remote method on the masher with any other arguments.
        Returns whatever the remote method returned to us.
        """
        log.debug('Calling remote method "%s" with %s' % (method, kwargs))
        try:
            client = ProxyClient(config.get('masher'))
            cookie = SimpleCookie(cherrypy.request.headers.get('Cookie'))
            session, data = client.send_request(
                method,
                auth_params={'session_id': cookie.get('tg-visit').value},
                req_params=kwargs)
            log.debug("Remote method returned %s" % repr(data))
            if data.get('tg_flash'):
                flash_log(data['tg_flash'])
            return data
        except Exception, e:
            flash_log("Error: %s" % str(e))
            log.exception(e)
Пример #30
0
            msg = msg + '\n'.join(unbranched)
        else:
            num_branched = len(pkgs) - len(unbranched)
            msg = _('Succesfully branched all %(num)s packages') % \
                    {'num': num_branched}

        # Send an email to the user to tell them how things turned out
        eventlogger = EventLogger()
        eventlogger.send_msg(msg, _('Mass branching status for %(branch)s') %
                {'branch': to_branch.branchname},
                (author_email,))

    @expose(allow_json=True)
    @json_or_redirect('/collections')
    # Check that we have a tg.identity, otherwise you can't set any acls.
    @identity.require(identity.in_group(admin_grp))
    def mass_branch(self, branch):
        '''Mass branch all packages listed as non-blocked in koji to the pkgdb.

        Note: At some point, this will need to do the reverse: we'll maintain
        the list of dead packages in the pkgdb and sync that information to
        koji.

        Note: It is safe to call this method repeatedly.  If all packages have
        been branched already, new invokations will have no effect.

        :arg branch: Name of the branch to branch all packages for
        :returns: number of packages branched
        :raises InvalidBranch: If the branch does not exist in the pkgdb or
            koji
        :raises ServiceError: If we cannot log into koji
Пример #31
0
            except ValueError:
                flash(_(u"Invalid date and time specification, use: YYYY-MM-DD HH:MM"))
                raise redirect("/configuration/edit?id=%d" % item.id)
        else:
            valid_from = None

        try:
            item.set(kw['value'], valid_from, identity.current.user)
        except Exception, msg:
            flash(_(u"Failed to save setting: %s" % msg))
            raise redirect("/configuration/edit?id=%d" % item.id)

        flash(_(u"%s saved" % item.name))
        redirect(".")

    @identity.require(identity.in_group("admin"))
    @expose(template="bkr.server.templates.admin_grid")
    @paginate('list')
    def index(self, *args, **kw):
        configitems = session.query(ConfigItem)
        list_by_letters = set([elem.name[0].capitalize() for elem in configitems])
        results = self.process_search(**kw)
        if results:
            configitems = results
        configitems_grid = myPaginateDataGrid(fields=[
                                  ('Setting', lambda x: make_edit_link(x.name, x.id)),
                                  ('Description', lambda x: x.description),
                                  ('Current Value', lambda x: x.current_value()),
                                  ('Next Value', lambda x: x.next_value() and u'"%s" from %s' % (x.next_value().value, x.next_value().valid_from)),
                                  (' ', lambda x: (x.readonly or x.current_value() is None) and " " or
                                        make_link(url  = 'remove?id=%s' % x.id, text = 'Clear current value')),
Пример #32
0
                    .filter(Arch.id == kw.get('arch_id'))
        if kw.get('status'):
            tasks = tasks.filter(RecipeTask.status == kw['status'])
        if kw.get('result'):
            tasks = tasks.filter(RecipeTask.result == kw['result'])
        if kw.get('osmajor_id'):
            tasks = tasks.join(RecipeTask.recipe, Recipe.distro_tree,
                    DistroTree.distro, Distro.osversion, OSVersion.osmajor)\
                    .filter(OSMajor.id == kw.get('osmajor_id'))
        if kw.get('whiteboard'):
            tasks = tasks.join('recipe').filter(Recipe.whiteboard==kw.get('whiteboard'))
        return dict(tasks = tasks,
                    hidden = hidden,
                    task_widget = self.task_widget)

    @identity.require(identity.in_group('admin'))
    @expose()
    def disable_from_ui(self, t_id, *args, **kw):
        to_return = dict( t_id = t_id )
        try:
            self._disable(t_id)
            to_return['success'] = True
        except Exception, e:
            log.exception('Unable to disable task:%s' % t_id)
            to_return['success'] = False
            to_return['err_msg'] = unicode(e)
            session.rollback()
        return to_return

    def _disable(self, t_id, *args, **kw):
        """
Пример #33
0
    def filter_private(self, user='******', trust_argument=False):
        '''Filter out data marked private unless the user is authorized.

        Some data in this class can only be released if the user has not asked
        for it to be private.  Calling this method will filter the information
        out so it doesn't go anywhere.

        This method will disconnect the data structure from being persisted in
        the database and then remove the information that the user should not
        be allowed to see.

        If it's an admin, then all data will be returned.  If it's
        anything else, parts of the information will be removed.

        Note that it is not foolproof.  For instance, a template could be
        written that traverses from people to groups to a different person
        and retrieves information from there.  However, this would not be a
        standard use of this method so we should know when we're doing
        non-standard things and filter the data there as well.
        '''
        person_data = DictContainer()

        try:
            if not trust_argument:
                if identity.in_any_group(admin_group, system_group):
                    # Admin and system are the same for now
                    user = '******'
                elif identity.current.user_name == self.username:
                    user = '******'
                elif identity.current.anonymous:
                    user = '******'
                elif self.privacy:
                    user = '******'
                else:
                    user = '******'

            for field in self.allow_fields[user]:
                person_data[field] = self.__dict__[field]

            # thirdparty users need to get some things so that users can login to
            # their boxes.
            if identity.in_group(thirdparty_group):
                for field in self.allow_fields['thirdparty']:
                    person_data[field] = self.__dict__[field]
        except:
            # Typically this exception means this was called by shell
            for field in self.allow_fields[user]:
                person_data[field] = self.__dict__.get(field, '')

        # Instead of None password fields, we set it to '*' for easier fasClient
        # parsing
        if 'password' not in person_data:
            person_data['password'] = '******'

        # Make sure we have empty fields for the rest of the info
        for field in self.allow_fields['complete']:
            if field not in person_data:
                person_data[field] = None

        person_data['group_roles'] = {}
        for field in self.roles:
            person_data['group_roles'][field.groupname] = field

        person_data['memberships'] = list(self.memberships)
        person_data['roles'] = self.roles

        return person_data
Пример #34
0
class Root(controllers.RootController):

  @expose(template="dejagears.templates.page")
  def index(self, pagename="FrontPage" ):
    box = hub.getConnection()
    player_fields = {
      Player : [
        ('Name', 'name'),
        ('Birth Date', 'birthdate'),
        #('Team', 'team'),
        ('Points', 'points'),
      ],
      Team : [
        ('City', 'city'),
        ('NickName', 'nickname'),
      ],
    }
    team_fields = [
      ('City', 'city'),
      ('NickName', 'nickname'),
    ]
    page = box.Page(pagename=pagename)
    if page == None:
      raise turbogears.redirect("notfound", pagename = pagename)
    content = publish_parts(page.data, writer_name="html")['html_body']
    root = str(turbogears.url('/'))
    content = wikiwords.sub(r'<a href="%s\1">\1</a>' % root, content)
    return dict(
      data=content,
      page=page,
      players=box.recall(Team + Player),
      teams=box.recall(Team),
      players_widget=DataGrid(fields=player_fields),
      teams_widget=DataGrid(fields=team_fields),
    )
  
  @expose(template="dejagears.templates.edit")
  def edit(self,pagename):
    box = hub.getConnection()
    page = box.Page(pagename=pagename)
    return dict(page=page)

  @expose()
  @identity.require(identity.Any(identity.in_group("admin"),identity.has_permission("ls")))
  def save(self, pagename, data, submit):
    box = hub.getConnection() #.begin( isolation = turbogears.database.SERIALIZABLE )
    self.increment_counter()
    page = box.Page(pagename=pagename)
    if page == None:
      page = Page(pagename=pagename,data=data)
      box.memorize(page)
    page.data = data
    turbogears.flash("Changes saved!")
    raise turbogears.redirect("/", pagename=pagename)
    
  @expose()
  def default_values(self):
    "Set some default values in the database"
    
    # Add some information
    box = hub.getConnection()
    t1 = Team(city='Pittsburgh', nickname='Ferrous Metals')
    box.memorize(t1)
    t2 = Team(city='Seattle', nickname='Seagulls')
    box.memorize(t2)
    p1 = Player(name='Bob Waffleburger', birthdate=datetime.date(1982,3,2), points=21)
    box.memorize(p1)
    p2 = Player(name='Mike Handleback', birthdate=datetime.date(1975,9,25), points=10)
    box.memorize(p2)
    p1.team = t1.ID
    p2.team = t2.ID
    
    # Add a default Page
    page = Page( pagename="FrontPage", data="This is the main page, please edit it." )
    box.memorize( page )
    
    # Setup identity data 
    jrodrigo = TG_User( user_name = "jrodrigo" )
    box.memorize( jrodrigo )
    jrodrigo.password = "******"
    
    root = TG_User( user_name = "root" )
    box.memorize( root )
    root.password = "******"
    
    user = TG_Group( group_name = "user" )
    box.memorize( user )
    
    admin = TG_Group( group_name = "admin" )
    box.memorize( admin )
    
    format = TG_Permission( permission_name = "format" )
    box.memorize( format )
    ls = TG_Permission( permission_name = "ls" )
    box.memorize( ls )
    cat = TG_Permission( permission_name = "cat" )
    box.memorize( cat )
    
    o = TG_UserGroup( user_id = root.user_id, group_id = user.group_id )
    box.memorize( o )
    o = TG_UserGroup( user_id = root.user_id, group_id = admin.group_id )
    box.memorize( o )
    o = TG_UserGroup( user_id = jrodrigo.user_id, group_id = user.group_id )
    box.memorize( o )
    
    o = TG_GroupPermission( group_id = admin.group_id, permission_id = format.permission_id )
    box.memorize( o )
    o = TG_GroupPermission( group_id = user.group_id, permission_id = ls.permission_id )
    box.memorize( o )
    o = TG_GroupPermission( group_id = user.group_id, permission_id = cat.permission_id )
    box.memorize( o )
    
    return "done"

  @expose()
  def default(self, pagename):
    return self.index(pagename)

  @expose("dejagears.templates.edit")
  def notfound(self, pagename):
    page = Page(pagename=pagename, data="")
    return dict(page=page)

  @expose("dejagears.templates.pagelist")
  @expose("json")
  def pagelist(self):
    box = hub.getConnection()
    self.increment_counter()
    pages = box.recall(Page)
    pages.sort(dejavu.sort('pagename'))
    pages = [page.pagename for page in pages]
    return dict(pages=pages)

  def increment_counter(self):
    # We call acquire_lock at the beginning
    #   of the method
    cherrypy.session.acquire_lock()
    c = cherrypy.session.get('counter', 0) + 1
    cherrypy.session['counter'] = c
    return str(c)
  increment_counter.exposed = True

  def read_counter(self):
    # No need to call acquire_lock
    #   because we're only reading
    #   the session data
    c = cherrypy.session.get('counter', 0) + 1
    return str(c)
  read_counter.exposed = True
    
  @expose()
  def logout(self):
    identity.current.logout()
    raise redirect("/")
  
  @expose("json")
  def lookup( self ):
    user = identity.current.user
    print user.userId
    print user.emailAddress
    print user.displayName
    group = user.groups.pop()
    print group.groupId
    print group.displayName
    permission = user.permissions.pop()
    print permission.permissionId
    
    print permission.groups

    print group.permissions
    print group.users
    
    print user.groups
    print user.permissions
    
    return [
      jsonify.encode( identity.current.user ),
      jsonify.encode( identity.current.user.groups.pop() ),
      jsonify.encode( identity.current.user.permissions.pop() ),
    ]

  @expose("dejagears.templates.login")
  def login(self, forward_url=None, previous_url=None, *args, **kw):
  
    if not identity.current.anonymous \
        and identity.was_login_attempted() \
        and not identity.get_identity_errors():
      raise redirect(forward_url)

    forward_url=None
    previous_url= request.path
  
    if identity.was_login_attempted():
      msg=_("The credentials you supplied were not correct or "
             "did not grant access to this resource.")
    elif identity.get_identity_errors():
      msg=_("You must provide your credentials before accessing "
             "this resource.")
    else:
      msg=_("Please log in.")
      forward_url= request.headers.get("Referer", "/")
      
    response.status=403
    return dict(message=msg, previous_url=previous_url, logging_in=True,
                original_parameters=request.params,
                forward_url=forward_url)

  @expose()
  @identity.require(identity.has_permission("format"))
  def format_only(self):
      return "format_only"
  
  @expose()
  @identity.require(identity.in_group("admin"))
  def root_only(self):
      return "root_only"
  
  @expose()
  @identity.require(identity.Any(identity.has_permission("ls"),identity.has_permission("format")))
  def both(self):
      return "both"
  
  @expose()
  @identity.require(identity.All(identity.has_permission("format"),identity.in_group("user")))
  def all(self):
      return "all"
Пример #35
0
 def test_in_group(self):
     """Test the predicate for requiring a group."""
     assert self.met(in_group('admin'))
     assert not self.met(in_group('guest'))
Пример #36
0
class IdentityRoot(RootController):

    [expose()]

    def index(self):
        pass

    [expose()]

    def identity_failed(self, **kw):
        cherrypy.response.status = 401
        return 'identity_failed_answer'

    [expose()]
    [identity.require(not_anonymous())]

    def logged_in_only(self):
        return 'logged_in_only'

    [expose()]
    [identity.require(in_group('peon'))]

    def in_peon_group(self):
        return 'in_peon_group'

    [expose()]

    def test_exposed_require(self):
        if not hasattr(self.in_peon_group, '_require'):
            return 'no _require attr'
        if not isinstance(self.in_peon_group._require, in_group):
            return 'not correct class'
        if 'peon' != self.in_peon_group._require.group_name:
            return 'not correct group name'
        return '_require is exposed'

    [expose()]
    [identity.require(in_group('admin'))]

    def in_admin_group(self):
        return 'in_admin_group'

    [expose()]
    [identity.require(has_permission('chops_wood'))]

    def has_chopper_permission(self):
        return 'has_chopper_permission'

    [expose()]
    [identity.require(has_permission('bosses_people'))]

    def has_boss_permission(self):
        return "has_boss_permission"

    [expose()]

    def logout(self):
        identity.current.logout()
        return "logged out"

    [expose()]
    [identity.require(not_anonymous())]

    def user_email(self):
        return identity.current.user.email_address

    peon_area = RestrictedArea()

    [expose()]

    def new_user_setup(self, user_name, password):
        return '%s %s' % (user_name, password)

    _test_encoded_params = ('b=krümel&d.a=klöße1')

    [expose()]
    [identity.require(not_anonymous())]

    def test_params(self, **kwargs):
        params = self._test_encoded_params
        # formencode's variable_decode create a datastructure
        #  but does not "decode" anything
        to_datastruct = formencode.variabledecode.variable_decode
        expected_params = to_datastruct(
            dict([p.split('=') for p in params.split('&')]))
        params_ok = True
        if not expected_params['b'].decode(
                'utf8') == cherrypy.request.params['b']:
            params_ok = False
        if not expected_params['d']['a'].decode(
                'utf8') == cherrypy.request.params['d']['a']:
            params_ok = False
        if params_ok:
            return 'params ok'
        else:
            return 'wrong params: %s\nexpected unicode objects' \
                ' for all strings' % cherrypy.request.params
Пример #37
0
class PrivateBackend(controllers.Controller, identity.SecureResource):
    require = identity.in_group("admin")

    @expose(
        template="infoshopkeeperonline.templates.private.uncategorizedtitles")
    def uncategorized(self, letter=""):
        all_titles = []
        if letter == "":
            all_titles = Title.select("kind_id=1", orderBy='booktitle')
        else:
            all_titles = Title.select(
                """kind_id=1 and booktitle LIKE '%s%%'""" %
                (escape_string(letter)),
                orderBy='booktitle')

        return dict(
            titles=[t for t in all_titles if len(list(t.sections)) == 0])

    @expose(template="infoshopkeeperonline.templates.private.outofstocktitles")
    def outofstock(self, letter=""):
        all_titles = []
        if letter == "":
            all_titles = Title.select("kind_id=1", orderBy='booktitle')
        else:
            all_titles = Title.select(
                """kind_id=1 and booktitle LIKE '%s%%'""" %
                (escape_string(letter)),
                orderBy='booktitle')

        return dict(
            titles=[t for t in all_titles if t.copies_in_status("STOCK") == 0])

    @expose(template="infoshopkeeperonline.templates.private.unconfirmedtitles"
            )
    def unconfirmed(self, letter=""):
        all_titles = []
        if letter == "":
            all_titles = Title.select("kind_id=1", orderBy='booktitle')
        else:
            all_titles = Title.select(
                """kind_id=1 and booktitle LIKE '%s%%'""" %
                (escape_string(letter)),
                orderBy='booktitle')
        unconfirmed_titles = []
        for t in all_titles:
            if t.copies_in_status(
                    'STOCK') > 0:  # or t.copies_in_status('UNKNOWN')>0:
                t.unconfirmed_books = []
                for b in [
                        b for b in t.books
                        if (b.status == 'STOCK' or b.status == 'UNKNOWN')
                ]:
                    tags = b.get_tags(
                        'inventory',
                        'confirmation11')  #needs a date eventually!
                    if len(tags) == 0:
                        t.unconfirmed_books.append(b)
                if len(t.unconfirmed_books) > 0:
                    unconfirmed_titles.append(t)

        return dict(titles=unconfirmed_titles)

    @expose()
    def persistsection(self, section, activate):
        if not (session.has_key('persisting_sections')):
            session['persisting_sections'] = []
        if activate == 'true':
            session['persisting_sections'].append(section)
        else:
            session['persisting_sections'].remove(section)
        return "OK"

    @expose(template="infoshopkeeperonline.templates.private.reinventory")
    def reinventory(self, isbn="", author="", title=""):
        searchform = widgets.TableForm(fields=PrivateSearchFields(),
                                       submit_text="Search!")
        if author == "" and title == "" and isbn == "":
            the_titles = False
        else:
            the_titles = Title.select("""
            title.isbn LIKE '%%%s%%' AND
            author.id=author_title.author_id AND
            author_title.title_id=title.id AND author.author_name LIKE '%%%s%%' AND title.booktitle LIKE '%%%s%%'
            """ % (escape_string(isbn), escape_string(author),
                   escape_string(title)),
                                      orderBy="booktitle",
                                      clauseTables=['author', 'author_title'],
                                      distinct=True)

        title_count = 0
        try:
            title_count = the_titles.count()
        except:
            pass
        if title_count > 0:
            if the_titles.count() == 1:
                return self.title(the_titles[0].id,
                                  searchvalues=dict(author=author,
                                                    title=title,
                                                    isbn=isbn))

        return dict(the_titles=the_titles,
                    authorswidget=PrivateAuthorsWidget(),
                    titlelistwidget=PrivateTitleListWidget(),
                    searchform=searchform,
                    values=dict(author=author, title=title, isbn=isbn))

    @expose(template="infoshopkeeperonline.templates.private.title")
    def title(self, id, searchvalues=None):
        thetitle = Title.get(id)
        searchform = widgets.TableForm(fields=PrivateSearchFields(),
                                       submit_text="Search!")
        titleform = widgets.TableForm(
            name="titleform",
            fields=PrivateTitleFields(),
            submit_text="modify this title's sections and distributor")
        titlepersistenceform = widgets.TableForm(
            fields=PrivateTitlePersistenceFields(), submit_text="")
        persisting_sections = []
        #       try:
        #           persisting_sections=session['persisting_sections']
        #       except:
        #           session['persisting_sections']=[]
        #       print persisting_sections
        #        sections=list(set(thetitle.get_tag_collection(category='inventory',key='section')))
        #        sections=thetitle.sections
        #      sections.extend(persisting_sections)
        print[s.id for s in list(thetitle.sections)]

        return dict(thetitle=thetitle,
                    authorswidget=PrivateAuthorsWidget(),
                    searchform=searchform,
                    searchvalues=searchvalues,
                    titleform=titleform,
                    today=strftime("%Y-%m-%d", gmtime()),
                    titlepersistenceform=titlepersistenceform,
                    titlesections=[s.id for s in list(thetitle.sections)],
                    persisting_sections=persisting_sections)

    @expose(template="infoshopkeeperonline.templates.private.checktrans")
    def checktrans(self, what):
        transactions = Transaction.select("""info LIKE '%%%s%%'""" %
                                          (escape_string(what)),
                                          orderBy='date')
        return dict(transactions=transactions)

    @expose()
    def reordertag(self, title_id):
        title = Title.get(title_id)
        title.set_tag(category="inventory",
                      key="reorder",
                      value=identity.current.user_name)
        return "1"

    @expose()
    def statustag(self, book_id, status):
        book = Book.get(book_id)
        if status == "CONFIRM":
            book.status = "STOCK"
            book.set_tag(category="inventory",
                         key="confirmation11",
                         value="stock")
        else:
            if status == "SOLD":
                book.sold_when = now()
                book.status = "SOLD"
                book.set_tag(category="inventory",
                             key="confirmation11",
                             value="sold_at_some_point")
            else:
                book.status = status
                book.set_tag(category="inventory",
                             key="confirmation11",
                             value="removed")
        return book.status

    @expose()
    def confirm(self, title, book, **kw):
        book = Book.get(book)
        title = Title.get(title)
        book.set_tag(category="inventory", key="confirmation11", value="stock")
        return self.title(title.id)

    @expose(template="infoshopkeeperonline.templates.private.section")
    def section(self, section_id, **kw):
        section = Section.get(section_id)
        return dict(section=section)

    @expose()
    def edit_title(self, title_id, **kw):
        title = Title.get(title_id)
        if kw['preferred_distributor']:
            title.set_unique_tag(category='distribution',
                                 key='preferred',
                                 value=kw['preferred_distributor'])
        if kw.has_key('sections'):
            the_sections = kw['sections']
            if type(the_sections) != type([0, 1]):
                the_sections = [the_sections]
            #title.set_tag_collection(category='inventory',key='section',values=the_sections)
            for s in title.sections:
                print "Removing %s" % s
                title.removeSection(s)
            for s in the_sections:
                print "Adding %s" % s
                title.addSection(Section.get(s))

        return self.title(title_id)
Пример #38
0
 def is_siteadmin(self, identity):
     admin_group = config.get('mirrormanager.admin_group', 'sysadmin')
     if identity.in_group(admin_group):
         return True
     return self.is_siteadmin_byname(identity.current.user_name)
Пример #39
0
class Root(controllers.RootController):
    @expose(template="tumpire.templates.index")
    # @identity.require(identity.in_group("admin"))
    def index(self):
        # log.debug("Happy TurboGears Controller Responding For Duty")
        #flash("Your application is now running")
        return {}

    @expose(template="tumpire.templates.rules")
    def rules(self):
        return {}

    @expose(template="tumpire.templates.weapons")
    def weapons(self):
        return {}

    @expose(template="tumpire.templates.changes")
    def changes(self):
        return {}

    @expose(template="tumpire.templates.rulings")
    def rulings(self):
        return {}

    @expose(template="tumpire.templates.scoring")
    def scoring(self):
        return {}

    @expose(template="tumpire.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            raise redirect(forward_url)

        forward_url = None
        previous_url = request.path

        if identity.was_login_attempted():
            msg = _("The credentials you supplied were not correct or "
                    "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg = _("You must provide your credentials before accessing "
                    "this resource.")
        else:
            msg = _("Please log in.")
            forward_url = request.headers.get("Referer", "/")

        response.status = 403
        return dict(message=msg,
                    previous_url=previous_url,
                    logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)

    @expose(template="tumpire.templates.players")
    def scoresname(self):
        return {'players': User.select(orderBy='user_name')}

    @expose(template="tumpire.templates.players")
    def scorescollege(self):
        return {'players': User.select(orderBy='college')}

    @expose(template="tumpire.templates.players")
    def scoresrank(self):
        return {'players': User.select(orderBy='score')}

    @expose(template="tumpire.templates.news")
    def news(self):
        return {'events': Event.select(orderBy='datetime')}

    @expose(template="tumpire.templates.updates")
    def updates(self):
        return {'events': Event.select(orderBy='datetime')}

    @expose(template="tumpire.templates.addreportselevent")
    def addreportselevent(self):
        return {}

    @expose()
    def logout(self):
        identity.current.logout()
        raise redirect(url("/"))

    @expose(template="tumpire.templates.edituser")
    def edituser(self, player):
        try:
            return {'user': User.by_user_name(player), 'new': False}
        except SQLObjectNotFound:
            flash("Error: Tried to edit a nonexistent user")
            raise redirect(url("/scoresname"))

    @expose(template="tumpire.templates.edituser")
    def adduser(self):
        return {'new': True}

    @expose()
    @validate(validators={'adjustment': Number()})
    def saveuser(self, oldname, name, address, college, water, notes, password,
                 email, adjustment):
        if (oldname):
            try:
                u = User.by_user_name(oldname)
            except SQLObjectNotFound:
                flash("Error: Tried to edit a nonexistent player")
                raise redirect(url("/scoresname"))
            #u.user_name=name #don't give too much opportunity to break things
            u.address = address
            u.college = college
            u.water = water
            u.notes = notes
            if (password):
                u.password = password
            u.email_address = email
            if (adjustment != u.adjustment and not identity.in_group('admin')):
                flash(
                    "Error: Tried to change a score adjustment while not umpire"
                )
                raise redirect(url('/scoresname'))
            u.adjustment = adjustment
        else:
            u = User(user_name=name,
                     address=address,
                     college=college,
                     water=water,
                     notes=notes,
                     password=password,
                     email_address=email,
                     score=0.0,
                     adjustment=adjustment)
            p = Pseudonym(name=name, player=u)
        self.updatescores()
        flash("Player updated!")
        raise redirect(url("/scoresname"))

    @expose(template="tumpire.templates.editpseudonym")
    @validate(validators={'id': Int()})
    def editpseudonym(self, id):
        return {'id': id, 'new': False}

    @expose(template="tumpire.templates.editpseudonym")
    def addpseudonym(self, player):
        return {'new': True, 'playerid': player}

    @expose()
    @validate(validators={'playerid': Int(), 'new': StringBoolean()})
    def savepseudonym(self, new, name, playerid, id=0, submit=""):
        if (new):
            try:
                p = Pseudonym(player=User.get(playerid), name=name)
            except SQLObjectNotFound:
                flash("Error: Tried to add a pseudonym to a nonexistent user")
                raise redirect(url("/scoresname"))
        else:
            try:
                p = Pseudonym.get(id)
            except SQLObjectNotFound:
                flash("Error: Tried to edit a nonexistent pseudonym")
                raise redirect(url("/scoresname"))
            p.name = name
        flash("Pseudonym updated!")
        raise redirect(url("/edituser/" + p.player.user_name))

    @expose(template="tumpire.templates.editevent")
    @validate(validators={'id': Int()})
    def editevent(self, id):
        return {'id': id, 'new': False}

    @expose(template="tumpire.templates.editevent")
    def addevent(self):
        return {'new': True}

    @expose()
    @validate(validators={'new': StringBoolean()})
    def saveevent(self, new, headline, timestamp, id=0):
        try:
            t = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
        except ValueError:
            flash("Error: You entered an invalid date/time")
            raise redirect(url("/news"))
        if (t.year <= 1900 or t.year >= 2020):
            flash("Error: Absurd year %d" % t.year)
            raise redirect(url("/news"))
        if (new):
            e = Event(headline=headline, datetime=t)
            flash("Event Added!")
            raise redirect(url("/editevent/" + str(e.id)))
        else:
            try:
                e = Event.get(id)
            except SQLObjectNotFound:
                flash("Error: Tried to edit a nonexistent event")
                raise redirect(url("/news"))
            e.headline = headline
            e.datetime = t
        flash("Event Updated!")
        raise redirect(url("/news"))

    @expose()
    @validate(validators={'id': Int()})
    @identity.require(identity.in_group('admin'))
    def deleteevent(self, id):
        try:
            Event.delete(id)
            flash("Event deleted!")
            raise redirect(url("/news"))
        except SQLObjectNotFound:
            flash("Error: Tried to delete an event that doesn't exist")
            raise redirect(url("/news"))

    @expose(template="tumpire.templates.editparticipant")
    @validate(validators={'id': Int()})
    def editparticipant(self, id):
        return {'id': id, 'new': False}

    @expose(template="tumpire.templates.editparticipant")
    @validate(validators={'eid': Int()})
    def addparticipant(self, eid):
        try:
            return {'new': True, 'event': Event.get(eid)}
        except SQLObjectNotFound:
            flash("Error: Tried to add participant to a nonexistent event")
            raise redirect(url("/news"))

    @expose()
    @validate(validators={'new': StringBoolean(), 'eid': Int()})
    def saveparticipant(self, new, eid, player, pseudonym="", id=0, submit=""):
        if (new):
            try:
                for q in Event.get(eid).participants:
                    if (q.player.user_name == player):
                        flash(
                            "Error: %s is already a participant in this event"
                            % player)
                        raise redirect(url("/editevent/" + str(eid)))
                p = Participant(event=Event.get(eid),
                                player=User.by_user_name(player),
                                pseudonym=Pseudonym.byName(player))
            except SQLObjectNotFound:
                flash(
                    "Error: Tried to add a participant to a nonexistent event")
                raise redirect(url("/news"))
        else:
            try:
                p = Participant.get(id)
            except SQLObjectNotFound:
                flash("Error: Tried to edit a nonexistent participant")
                raise redirect(url("/news"))
            try:
                p.player = User.by_user_name(player)
                p.pseudonym = Pseudonym.byName(pseudonym)
            except SQLObjectNotFound:
                flash(
                    "Error: Tried to change pseudonym to one that doesn't exist, or change pseudonym for a player that doesn't exist"
                )
                raise redirect(url("/news"))
        flash("Participant updated!")
        raise redirect(url("/editevent/" + str(eid)))

    @expose(template="tumpire.templates.editreport")
    @validate(validators={'id': Int()})
    @identity.require(identity.not_anonymous())
    def editreport(self, id):
        return {'id': id, 'new': False}

    @expose(template="tumpire.templates.editreport")
    @validate(validators={'eid': Int()})
    @identity.require(identity.not_anonymous())
    def addreport(self, eid):
        try:
            return {'new': True, 'event': Event.get(eid)}
        except SQLObjectNotFound:
            flash("Error: Tried to add report to a nonexistent event")
            raise redirect(url("/news"))

    @expose()
    @validate(validators={'new': StringBoolean(), 'eid': Int(), 'id': Int()})
    def savereport(self, new, eid, player, text, id=0):
        if (new):
            try:
                r = Report(speaker=User.by_user_name(player),
                           event=Event.get(eid),
                           content=text)
            except SQLObjectNotFound:
                flash(
                    "Error: Tried to add report by a nonexistent player, or to a nonexistent event"
                )
                raise redirect(url("/news"))
        else:
            try:
                r = Report.get(id)
                r.content = text
                #nothing else really should be being edited, but will update it all for future compatibility
                r.speaker = User.by_user_name(player)
                r.event = Event.get(eid)
            except SQLObjectNotFound:
                flash(
                    "Error: Tried to edit a nonexistent report, or a report for a nonexistent event, or write a report as a nonexistent player."
                )
                raise redirect(url("/news"))
        flash("Report updated!")
        raise redirect(url("/news"))

    @expose(template="tumpire.templates.addkill")
    @validate(validators={'eid': Int()})
    def addkill(self, eid):
        try:
            return {'event': Event.get(eid)}
        except SQLObjectNotFound:
            flash("Error: Tried to add a kill to a nonexistent event.")
            raise redirect(url("/news"))

    @expose()
    @validate(validators={'eid': Int()})
    def savekill(self, eid, killer, victim):
        try:
            for k in Event.get(eid).kills:
                if (k.victim == User.by_user_name(victim)):
                    flash(
                        "Error: %s is already marked as being killed in this event, by %s. If they didn't kill %s, delete that kill first."
                        % (victim, k.killer, victim))
                    raise redirect(url("/editevent/" + str(eid)))
            k = Kill(event=Event.get(eid),
                     killer=User.by_user_name(killer),
                     victim=User.by_user_name(victim))
            self.updatescores()
            flash("Kill added!")
            for l in Kill.select():
                if (l.id != k.id):
                    if ((l.victim == k.victim or l.victim == k.killer)
                            and l.event.datetime < k.event.datetime
                            and l.event.datetime >=
                        (k.event.datetime - datetime.timedelta(0, 14400))):
                        flash(
                            "Warning: %s is listed as being killed in the event %s, which was less than four hours before this event."
                            % (l.victim.user_name, str(l.event)))
                    if (l.victim == k.victim
                            and k.event.datetime <= l.event.datetime
                            and k.event.datetime >=
                        (l.event.datetime - datetime.timedelta(0, 14400))):
                        flash(
                            "Warning: %s is listed as dying again in the event %s, which is less than four hours after this event."
                            % (k.victim.user_name, str(l.event)))
                    if (l.killer == k.victim
                            and k.event.datetime < l.event.datetime
                            and k.event.datetime >=
                        (l.event.datetime - datetime.timedelta(0, 14400))):
                        flash(
                            "Warning: %s is listed as killing someone else in the event %s, which is less than four hours after this event."
                            % (k.victim.user_name, str(l.event)))
            raise redirect(url("/editevent/" + str(eid)))
        except SQLObjectNotFound:
            flash("Error: Tried to add a kill to a nonexistent event.")
            raise redirect(url("/news"))

    @expose()
    @validate(validators={'kid': Int()})
    def deletekill(self, kid):
        try:
            eid = Kill.get(kid).event.id
        except SQLObjectNotFound:
            flash("Error: you tried to delete a kill that doesn't exist!")
            raise redirect(url("/news"))
        Kill.delete(kid)
        self.updatescores()
        flash("Kill removed!")
        raise redirect(url("/editevent/" + str(eid)))

    @expose(template="tumpire.templates.addinnocentkill")
    @validate(validators={'eid': Int()})
    def addinnocentkill(self, eid):
        try:
            return {'event': Event.get(eid)}
        except SQLObjectNotFound:
            flash(
                "Error: Tried to add an innocent kill to a nonexistent event.")
            raise redirect(url("/news"))

    @expose()
    @validate(validators={'eid': Int(), 'licit': StringBoolean()})
    def saveinnocentkill(self, eid, killer, licit):
        try:
            k = InnocentKill(event=Event.get(eid),
                             killer=User.by_user_name(killer),
                             licit=licit)
            self.updatescores()
            flash("Innocent Kill added!")
            for l in Kill.select():
                if ((l.victim == k.killer)
                        and l.event.datetime < k.event.datetime
                        and l.event.datetime >=
                    (k.event.datetime - datetime.timedelta(0, 14400))):
                    flash(
                        "Warning: %s is listed as being killed in the event %s, which was less than four hours before this event."
                        % (l.victim.user_name, str(l.event)))
            raise redirect(url("/editevent/" + str(eid)))
        except SQLObjectNotFound:
            flash(
                "Error: Tried to add an innocent kill to a nonexistent event.")
            raise redirect(url("/news"))

    @expose()
    @validate(validators={'iid': Int()})
    def deleteinnocentkill(self, iid):
        try:
            eid = InnocentKill.get(iid).event.id
        except SQLObjectNotFound:
            flash(
                "Error: you tried to delete an innocent kill that doesn't exist!"
            )
            raise redirect(url("/news"))
        InnocentKill.delete(iid)
        self.updatescores()
        flash("Innocent Kill removed!")
        raise redirect(url("/editevent/" + str(eid)))

    def updatescores(self):
        glicko = {}
        innocent_vector = [0, 1, 2, 4, 6, 9, 13, 17, 23]
        for u in User.select():
            glicko[u.user_name] = (1500, 350, 0.06)
        kills = Kill.select()
        gamestart = datetime.datetime(2008, 6, 13, 17, 0, 0)
        for i in range(42):
            glicko = glickostep(glicko, [
                x for x in kills if x.event.datetime >= gamestart +
                datetime.timedelta(i * 14400) and x.event.datetime <
                gamestart + datetime.timedelta((i + 1) * 14400)
            ])
        for u in glicko:
            p = User.by_user_name(u)
            i = 0
            for ik in InnocentKill.select():
                if (ik.killer == p and not ik.licit):
                    i += 1
            p.score = glicko[u][0] - glicko[u][
                1] + p.adjustment - 35 * innocent_vector[min(i, 8)]
        return
Пример #40
0
class Menus:
    def __init__(self, menuapp):
        self.app = menuapp

    def strongly_expire(func):
        """Decorator that sends headers that instruct browsers and proxies not to cache.
        """
        def newfunc(*args, **kwargs):
            cherrypy.response.headers[
                'Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT'
            cherrypy.response.headers[
                'Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
            cherrypy.response.headers['Pragma'] = 'no-cache'
            return func(*args, **kwargs)

        return newfunc

    @expose(template=".templates.menu")
    @strongly_expire
    @identity.require(identity.in_group("admin"))
    def default(self, menu=None, action=None):

        # is this a valid menu name?
        m = None
        try:
            m = self.app.menus[menu]
        except:
            m = self.app.currentMenu()
        if m == None:
            m = self.app.currentMenu()

        if action != None:
            try:
                if action == 'm':
                    self.app.processTransition(m, 'm', self.app.webModeHandler)
                else:
                    idx = int(action)
                    self.app.processTransition(m, str(idx),
                                               self.app.webModeHandler)
            except:
                print formatExceptionInfo()

        # After transition, set up new page
        cmenu = self.app.currentMenu()
        menuname = cmenu.title
        tupleList = [("", "")]
        wlist = []
        mitems = cmenu.menuitems

        for i in range(0, len(mitems)):
            tupleList.append(
                ('/menus/' + self.app.currentmenu + '?action=' + str(i + 1),
                 mitems[i][0]))

        jump = widgets.JumpMenu("Options", options=tupleList)
        wlist.append(jump.js)
        wlist.append(jump)

        hc = self.app.hardcopyReady
        sr = self.app.shellResult

        if hc != None:
            self.app.hardcopyReady = None
            try:
                f = open(self.app.hardcopies[hc], 'r')
                txt = f.read()
                f.close()
                wlist.append(
                    widgets.TextArea(default=txt,
                                     rows=24,
                                     cols=80,
                                     attrs={'READONLY': 'true'}))
            except:
                wlist.append(
                    widgets.TextArea(default='No screen available.',
                                     rows=24,
                                     cols=80,
                                     attrs={'READONLY': 'true'}))

        if sr != None:
            self.app.shellResult = None
            wlist.append(
                widgets.TextArea(default=sr,
                                 rows=24,
                                 cols=80,
                                 attrs={'READONLY': 'true'}))

        return dict(title=cmenu.title, wlist=wlist)
Пример #41
0
class UserController(controllers.Controller, identity.SecureResource):
    """Basic model admin interface"""
    modelname = "User"
    require = identity.in_group("admin")

    @expose()
    def default(self, tg_errors=None):
        """handle non exist urls"""
        raise redirect("list")

    #require = identity.in_group("admin")
    @expose()
    def index(self):
        raise redirect("list")

    @expose(template='kid:repo.templates.crudlist')
    @paginate('records')
    def list(self, **kw):
        """List records in model"""
        records = User.select()

        grid = PaginateDataGrid(
            fields=[('User Id',
                     'user_id'), ('User Name', 'user_name'), (
                         'Show',
                         show_link), ('Edit',
                                      edit_link), ('Delete', destroy_link)])

        return dict(records=records,
                    modelname=self.modelname,
                    grid=grid,
                    now=datetime.today().strftime("%A, %d %b %Y"))

    @expose(template='kid:repo.controllers.UserController.templates.new')
    def new(self, **kw):
        """Create new records in model"""

        return dict(modelname=self.modelname,
                    form=model_form,
                    now=datetime.today().strftime("%A, %d %b %Y"))

    @expose(template='kid:repo.controllers.UserController.templates.edit')
    def edit(self, id, **kw):
        """Edit record in model"""

        try:
            record = User.get(int(id))
            group_defaults = [entry.group_id for entry in record.groups]
        except:
            flash = "Not valid edit"

        log.info("user_name: " + str(record.user_name))
        log.info("group_defaults: " + str(group_defaults))

        return dict(
            modelname=self.modelname,
            record=record,
            value=dict(user_name=record.user_name,
                       status=record.status,
                       user_groups=group_defaults,
                       display_name=record.display_name,
                       password='******',
                       password_confirm='password'),
            #options=dict(user_groups=[(entry.group_id, entry.group_name) for entry in Group.select()]),
            form=model_edit_form,
            now=datetime.today().strftime("%A, %d %b %Y"))

    @expose(template='kid:repo.controllers.UserController.templates.show')
    def show(self, id, **kw):
        """Show record in model"""
        record = User.get(int(id))

        return dict(record=record,
                    now=datetime.today().strftime("%A, %d %b %Y"))

    @expose()
    def destroy(self, id):
        """Destroy record in model"""
        record = User.get(int(id))
        session.delete(record)
        flash("User was successfully destroyed.")
        raise redirect("../list")

    @validate(model_form)
    @error_handler(new)
    @expose()
    def save(self, id=None, **kw):
        """Save or create record to model"""
        #update kw

        log.info('kw: ' + str(kw))
        log.info('kw: ' + str(kw))
        log.info('kw: ' + str(kw))
        log.info('kw: ' + str(kw))
        log.info('kw: ' + str(kw))

        try:
            if isinstance(kw['user_groups'], list):
                groups = Group.select(Group.c.group_id.in_(*kw['user_groups']))
            else:
                groups = Group.select(Group.c.group_id.in_(kw['user_groups']))
        except:
            groups = []

        #create
        if not id:
            kw['groups'] = groups
            User(**kw)
            flash("User was successfully created.")
            raise redirect("list")
        #update
        else:

            record = User.get_by(user_id=int(id))
            for attr in kw:
                setattr(record, attr, kw[attr])
            record.groups = groups
            log.info("Saved update on user " + record.user_name + str(kw))

            flash("User was successfully updated.")
            raise redirect("../list")

    @validate(model_edit_form)
    @error_handler(edit)
    @expose()
    def update(self, id=None, **kw):
        """Save or create record to model"""
        #update kw

        log.info('kw: ' + str(kw))
        log.info('kw: ' + str(kw))
        log.info('kw: ' + str(kw))
        log.info('kw: ' + str(kw))
        log.info('kw: ' + str(kw))

        try:
            if isinstance(kw['user_groups'], list):
                groups = Group.select(Group.c.group_id.in_(*kw['user_groups']))
            else:
                groups = Group.select(Group.c.group_id.in_(kw['user_groups']))
        except:
            groups = []

        #create
        if not id:
            kw['groups'] = groups
            User(**kw)
            flash("User was successfully created.")
            raise redirect("list")
        #update
        else:

            record = User.get_by(user_id=int(id))
            for attr in kw:
                if attr == 'password':
                    setattr(record, attr, identity.encrypt_password(kw[attr]))
                else:
                    setattr(record, attr, kw[attr])
            record.groups = groups
            log.info("Saved update on user " + record.user_name + str(kw))

            flash("User was successfully updated.")
            raise redirect("../list")
Пример #42
0
    def filter_private(self, user='******'):
        '''Filter out data marked private unless the user is authorized.

        Some data in this class can only be released if the user has not asked
        for it to be private.  Calling this method will filter the information
        out so it doesn't go anywhere.

        This method will disconnect the data structure from being persisted in
        the database and then remove the information that the user should not
        be allowed to see.

        If it's an admin, then all data will be returned.  If it's
        anything else, parts of the information will be removed.

        Note that it is not foolproof.  For instance, a template could be
        written that traverses from people to groups to a different person
        and retrieves information from there.  However, this would not be a
        standard use of this method so we should know when we're doing
        non-standard things and filter the data there as well.
        '''
        person_data = DictContainer()

        try:
            if identity.in_any_group(admin_group, system_group):
                # Admin and system are the same for now
                user ='******'
            elif identity.current.user_name == self.username:
                user = '******'
            elif identity.current.anonymous:
                user = '******'
            elif self.privacy:
                user = '******'
            else:
                user = '******'

            for field in self.allow_fields[user]:
                person_data[field] = self.__dict__[field]

            # thirdparty users need to get some things so that users can login to
            # their boxes.
            if identity.in_group(thirdparty_group):
                for field in self.allow_fields['thirdparty']:
                    person_data[field] = self.__dict__[field]
        except:
            # Typically this exception means this was called by shell
            for field in self.allow_fields[user]:
                person_data[field] = self.__dict__[field]

        # Instead of None password fields, we set it to '*' for easier fasClient
        # parsing
        if 'password' not in person_data:
            person_data['password'] = '******'

        # Make sure we have empty fields for the rest of the info
        for field in self.allow_fields['complete']:
            if field not in person_data:
                person_data[field] = None

        person_data['group_roles'] = {}
        for field in self.roles:
            person_data['group_roles'][field.groupname] = field

        person_data['memberships'] = list(self.memberships)
        person_data['roles'] = self.roles


        return person_data
Пример #43
0
    def fas_client(self, data=None, force_refresh=None):
        admin_group = config.get('admingroup', 'accounts')
        system_group = config.get('systemgroup', 'fas-system')
        thirdparty_group = config.get('thirdpartygroup', 'thirdparty')

        privs = {
            'admin': False,
            'system': False,
            'thirdparty': False,
        }

        if identity.in_group(admin_group):
            privs['admin'] = privs['system'] = privs['thirdparty'] = True
        elif identity.in_group(system_group):
            privs['system'] = privs['thirdparty'] = True
        elif identity.in_group(thirdparty_group):
            privs['thirdparty'] = True

        if data == 'group_data':
            groups = None
            if not force_refresh:
                groups = mc.get('group_data')
            if not groups:
                groups = {}
                groupjoin = [
                    GroupsTable.outerjoin(
                        PersonRolesTable,
                        PersonRolesTable.c.group_id == GroupsTable.c.id)
                ]

                group_query = select([
                    GroupsTable.c.id, GroupsTable.c.name,
                    GroupsTable.c.group_type, PersonRolesTable.c.person_id,
                    PersonRolesTable.c.role_status,
                    PersonRolesTable.c.role_type
                ],
                                     from_obj=groupjoin)

                results = group_query.execute()

                for id, name, group_type, person_id, role_status, role_type in results:
                    if name not in groups:
                        groups[name] = {
                            'id': id,
                            'administrators': [],
                            'sponsors': [],
                            'users': [],
                            'type': group_type
                        }

                    if role_status != 'approved':
                        continue

                    if role_type == 'administrator':
                        groups[name]['administrators'].append(person_id)
                    elif role_type == 'sponsor':
                        groups[name]['sponsors'].append(person_id)
                    elif role_type == 'user':
                        groups[name]['users'].append(person_id)

                # Save cache - valid for 15 minutes
                mc.set('group_data', groups, 900)

            return dict(success=True, data=groups)
        elif data == 'user_data':
            people = {}
            people_list = select([
                PeopleTable.c.id, PeopleTable.c.username,
                PeopleTable.c.password, PeopleTable.c.human_name,
                PeopleTable.c.ssh_key, PeopleTable.c.email,
                PeopleTable.c.privacy, PeopleTable.c.alias_enabled
            ], PeopleTable.c.status == 'active').execute()
            for id, username, password, human_name, ssh_key, email, privacy, alias_enabled in people_list:
                people[id] = {
                    'username': username,
                    'password': password,
                    'human_name': human_name,
                    'ssh_key': ssh_key,
                    'email': email,
                    'alias_enabled': alias_enabled
                }

                if privacy:
                    # If they have privacy enabled, set their human_name to
                    # their username
                    people[id]['human_name'] = username

                if not privs['system']:
                    people[id]['password'] = '******'
                if not privs['thirdparty']:
                    people[id]['ssh_key'] = ''
            return dict(success=True, data=people)
        return dict(success=False, data={})
Пример #44
0
        else:
            num_branched = len(pkgs) - len(unbranched)
            msg = _('Succesfully branched all %(num)s packages') % \
                    {'num': num_branched}

        # Send an email to the user to tell them how things turned out
        eventlogger = EventLogger()
        eventlogger.send_msg(
            msg,
            _('Mass branching status for %(branch)s') %
            {'branch': to_branch.branchname}, (author_email, ))

    @expose(allow_json=True)
    @json_or_redirect('/collections')
    # Check that we have a tg.identity, otherwise you can't set any acls.
    @identity.require(identity.in_group(admin_grp))
    def mass_branch(self, branch):
        '''Mass branch all packages listed as non-blocked in koji to the pkgdb.

        Note: At some point, this will need to do the reverse: we'll maintain
        the list of dead packages in the pkgdb and sync that information to
        koji.

        Note: It is safe to call this method repeatedly.  If all packages have
        been branched already, new invokations will have no effect.

        :arg branch: Name of the branch to branch all packages for
        :returns: number of packages branched
        :raises InvalidBranch: If the branch does not exist in the pkgdb or
            koji
        :raises ServiceError: If we cannot log into koji