Beispiel #1
0
class Root(RootController):
    @expose(template='videostore.templates.index')
    @identity.require(identity.not_anonymous())
    def index(self):
        return dict(movies=Movie.query.all())

    @expose(template='videostore.templates.movie')
    @identity.require(identity.not_anonymous())
    @validate(validators=dict(movieID=validators.Int()))
    def movie(self, movieID):
        return dict(movie=Movie.get(movieID))

    @expose(template='videostore.templates.actor')
    @identity.require(identity.not_anonymous())
    @validate(validators=dict(actorID=validators.Int()))
    def actor(self, actorID):
        return dict(actor=Actor.get(actorID))

    @expose(template='videostore.templates.director')
    @identity.require(identity.not_anonymous())
    @validate(validators=dict(directorID=validators.Int()))
    def director(self, directorID):
        return dict(director=Director.get(directorID))

    @expose(template='videostore.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.'
        elif identity.get_identity_errors():
            msg = 'You must provide your credentials.'
        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()
        raise redirect("/")
Beispiel #2
0
 def join(self, show=None):
     if not show:
         turbogears.redirect('/show/list/')
     if identity.not_anonymous():
         identity.current.logout()
     show = Show.by_name(show)
     return dict(show=show)
Beispiel #3
0
    def add_user(self,
                 show,
                 username,
                 human_name,
                 email,
                 telephone=None,
                 postal_address=None,
                 age_check=False):
        if identity.not_anonymous():
            identity.current.logout()
        try:
            user = \
                self._root.user.create_user(username, human_name, email,
                                            telephone, postal_address,
                                            age_check,
                                            redirect='/show/join/%s' % show)

            show = Show.by_name(show)
            user.show = show
        except IntegrityError:
            turbogears.flash(
                _("Your account could not be created.  Please contact a Fedora Ambassador for assistance."
                  ))
            turbogears.redirect('/show/fail/%s' % show)
            return dict()
        else:
            turbogears.flash(
                _('Your password has been emailed to you.  Please log in with it and change your password'
                  ))
            turbogears.redirect('/show/success/%s' % show)

        turbogears.redirect('/show/join/%s' % show)
Beispiel #4
0
def get_hubspace_locale():
    """get the locale based on the home hub of the user or the base_url and the name of the hub
    """
    #if user is not logged in, then reset the locale
    try:
        if identity.not_anonymous() and '_' not in cherrypy.session.get('locale', ''):
            cherrypy.session['locale'] = ''
        locale = cherrypy.session.get('locale', '')
        if locale:
            return locale

        if identity.current.anonymous:
            locale = site_default_lang.get(cherrypy.request.base, 'en')
        else:
            locale = get_hubspace_user_locale()

        cherrypy.session['locale'] = locale
        tool = tool_instance()

        if os.path.exists(tool.get_locale_catalog(locale, "messages")):
            if not os.path.exists(tool.get_locale_mo(locale, "messages")):
                tool.compile_message_catalogs(locale)
            #should maybe test for each domain separately?
            return cherrypy.session.get('locale')

        install_new_locale(locale)
        return cherrypy.session.get('locale')
    except identity.RequestRequiredException:
        # called from a scheduled job?
        return 'en'
Beispiel #5
0
 def join(self, show=None):
     if not show:
         turbogears.redirect('/show/list/')
     if identity.not_anonymous():
         identity.current.logout()
     show = Show.by_name(show)
     return dict(show=show)
Beispiel #6
0
def get_hubspace_user_locale():
    if identity.not_anonymous():
        if identity.current.user.homeplace:
            return hubspace_lang_code(identity.current.user.homeplace)
        else:
            return 'en' # user doesn't have a home location
    else:
        return hubspace_lang_code(get_location_from_base_url())
Beispiel #7
0
 def _to_python(self, value, state):
     if identity.not_anonymous():
         if value == identity.current.user.email_address:
             # the user isn't trying to change their email address
             # so the value is ok
             return value 
     if not register_model.email_is_unique(value):
         raise validators.Invalid(self.message('notUnique', state), value, state)
     return value
Beispiel #8
0
Datei: new.py Projekt: tyll/bodhi
class NewUpdateController(controllers.Controller):
    @identity.require(identity.not_anonymous())
    @expose(template="bodhi.templates.form")
    def index(self, *args, **kw):
        notice = config.get('newupdate_notice')
        if notice:
            flash(notice)
        return dict(form=update_form,
                    values=kw,
                    action=url("/save"),
                    title='New Update Form')

    @expose(format="json")
    def search(self, name):
        """
        Called automagically by the AutoCompleteWidget.
        If a package is specified (or 'pkg-'), return a list of available
        n-v-r's.  This method also auto-completes packages.
        """
        if not name: return dict()
        matches = []
        pkgname = name[:-1]
        if name[-1] == '-' and pkgname and pkgname in packages:
            name = pkgname
            matches.extend(self._fetch_candidate_builds(pkgname))
        else:
            for pkg in packages:
                if name == pkg:
                    matches.extend(self._fetch_candidate_builds(pkg))
                    break
                elif pkg.startswith(name):
                    matches.append(pkg)
        return dict(pkgs=matches)

    def _fetch_candidate_builds(self, pkg):
        """ Return all candidate builds for a given package """
        matches = {}
        koji = get_session()
        koji.multicall = True
        for tag in [r.candidate_tag for r in Release.select()]:
            koji.listTagged(tag, package=pkg)
        results = koji.multiCall()
        for result in results:
            for entries in result:
                for entry in entries:
                    matches[entry['nvr']] = entry['completion_time']
        return [
            build[0] for build in sorted(
                matches.items(), key=itemgetter(1), reverse=True)
        ]
Beispiel #9
0
    def add_user(self, show, username, human_name, email, telephone=None, 
               postal_address=None, age_check=False):
        if identity.not_anonymous():
            identity.current.logout()
        try:
            user = \
                self._root.user.create_user(username, human_name, email, 
                                            telephone, postal_address, 
                                            age_check, 
                                            redirect='/show/join/%s' % show)
            
            show = Show.by_name(show)
            user.show = show
        except IntegrityError:
            turbogears.flash(_("Your account could not be created.  Please contact a Fedora Ambassador for assistance."))
            turbogears.redirect('/show/fail/%s' % show)
            return dict()
        else:
            turbogears.flash(_('Your password has been emailed to you.  Please log in with it and change your password'))
            turbogears.redirect('/show/success/%s' % show)

        turbogears.redirect('/show/join/%s' % show)
Beispiel #10
0
    def filter(self, filters):
        """
        Returns a list of details for jobs filtered by the given criteria.

        The *filter* argument must be a an XML-RPC structure (dict) specifying
        filter criteria. The following keys are recognised:

            'tags'
                List of job tags.
            'daysComplete'
                Number of days elapsed since the jobs completion.
            'family'
                Job distro family, for example ``'RedHatEnterpriseLinuxServer5'``.
            'product'
                Job product name
            'owner'
                Job owner username
            'mine'
                Inclusion is equivalent to including own username in 'owner'
            'whiteboard'
                Job whiteboard
            'limit'
                Integer limit to number of jobs returned.
            'minid'
                Min JobID of the jobs to search
            'maxid'
                Maximum Job ID of the jobs to search

        Returns a two-element array. The first element is an array of JobIDs
        of the form ``'J:123'``, suitable to be passed to the
        :meth:`jobs.delete_jobs` method. The second element is a human-readable
        count of the number of Jobs matched. Does not return deleted jobs.
        """

        # if  min/max/both IDs have been specified, filter it right here
        minid = filters.get('minid', None)
        maxid = filters.get('maxid', None)
        jobs = session.query(Job)
        if minid:
            jobs = jobs.filter(Job.id >= minid)
        if maxid:
            jobs = jobs.filter(Job.id <= maxid)

        tags = filters.get('tags', None)
        complete_days = filters.get('daysComplete', None)
        family = filters.get('family', None)
        product = filters.get('product', None)
        owner = filters.get('owner', None)
        whiteboard = filters.get('whiteboard', None)
        mine = filters.get('mine', None)
        limit = filters.get('limit', None)

        if mine and not identity.not_anonymous():
            raise BX(_('You should be authenticated to use the --mine filter.'))

        if mine and identity.not_anonymous():
            if owner:
                if type(owner) is list:
                    owner.append(identity.current.user.user_name)
                else:
                    owner = [owner, identity.current.user.user_name]
            else:
                owner = identity.current.user.user_name

        jobs = jobs.order_by(Job.id.desc())
        if tags:
            jobs = Job.by_tag(tags, jobs)
        if complete_days:
            jobs = Job.complete_delta({'days':int(complete_days)}, jobs)
        if family:
            jobs = Job.has_family(family, jobs)
        if product:
            jobs = Job.by_product(product, jobs)
        if owner:
            jobs = Job.by_owner(owner, jobs)
        if whiteboard:
            jobs = Job.by_whiteboard(whiteboard, jobs)

        jobs = Job.sanitise_jobs(jobs)

        if limit:
            limit = int(limit)
            jobs = jobs.limit(limit)

        jobs = jobs.values(Job.id)
        
        return_value = ['J:%s' % j[0] for j in jobs]
        return return_value
Beispiel #11
0
class BuildRootOverrideController(Controller):
    @identity.require(identity.not_anonymous())
    @expose()
    def index(self):
        raise redirect('/override/list')

    @identity.require(identity.not_anonymous())
    @expose(template="bodhi.templates.overrides", allow_json=True)
    @validate(
        validators={
            'build': validators.UnicodeString(),
            'mine': validators.StringBool(),
            'release': validators.UnicodeString(),
            'show_expired': validators.StringBool()
        })
    @paginate('overrides',
              default_order='-date_submitted',
              limit=20,
              max_limit=1000)
    def list(self,
             build=None,
             tg_errors=None,
             mine=False,
             release=None,
             show_expired=False,
             **kw):
        query = []
        title = '%d Buildroot Overrides'
        if mine:
            query.append(
                BuildRootOverride.q.submitter == identity.current.user_name)
            title += ' submitted by %s' % identity.current.user_name
        if release:
            rel = Release.byName(release)
            query.append(BuildRootOverride.q.releaseID == rel.id)
            title += ' for %s' % rel.long_name
        if not show_expired:
            query.append(BuildRootOverride.q.date_expired == None)

        overrides = BuildRootOverride.select(AND(*query))

        if request_format() == 'json':
            overrides = [o.__json__() for o in overrides]
            num_items = len(overrides)
        else:
            num_items = overrides.count()
        return dict(overrides=overrides,
                    title=title % num_items,
                    num_items=num_items,
                    show_expired=show_expired,
                    mine=mine)

    @identity.require(identity.not_anonymous())
    @expose(template="bodhi.templates.form")
    def new(self, tg_errors=None, *args, **kw):
        if tg_errors:
            flash(str(tg_errors))
        expiration = datetime.utcnow() + \
            timedelta(days=config.get('buildroot_overrides.expire_after', 1))
        return dict(form=override_form,
                    values={'expiration': expiration},
                    action=url('/override/save'),
                    title='Buildroot Overrides')

    @identity.require(identity.not_anonymous())
    @expose(allow_json=True)
    def expire(self, build, *args, **kw):
        """ Expire a given override """
        override = BuildRootOverride.byBuild(build)
        if override.date_expired:
            flash('Override %s already expired!' % build)
            if request_format() == 'json': return dict()
            raise redirect('/override')
        override.date_expired = datetime.utcnow()
        try:
            override.untag()
        except Exception, e:
            log.error(str(e))
            flash(str(e))
            raise redirect('/override')
        log.info('Buildroot override %s manually expired by %s' %
                 (build, identity.current.user_name))
        flash('Buildroot override for %s successful untagged' % build)
        if request_format() == 'json': return dict()
        raise redirect('/override')
 def test_anonymous(self):
     """Test predicate for checking anonymous visitors."""
     assert self.met(not_anonymous())
Beispiel #13
0
class Root(controllers.RootController):

    #preventing the everytime polling and getting
    #func = Overlord("name") thing
    func_cache = {
        'fc_object': None,  #the fc = Overlord() thing,
        'glob': None,
        'minion_name': None,
        'module_name': None,
        'modules': None,
        'minions': None,
        'methods': None
    }
    #will be reused for widget validation

    @expose(template="funcweb.templates.minions")
    @identity.require(identity.not_anonymous())
    def minions(self, glob='*'):
        """ Return a list of our minions that match a given glob """
        #make the cache thing
        if self.func_cache['glob'] == glob:
            minions = self.func_cache['minions']
        else:
            #we dont have it it is for first time so lets pull it
            minions = Minions(glob).get_all_hosts()
            self.func_cache['glob'] = glob
            self.func_cache['minions'] = minions

        return dict(minions=minions)

    index = minions  # start with our minion view, for now

    @expose(template="funcweb.templates.minion")
    @identity.require(identity.not_anonymous())
    def minion(self, name="*", module=None, method=None):
        """ Display module or method details for a specific minion.

        If only the minion name is given, it will display a list of modules
        for that minion.  If a module is supplied, it will display a list of
        methods.
        """
        #if we have it in the cache
        if self.func_cache['minion_name'] == name:
            fc = self.func_cache['fc_object']
        else:
            fc = Overlord(name)
            self.func_cache['fc_object'] = fc
            self.func_cache['minion_name'] = name
            #reset the children :)
            self.func_cache['module_name'] = None
            self.func_cache['modules'] = None
            self.func_cache['methods'] = None

            #should also reset the other fields or not ?

        if not module:
            if not self.func_cache['modules']:
                modules = fc.system.list_modules()
                display_modules = []

                for module in modules.itervalues():
                    for mod in module:
                        #if it is not empty
                        if getattr(fc, mod).get_method_args()[name]:
                            display_modules.append(mod)

                #put it into the cache to make that slow thing faster
                self.func_cache['modules'] = display_modules

            else:
                #print "Im in the cache"
                #just list those who have get_method_args
                display_modules = self.func_cache['modules']

            modules = {}
            modules[name] = display_modules

            return dict(modules=modules)
        else:  # a module is specified
            if not method:  # return a list of methods for specified module
                #first check if we have it into the cache
                if self.func_cache[
                        'module_name'] == module and self.func_cache['methods']:
                    modules = self.func_cache['methods']
                    #print "Im in the cache"

                else:
                    self.func_cache['module_name'] = module
                    #display the list only that is registered with register_method template !
                    registered_methods = getattr(
                        fc, module).get_method_args()[name].keys()
                    modules = getattr(fc, module).list_methods()
                    for mods in modules.itervalues():
                        from copy import copy
                        cp_mods = copy(mods)
                        for m in cp_mods:
                            if not m in registered_methods:
                                mods.remove(m)

                    #store into cache if we get it again
                    self.func_cache['methods'] = modules
                #display em
                return dict(modules=modules,
                            module=module,
                            tg_template="funcweb.templates.module")
            else:
                return "Wrong place :)"

    @expose(template="funcweb.templates.method_args")
    @identity.require(identity.not_anonymous())
    def method_display(self, minion=None, module=None, method=None):
        """
        That method generates the input widget for givent method.
        """

        global global_form
        if self.func_cache['minion_name'] == minion:
            fc = self.func_cache['fc_object']
        else:
            fc = Overlord(minion)
            self.func_cache['fc_object'] = fc
            self.func_cache['minion_name'] = minion
            #reset the children :)
            self.func_cache['module_name'] = module
            self.func_cache['modules'] = None
            self.func_cache['methods'] = None

        #get the method args
        method_args = getattr(fc, module).get_method_args()

        if not method_args.values():
            #print "Not registered method here"
            return dict(minion_form=None,
                        minion=minion,
                        module=module,
                        method=method)

        minion_arguments = method_args[minion][method]['args']
        #the description of the method we are going to display
        if method_args[minion][method].has_key('description'):
            description = method_args[minion][method]['description']
        else:
            description = None
        if minion_arguments:
            wlist_object = WidgetListFactory(minion_arguments,
                                             minion=minion,
                                             module=module,
                                             method=method)
            wlist_object = wlist_object.get_widgetlist_object()
            #create the validation parts for the remote form
            wf = WidgetSchemaFactory(minion_arguments)
            schema_man = wf.get_ready_schema()

            #create the final form
            minion_form = RemoteFormAutomation(wlist_object, schema_man)
            global_form = minion_form.for_widget
            #print global_form
            #i use that when something goes wrong to check the problem better to stay here ;)
            #self.minion_form =RemoteFormFactory(wlist_object,schema_man).get_remote_form()

            del wlist_object
            del minion_arguments

            return dict(minion_form=minion_form,
                        minion=minion,
                        module=module,
                        method=method,
                        description=description)
        else:
            return dict(minion_form=None,
                        minion=minion,
                        module=module,
                        method=method,
                        description=description)

    @expose(template="funcweb.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):
        """
        The login form for not registered users
        """
        from cherrypy import request, response
        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.not_anonymous())
    def handle_minion_error(self, tg_errors=None):
        """
        The method checks the result from turbogears.validate
        decorator so if it has the tg_errors we know that the
        form validation is failed. That prevents the extra traffic
        to be sent to the minions!
        """
        if tg_errors:
            #print tg_errors
            return str(tg_errors)

    @expose(allow_json=True)
    @error_handler(handle_minion_error)
    @validate(form=validate_decorator_updater)
    @identity.require(identity.not_anonymous())
    def post_form(self, **kw):
        """
        Data processing part for methods that accept some inputs.
        Method recieves the method arguments for minion method then
        orders them into their original order and sends the xmlrpc
        request to the minion !
        """
        if kw.has_key('minion') and kw.has_key('module') and kw.has_key(
                'method'):
            #assign them because we need the rest so dont control everytime
            #and dont make lookup everytime ...
            #the del statements above are important dont remove them :)
            minion = kw['minion']
            del kw['minion']
            module = kw['module']
            del kw['module']
            method = kw['method']
            del kw['method']

            if self.func_cache['minion_name'] == minion:
                fc = self.func_cache['fc_object']
            else:
                fc = Overlord(minion)
                self.func_cache['fc_object'] = fc
                self.func_cache['minion_name'] = minion
                #reset the children :)
                self.func_cache['module_name'] = module
                self.func_cache['modules'] = None
                self.func_cache['methods'] = None

            #get again the method args to get their order :
            arguments = getattr(fc, module).get_method_args()
            #so we know the order just allocate and put them there
            cmd_args = [''] * (len(kw.keys()))

            for arg in kw.keys():
                #wow what a lookup :)
                index_of_arg = arguments[minion][method]['args'][arg]['order']
                cmd_args[index_of_arg] = kw[arg]

            #now execute the stuff
            result = getattr(getattr(fc, module), method)(*cmd_args)
            return str(result)

        else:
            return "Missing arguments sorry can not proceess the form"

    @expose(template="funcweb.templates.method_args")
    @identity.require(identity.not_anonymous())
    def execute_link(self, minion=None, module=None, method=None):
        """
        Method is fot those minion methods that dont accept any 
        arguments so they provide only some information,executed
        by pressing only the link !
        """
        if self.func_cache['minion_name'] == minion:
            fc = self.func_cache['fc_object']
        else:
            fc = Overlord(minion)
            self.func_cache['fc_object'] = fc
            self.func_cache['minion_name'] = minion
            #reset the children :)
            self.func_cache['module_name'] = module
            self.func_cache['modules'] = None
            self.func_cache['methods'] = None

        result = getattr(getattr(fc, module), method)()
        return str(result)

    @expose()
    def logout(self):
        """
        The logoout part 
        """
        identity.current.logout()
        raise redirect("/")
Beispiel #14
0
class Root(plugin.RootController):

    user = User()
    group = Group()
    fpca = FPCA()
    json = JsonRequest()
    config = Config()
    help = Help()

    openid = OpenID()

    def __init__(self):
        # TODO: Find a better place for this.
        os.environ['GNUPGHOME'] = config.get('gpghome')
        plugin.RootController.__init__(self)

    def getpluginident(self):
        return 'fas'

    @expose(template="fas.templates.welcome", allow_json=True)
    def index(self):
        if turbogears.identity.not_anonymous():
            if request_format() == 'json':
                # redirects don't work with JSON calls.  This is a bit of a
                # hack until we can figure out something better.
                return dict()
            turbogears.redirect('/home')
        return dict(now=time.ctime())

    @identity.require(identity.not_anonymous())
    @expose(template="fas.templates.home", allow_json=True)
    def home(self):
        user_name = turbogears.identity.current.user_name
        person = People.by_username(user_name)
        sshkeys = PeopleSSHKey.by_personid(person.id)
        (cla_done, undeprecated_cla) = undeprecated_cla_done(person)

        person = person.filter_private()
        return dict(person=person,
                    sshkeys=sshkeys,
                    memberships=person['memberships'],
                    cla=undeprecated_cla)

    @expose(template="fas.templates.about")
    def about(self):
        return dict()

    @expose(template="fas.templates.login", allow_json=True)
    def login(self, forward_url=None, *args, **kwargs):
        '''Page to become authenticated to the Account System.

        This shows a small login box to type in your username and password
        from the Fedora Account System.

        :kwarg forward_url: The url to send to once authentication succeeds
        '''
        login_dict = f_ctrlers.login(forward_url=forward_url, *args, **kwargs)

        if not identity.current.anonymous and identity.was_login_attempted() \
                and not identity.get_identity_errors():
            # Success that needs to be passed back via json
            return login_dict

        if identity.was_login_attempted() and request.fas_provided_username:
            if request.fas_identity_failure_reason == 'status_inactive':
                turbogears.flash(
                    _('Your old password has expired.  Please'
                      ' reset your password below.'))
                if request_format() != 'json':
                    redirect('/user/resetpass')
            if request.fas_identity_failure_reason == 'status_account_disabled':
                turbogears.flash(
                    _('Your account is currently disabled.  For'
                      ' more information, please contact %(admin_email)s' %
                      {'admin_email': config.get('accounts_email')}))
                if request_format() != 'json':
                    redirect('/login')

        return login_dict

    @expose(allow_json=True)
    def logout(self):
        return f_ctrlers.logout()

    @expose()
    def language(self, locale):
        if locale not in available_languages():
            turbogears.flash(
                _('The language \'%s\' is not available.') % locale)
            redirect(request.headers.get("Referer", "/"))
            return dict()
        #turbogears.i18n.set_session_locale(locale)
        cherrypy.response.simple_cookie['fas_locale'] = locale
        redirect(request.headers.get("Referer", "/"))
        return dict()
Beispiel #15
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
Beispiel #16
0
            openid_response.addExtension(sreg_resp)

        elif 'no' in kw:
            openid_response = openid_request.answer(False)
            remember_value = 'never'

        else:
            assert False, 'strange allow post %s' % kw

        if kw.get('remember', 'no') == 'yes':
            session[(openid_request.identity,
                     openid_request.trust_root)] = remember_value

        return self.respond(openid_response)

    @identity.require(identity.not_anonymous())
    @expose()
    def login(self, trust_root):
        """Force the user to login, then go back to checkidrequest"""
        openid_request = self.request_from_session(trust_root)
        if not openid_request:
            flash(
                _('Your last OpenID request could not be retrieved.  Try re-authenticating to the OpenID consumer.'
                  ))
            return redirect('/')

        return self.checkidrequest(openid_request)

    def request_from_session(self, trust_root):
        trust_root = unquote(trust_root)
        if 'last_request' in session:
Beispiel #17
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
Beispiel #18
0
class Root(plugin.RootController):

    user = User()
    group = Group()
    fpca = FPCA()
    json = JsonRequest()
    config = Config()
    help = Help()

    def __init__(self):
        # TODO: Find a better place for this.
        os.environ['GNUPGHOME'] = config.get('gpghome')
        plugin.RootController.__init__(self)

    def getpluginident(self):
        return 'fas'

    @expose(template="fas.templates.welcome", allow_json=True)
    def index(self):
        if turbogears.identity.not_anonymous():
            if request_format() == 'json':
                # redirects don't work with JSON calls.  This is a bit of a
                # hack until we can figure out something better.
                return dict()
            turbogears.redirect('/home')
        return dict(now=time.ctime())

    @identity.require(identity.not_anonymous())
    @expose(template="fas.templates.home", allow_json=True)
    def home(self):
        user_name = turbogears.identity.current.user_name
        person = People.by_username(user_name)
        (cla_done, undeprecated_cla) = undeprecated_cla_done(person)

        person = person.filter_private()
        return dict(person=person,
                    memberships=person['memberships'],
                    cla=undeprecated_cla)

    @expose(template="fas.templates.about")
    def about(self):
        return dict()

    @expose(template="fas.templates.login", allow_json=True)
    def login(self, forward_url=None, *args, **kwargs):
        '''Page to become authenticated to the Account System.

        This shows a small login box to type in your username and password
        from the Fedora Account System.

        :kwarg forward_url: The url to send to once authentication succeeds
        '''
        actual_login_dict = f_ctrlers.login(forward_url=forward_url,
                                            *args,
                                            **kwargs)

        try:
            login_dict = Bunch()
            login_dict['user'] = Bunch()
            for field in People.allow_fields['complete']:
                login_dict['user'][field] = None
            for field in People.allow_fields['self']:
                login_dict['user'][field] = getattr(actual_login_dict['user'],
                                                    field)
            # Strip out things that the user shouldn't see about their own
            # login
            login_dict['user']['internal_comments'] = None
            login_dict['user']['emailtoken'] = None
            login_dict['user']['security_answer'] = None
            login_dict['user']['alias_enabled'] = None
            login_dict['user']['passwordtoken'] = None

            # Add things that are needed by some other apps
            login_dict['user'].approved_memberships = list(
                actual_login_dict['user'].approved_memberships)
            login_dict['user'].memberships = list(
                actual_login_dict['user'].memberships)
            login_dict['user'].unapproved_memberships = list(
                actual_login_dict['user'].unapproved_memberships)
            login_dict['user'].group_roles = list(
                actual_login_dict['user'].group_roles)
            login_dict['user'].roles = list(actual_login_dict['user'].roles)
            login_dict['user'].groups = [
                g.name for g in actual_login_dict['user'].approved_memberships
            ]
            return login_dict
        except KeyError, e:
            # No problem, this usually means that we failed to login and
            # therefore we don't have a user field.
            login_dict = actual_login_dict

        if not identity.current.anonymous and identity.was_login_attempted() \
                and not identity.get_identity_errors():
            # Success that needs to be passed back via json
            return login_dict

        if identity.was_login_attempted() and request.fas_provided_username:
            if request.fas_identity_failure_reason == 'status_inactive':
                turbogears.flash(
                    _('Your old password has expired.  Please'
                      ' reset your password below.'))
                if request_format() != 'json':
                    redirect('/user/resetpass')
            if request.fas_identity_failure_reason == 'status_account_disabled':
                turbogears.flash(
                    _('Your account is currently disabled.  For'
                      ' more information, please contact %(admin_email)s' %
                      {'admin_email': config.get('accounts_email')}))
                if request_format() != 'json':
                    redirect('/login')

        return login_dict
Beispiel #19
0
        else:
            user = '******'
            username = identity.current.user_name

        for row in stmt.execute():
            person = list(row[1:])
            if not row['sponsored']:
                person[-1] = 0
            if row['privacy'] and user != 'admin' \
                    and username != row['username']:
                # filter private data
                person[2] = u''
            people.append(person)
        return dict(people=people)

    @identity.require(identity.not_anonymous())
    @validate(validators=GroupInvite())
    @error_handler(error) # pylint: disable-msg=E0602
    @expose(template='fas.templates.group.invite')
    def invite(self, groupname, language):
        username = turbogears.identity.current.user_name
        person = People.by_username(username)
        group = Groups.by_name(groupname)
        person = person.filter_private()

        subject = _('Invitation to join the Fedora Team!', language)
        text = _('''
%(fullname)s <%(user)s@%(hostname)s> has invited you to join the Fedora
Project!  We are a community of users and developers who produce a
complete operating system from entirely free and open source software
(FOSS).  %(fullname)s thinks that you have knowledge and skills
Beispiel #20
0
class Root(controllers.RootController):
    @identity.require(identity.not_anonymous())
    @expose(template="fpes.templates.index")
    def index(self):
        return dict(works=Work.query().all())

    @expose()
    def add(self, id, **kw):
        if not httpsession.has_key('cart'):
            httpsession['cart'] = []
        httpsession['cart'].append(int(id))
        print httpsession['cart']
        raise redirect("/cart")

    @expose()
    def remove(self, id, **kw):
        id = int(id)
        if httpsession.has_key('cart'):
            for w in httpsession['cart']:
                if w == id:
                    httpsession['cart'].remove(w)

        raise redirect("/cart")

    @expose()
    def remove_all(self):
        httpsession['cart'] = []
        raise redirect("/cart")

    @expose(template="fpes.templates.cart")
    def cart(self):
        works = []
        if httpsession.has_key('cart'):
            for w in httpsession['cart']:
                works.append(Work.query().filter(Work.c.id == w).first())
        return {'works': works}

    @expose()
    def purchase(self):
        if not httpsession.has_key("cart"):
            redirect("/cart")

        session.begin()
        print "in transaction"
        invoice = Invoice()
        print invoice.invoice_date
        line_items = []
        for item in httpsession['cart']:
            li = LineItem()
            li.work_id = item
            li.quantity = 1
            li.unit_price = 1
            line_items.append(li)
        invoice.line_items = line_items

        session.commit()
        session.flush()

        host = request.headers['Host']
        if request.headers.has_key('X-Forwarded-Host'):
            host = request.headers['X-Forwarded-Host']

        url = fpys_client.getPipelineUrl(
            invoice.caller_reference, "Image Download", str(invoice.total),
            "http://%s/capture/%d" % (host, invoice.id))
        raise redirect(url)

    @expose()
    def capture(self, invoice_id, **params):
        print params
        path = "/capture/%s?" % invoice_id
        # is amazon not url encoding the signature?
        sig = params['awsSignature'].replace(" ", "+")
        if not fpys_client.validate_pipeline_signature(sig, path, params):
            return ("invalid signature")

        if params['status'] in ['SA', 'SB', 'SC']:
            invoice = Invoice.query().filter(
                Invoice.c.id == int(invoice_id)).first()
            invoice.sender_token = params['tokenID']
            invoice.install_recipient_token(fpys_client)
            response = invoice.pay(fpys_client,
                                   config.get("default_caller_token"))

            import xml.etree.ElementTree as ET
            print response.transaction.status
            print response.transaction.transactionId

            for li in invoice.line_items:
                works_users_table.insert(
                    dict(work_id=li.work_id,
                         user_id=identity.current.user.user_id)).execute()
            redirect("/mine")
        else:
            return ("The payment didn't succeed")

    @expose(template="fpes.templates.mine")
    def mine(self):
        works = work_table.join(works_users_table).select(
            works_users_table.c.user_id ==
            identity.current.user.user_id).execute()
        return {'works': works}

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

        session.begin()
        password = base64.encodestring(str(random.getrandbits(64))).strip()
        username = uuid.uuid1().hex
        user = User(user_name=username,
                    display_name='Guest User',
                    password=identity.encrypt_password(password))
        session.commit()
        session.flush()

        identity.current_provider.validate_identity(username, password,
                                                    identity.current.visit_key)
        raise redirect(request.path)

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

    @expose()
    def dump_data(self, **args):
        print args
        return args
Beispiel #21
0
	def UserMenu(self, **kw):
		'''     Return a list of menu items available to the current user
		'''
		#log.debug('UserMenu')
		results = []
		#Display top menu based on permissions of user. 
		results.append(dict(link='/',name='Main Menu',sub_menu=[]))
		if identity.has_permission("reg_view"):    
			results.append(dict(link='/registration',name='Registration',sub_menu=[]))
		if identity.has_permission("bill_view"):
			results.append(dict(link='/billing',name='Billing',sub_menu=[]))
		Locations = model.InvLocation.select()
		LocationStoreGroups = {}
		LocationDispGroups = {}
		for location in Locations:
			name_store = '%s_store' % location.Name.lower().replace(' ','_')
			name_disp = '%s_disp' % location.Name.lower().replace(' ','_')
			# Create the store link
			if getattr(self,name_store,None) != None and identity.has_permission('%s_view' % name_store):
					for group in location.Groups:
							if LocationStoreGroups.has_key(group.Name):
									LocationStoreGroups[group.Name].append(dict(link='/%s' % name_store, name='%s Inventory' % location.Name,sub_menu=[]))
							else:
									LocationStoreGroups[group.Name] = [dict(link='/%s' % name_store, name='%s Inventory' % location.Name,sub_menu=[])]
					if len(location.Groups) == 0:
							if LocationStoreGroups.has_key('Other'):
									LocationStoreGroups['Other'].append(dict(link='/%s' % name_store, name='%s Inventory' % location.Name,sub_menu=[]))
							else:
									LocationStoreGroups['Other'] = [dict(link='/%s' % name_store, name='%s Inventory' % location.Name,sub_menu=[])]
			# Create the dispensing location
			if location.CanSell:
					if getattr(self,name_disp,None) != None and identity.has_permission('%s_view' % name_disp):
							for group in location.Groups:
									if LocationDispGroups.has_key(group.Name):
											LocationDispGroups[group.Name].append(dict(link='/%s' % name_disp, name='%s Dispensing' % location.Name,sub_menu=[]))
									else:
											LocationDispGroups[group.Name] = [dict(link='/%s' % name_disp, name='%s Dispensing' % location.Name,sub_menu=[])]
							if len(location.Groups) == 0:
									if LocationDispGroups.has_key('Other'):
											LocationDispGroups['Other'].append(dict(link='/%s' % name_disp, name='%s Dispensing' % location.Name,sub_menu=[]))
									else:
											LocationDispGroups['Other'] = [dict(link='/%s' % name_disp, name='%s Dispensing' % location.Name,sub_menu=[])]
		if len(LocationStoreGroups) > 0:
				SubMenu = []
				keys = LocationStoreGroups.keys()
				keys.sort()
				for key in keys:
						SubMenu.append(dict(link='',name=key, sub_menu=LocationStoreGroups[key]))
				results.append(dict(link='', name='Inventory', sub_menu=SubMenu))
		if len(LocationDispGroups) > 0:
				SubMenu = []
				keys = LocationDispGroups.keys()
				keys.sort()
				for key in keys:
						SubMenu.append(dict(link='',name=key, sub_menu=LocationDispGroups[key]))
				results.append(dict(link='', name='Dispensing', sub_menu=SubMenu))
		if identity.has_permission("admin_controllers_inventory"):
			results.append(dict(link='/inventory',name='Admin Inventory',sub_menu=[]))
		if identity.has_permission("admin_users"):
			results.append(dict(link='/user_manager',name='User admin',sub_menu=[]))
		if identity.has_permission("admin_controllers_configuration"):
			results.append(dict(link='/configuration',name='Configuration Admin',sub_menu=[]))
		if identity.not_anonymous():
				results.append(dict(link='/user_reports',name='User Reports',sub_menu=[]))
		return results
Beispiel #22
0
class Config(controllers.Controller):
    '''Controller that serves generic third party app configs.
    '''

    def __init__(self):
        pass

    @expose(template="fas.templates.error", allow_json=True)
    def error(self, tg_errors=None):
        '''Show a friendly error message'''
        # Only tg controller methods are served via the web so we have to have
        # methods even if they could be functions. (R0201)
        # pylint: disable-msg=R0201

        ### FIXME: This can be made simpler once we have a new python-fedora
        # with jsonify_validation_errors()
        if tg_errors:
            if request_format() == 'json':
                message = '\n'.join([u'%s: %s' % (param, msg) for param, msg in
                    tg_errors.items()])
                return dict(exc='Invalid', tg_flash=message, tg_template='json')
        if not tg_errors:
            # We should only reach this if the user hit the url manually.
            if request_format() == 'json':
                return dict()
            else:
                redirect('/')
        return dict(tg_errors=tg_errors)

    @identity.require(identity.not_anonymous())
    @validate(validators=ConfigList())
    @error_handler(error) # pylint: disable-msg=E0602
    @expose(allow_json=True)
    def list(self, username, application, pattern=u'*'):
        '''Retrieve configs for a user and application.

        Arguments:
        :username: owner of the configs we're searching for
        :application: program that the configs are for
        :pattern: Limit the configs to ones which match this pattern. '*' is a
            wildcard character

        Returns: dict that maps the name of the config attribute to the config
            value.
        '''
        # Only tg controller methods are served via the web so we have to have
        # methods even if they could be functions. (R0201)
        # pylint: disable-msg=R0201

        # Verify user is allowed to view this config
        target = People.by_username(username)
        if not can_edit_user(identity.current.user, target):
            flash(_('You cannot look at configs for %s') % username)
            if request_format() == 'json':
                return dict(exc='AuthorizationError')
            else:
                redirect('/')

        # This only works if pattern is unicode.  But it should be unicode
        # because of the validator.
        pattern = pattern.translate({ord(u'*'): ur'%'}).lower()

        # Retrieve the data and reformat it as a dict keyed on attribute
        # pylint: disable-msg=E1101
        cfgs = Configs.query.filter_by(application=application).filter(
                and_(Configs.attribute.like(pattern),
                    Configs.person_id==target.id))
        # pylint: enable-msg=E1101
        results = dict((cfg.attribute, cfg.value) for cfg in cfgs.all())

        return dict(username=username, application=application,
                pattern=pattern, configs=results)

    @identity.require(identity.not_anonymous())
    @validate(validators=ConfigSet())
    @error_handler(error) # pylint: disable-msg=E0602
    @expose(allow_json=True)
    def set(self, username, application, attribute, value=None):
        '''Retrieve configs for a user and application.

        Arguments:
        :username: owner of the configs we're searching for
        :application: program that the configs are for
        :attribute: name of the option we're setting
        :value: value to set in the db.  If ths is None, we won't set anything
        '''
        # Only tg controller methods are served via the web so we have to have
        # methods even if they could be functions. (R0201)
        # pylint: disable-msg=R0201

        # Verify user is allowed to set this config
        target = People.by_username(username)
        if not can_edit_user(identity.current.user, target):
            flash(_('You cannot edit configs for %s') % username)
            if request_format() == 'json':
                return dict(exc='AuthorizationError')
            else:
                redirect('/')

        # Retrieve the data and reformat it as a dict keyed on attribute
        try:
            # pylint: disable-msg=E1101
            config = Configs.query.filter_by(application=application,
                    attribute=attribute).filter(Configs.person_id==target.id).one()
            config.value = value
        except InvalidRequestError:
            # There was no Config, create a new one
            config = Configs(application=application, attribute=attribute,
                    value=value)
            # pylint: disable-msg=E1101
            config.person = People.query.filter_by(username=username).one()

        try:
            # ScopedSession really does have a flush() method
            # pylint: disable-msg=E1101
            session.flush()
        except DBAPIError, error:
            flash(_('Error saving the config to the database: %s' % (error)))
            return dict(exc='DBAPIError')

        # On success return an empty dict
        flash(_('Config value successfully updated'))
        return {}
 def index(self, **kwargs):
     if identity.not_anonymous():
         return self.dashboard.index()
     redirect("/login")