예제 #1
0
 def critique(self, id):
     load_user()
     self.load_matches(id)
     act = meta.Session.query(Activity).get(id)
     if c.user and self._can_comment(c.user.id, c.service_matches):
         rt = Rating()
         # raise Exception('inserting rating by user %s of user %s'%(c.user.id,act.user.id))
         rt.by_user = c.user
         # rt.by_user_id = c.user.id
         # c.user.ratings_by.append(rt)
         rt.of_user = act.user
         # rt.of_user_id = act.user.id
         act.user.ratings_of.append(rt)
         rt.rating = self.form_result.get("rating")
         rt.comment = self.form_result.get("comment")
         meta.Session.add(rt)
         meta.Session.commit()
         sess = facebook.check_session()
         if sess:
             facebook.notifications.send(
                 [act.user.fb_uid],
                 _(
                     u' נתן ציון לשירותך באתר <a href="http://www.greenie.co.il/">השליחים הירוקים</a> - <a href="http://www.greenie.co.il%s">%s</a>'
                 )
                 % (url.current(controller=act.activity_type, action="index", id=act.id), act),
             )
         redirect(url.current(action="index", id=id))
     else:
         raise Exception("permission denied to comment for this user here")
예제 #2
0
파일: login.py 프로젝트: cyclefusion/szarp
	def submit(self):
		"""
		Verify username and password
		"""
		# Both fields filled?
		form_username = str(request.params.get('username'))
		form_password = str(request.params.get('password'))
		m = hashlib.md5()
		m.update(form_password)
		passhash = m.hexdigest()
		# Get user data from database
		if app_globals.rpcservice.check_admin(form_username, passhash):
			# Mark admin as logged in
			session['user'] = form_username
			session['passhash'] = passhash
			session.save()
			return redirect(url(controller='syncuser', action='index'))

		if app_globals.rpcservice.check_user(form_username, passhash):
			# Mark user as logged in
			session['user'] = form_username
			session['passhash'] = passhash
			session.save()
			return redirect(url.current(controller='account', action='index'))
		return redirect(url.current(action = 'invalid'))
예제 #3
0
파일: login.py 프로젝트: xiaomailong/szarp
    def submit(self):
        """
		Verify username and password
		"""
        # Both fields filled?
        form_username = str(request.params.get('username'))
        form_password = str(request.params.get('password'))
        m = hashlib.md5()
        m.update(form_password)
        passhash = m.hexdigest()
        # Get user data from database
        if app_globals.rpcservice.check_admin(form_username, passhash):
            # Mark admin as logged in
            session['user'] = form_username
            session['passhash'] = passhash
            session.save()
            return redirect(url(controller='syncuser', action='index'))

        if app_globals.rpcservice.check_user(form_username, passhash):
            # Mark user as logged in
            session['user'] = form_username
            session['passhash'] = passhash
            session.save()
            return redirect(url.current(controller='account', action='index'))
        return redirect(url.current(action='invalid'))
예제 #4
0
 def delete(self, id=None):
     """ Delete an existing excavation record."""
     excavation = Session.query(Excavation).get(id)
     if excavation:
         Session.delete(excavation)
         Session.commit()
         flash_message(_("Excavation record deleted"), 'success')
         return redirect(url.current(action='index'))
     else:
         flash_message(_("This record did not exist"), 'warning')
         return redirect(url.current(action='index', id=None))
예제 #5
0
 def create(self, id, tags):
     if not hasattr(self, 'form_result'):
         redirect(url.current(action='add'))
     location = LocationTag.get(tags)
     subject = Subject.get(location, id)
     page = Page(self.form_result['page_title'],
                 self.form_result['page_content'])
     subject.pages.append(page)
     meta.Session.add(page)
     meta.Session.commit()
     redirect(url.current(action='index', page_id=page.id))
예제 #6
0
 def __before__(self):
     if self.requires_auth and not session.get('logged_in'):
         if session.get('after_login') is None:
             session.clear()
             if url.current() != url(controller='auth/login', action='index'):
                 session['after_login'] = url.current()
             else:
                 session['after_login'] = url('/')
             session.save()
             
         redirect(url(controller='auth/login', action='index'))
예제 #7
0
 def delete(self, id=None):
     """ Delete an existing address record."""
     address = Session.query(Address).get(id)
     if address:
         Session.delete(address)
         Session.commit()
         flash_message(_("Address record deleted"), 'success')
         return redirect(url.current(action='index'))
     else:
         flash_message(_("This record did not exist"), 'warning')
         return redirect(url.current(action='index', id=None))
예제 #8
0
 def award_medal(self, user):
     try:
         medal_type = request.GET['medal_type']
     except KeyError:
         abort(404)
     if medal_type not in Medal.available_medal_types():
         abort(404)
     if medal_type in [m.medal_type for m in user.medals]:
         redirect(url.current(action='medals')) # Medal already granted.
     m = Medal(user, medal_type)
     meta.Session.add(m)
     meta.Session.commit()
     redirect(url.current(action='medals'))
예제 #9
0
 def update(self, id=None):
     """ Update an existing address record."""
     address = Session.query(Address).get(id)
     if address:
         # update record attributes
         for key, value in self.form_result.items():
             setattr(address, key, value)
         Session.commit()
         flash_message(_("Address record updated"), 'success')
         return redirect(url.current(action='show', id=address.address_id))
     else:
         flash_message(_("This record did not exist"), 'warning')
         return redirect(url.current(action='index', id=None))
예제 #10
0
 def take_away_medal(self, user):
     try:
         medal_id = int(request.GET['medal_id'])
     except KeyError:
         abort(404)
     try:
         medal = meta.Session.query(Medal).filter_by(id=medal_id).one()
     except NoResultFound:
         redirect(url.current(action='medals')) # Medal has been already taken away.
     if medal.user is not user:
         abort(404)
     meta.Session.delete(medal)
     meta.Session.commit()
     redirect(url.current(action='medals'))
예제 #11
0
파일: root.py 프로젝트: lazaret/archeobases
    def post_login(self):
        """ Post login action.

        If the credentials are good the user is connected and redirect to the
        main index page . If they are wrong the user his resend to login.
        """
        credentials = request.environ.get('repoze.what.credentials', False)
        if credentials:
            userid = credentials['repoze.what.userid']
            flash_message(_("Successful login, %s!") % userid)
            redirect(url.current(action='index'))
        else:
            flash_message(_("Wrong credentials"), 'warning')
            redirect(url.current(action='login'))
예제 #12
0
 def update(self, id=None):
     """ Update an existing person record."""
     person = Session.query(Person).get(id)
     if person:
         # check first for a duplicate entry
         self._check_duplicate(self.form_result, person.person_id)
         # update record attributes
         for key, value in self.form_result.items():
             setattr(person, key, value)
         Session.commit()
         flash_message(_("Person record updated"), 'success')
         return redirect(url.current(action='show', id=person.person_id))
     else:
         flash_message(_("This record did not exist"), 'warning')
         return redirect(url.current(action='index', id=None))
예제 #13
0
파일: root.py 프로젝트: lazaret/archeobases
 def login(self):
     """ Render the login page."""
     credentials = request.environ.get('repoze.what.credentials', False)
     if credentials:
         redirect(url.current(action='index'))
     else:
         return render('login.mako')
예제 #14
0
파일: root.py 프로젝트: lazaret/archeobases
 def index(self):
     """ Render the main index page."""
     credentials = request.environ.get('repoze.what.credentials', False)
     if credentials:
         return render('index.mako')
     else:
         redirect(url.current(action='login'))
예제 #15
0
파일: helpers.py 프로젝트: yujiro/rhodecode
def gravatar_url(email_address, size=30):
    from pylons import url  ## doh, we need to re-import url to mock it later
    if(str2bool(config['app_conf'].get('use_gravatar')) and
       config['app_conf'].get('alternative_gravatar_url')):
        tmpl = config['app_conf'].get('alternative_gravatar_url', '')
        parsed_url = urlparse.urlparse(url.current(qualified=True))
        tmpl = tmpl.replace('{email}', email_address)\
                   .replace('{md5email}', hashlib.md5(email_address.lower()).hexdigest()) \
                   .replace('{netloc}', parsed_url.netloc)\
                   .replace('{scheme}', parsed_url.scheme)\
                   .replace('{size}', str(size))
        return tmpl

    if (not str2bool(config['app_conf'].get('use_gravatar')) or
        not email_address or email_address == '*****@*****.**'):
        f = lambda a, l: min(l, key=lambda x: abs(x - a))
        return url("/images/user%s.png" % f(size, [14, 16, 20, 24, 30]))

    ssl_enabled = 'https' == request.environ.get('wsgi.url_scheme')
    default = 'identicon'
    baseurl_nossl = "http://www.gravatar.com/avatar/"
    baseurl_ssl = "https://secure.gravatar.com/avatar/"
    baseurl = baseurl_ssl if ssl_enabled else baseurl_nossl

    if isinstance(email_address, unicode):
        #hashlib crashes on unicode items
        email_address = safe_str(email_address)
    # construct the url
    gravatar_url = baseurl + hashlib.md5(email_address.lower()).hexdigest() + "?"
    gravatar_url += urllib.urlencode({'d': default, 's': str(size)})

    return gravatar_url
예제 #16
0
        def create_comparison_link(target, replace_with=None, move=0):
            u"""Manipulates the list of Pokémon before creating a link.

            `target` is the FoundPokemon to be operated upon.  It can be either
            replaced with a new string or moved left/right.
            """

            new_found_pokemon = c.found_pokemon[:]

            # Do the swapping first
            if move:
                idx1 = new_found_pokemon.index(target)
                idx2 = (idx1 + move) % len(new_found_pokemon)
                new_found_pokemon[idx1], new_found_pokemon[idx2] = \
                    new_found_pokemon[idx2], new_found_pokemon[idx1]

            # Construct a new query
            query_pokemon = []
            for found_pokemon in new_found_pokemon:
                if found_pokemon is None:
                    # Empty slot
                    query_pokemon.append(u'')
                elif found_pokemon is target and replace_with != None:
                    # Substitute a new Pokémon
                    query_pokemon.append(replace_with)
                else:
                    # Keep what we have now
                    query_pokemon.append(found_pokemon.input)

            short_params = self._shorten_compare_pokemon(query_pokemon)
            return url.current(**short_params)
예제 #17
0
 def build_url(self, request, facet_values):
     '''
     Build an url from the *request* and the *facet_value*
     '''
     params = self.build_params(request, facet_values)
     url_base = url.current(qualified=True)
     return url_base + "?" + urllib.urlencode(params)
예제 #18
0
파일: auth.py 프로젝트: jeffjirsa/rhodecode
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        user = cls.rhodecode_user
        loc = "%s:%s" % (cls.__class__.__name__, func.__name__)

        #check IP
        ip_access_ok = True
        if not user.ip_allowed:
            from rhodecode.lib import helpers as h
            h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr))),
                    category='warning')
            ip_access_ok = False

        api_access_ok = False
        if self.api_access:
            log.debug('Checking API KEY access for %s' % cls)
            if user.api_key == request.GET.get('api_key'):
                api_access_ok = True
            else:
                log.debug("API KEY token not valid")

        log.debug('Checking if %s is authenticated @ %s' %
                  (user.username, loc))
        if (user.is_authenticated or api_access_ok) and ip_access_ok:
            reason = 'RegularAuth' if user.is_authenticated else 'APIAuth'
            log.info('user %s is authenticated and granted access to %s '
                     'using %s' % (user.username, loc, reason))
            return func(*fargs, **fkwargs)
        else:
            log.warn('user %s NOT authenticated on func: %s' % (user, loc))
            p = url.current()

            log.debug('redirecting to login page with %s' % p)
            return redirect(url('login_home', came_from=p))
예제 #19
0
        def create_comparison_link(target, replace_with=None, move=0):
            u"""Manipulates the list of Pokémon before creating a link.

            `target` is the FoundPokemon to be operated upon.  It can be either
            replaced with a new string or moved left/right.
            """

            new_found_pokemon = c.found_pokemon[:]

            # Do the swapping first
            if move:
                idx1 = new_found_pokemon.index(target)
                idx2 = (idx1 + move) % len(new_found_pokemon)
                new_found_pokemon[idx1], new_found_pokemon[idx2] = \
                    new_found_pokemon[idx2], new_found_pokemon[idx1]

            # Construct a new query
            query_pokemon = []
            for found_pokemon in new_found_pokemon:
                if found_pokemon is None:
                    # Empty slot
                    query_pokemon.append(u'')
                elif found_pokemon is target and replace_with != None:
                    # Substitute a new Pokémon
                    query_pokemon.append(replace_with)
                else:
                    # Keep what we have now
                    query_pokemon.append(found_pokemon.input)

            short_params = self._shorten_compare_pokemon(query_pokemon)
            return url.current(**short_params)
예제 #20
0
 def build_url(self, request, facet_values):
     '''
     Build an url from the *request* and the *facet_value*
     '''
     params = self.build_params(request, facet_values)
     url_base = url.current(qualified=True)
     return url_base + "?" + urllib.urlencode(params)
예제 #21
0
 def create(self):
     report = m.Report()
     
     for t,p in reports.tokenize_report(c.text):
         if t == reports.Map:
             # just ignore this for now, it will resolve itself up there ^
             pass
         elif t == reports.Hash:
             hash = m.Hash.by_name(p).first()
             if not hash:
                 hash = m.Hash()
                 hash.name = p
                 m.Session.add(hash)
             hash.reports.append(report)
     
     report.solarSystemID=c.solarSystem.solarSystemID
     
     report.title=c.title
     report.text=c.text
     report.priority=c.priority
     
     m.Session.add(report)
     m.Session.commit()
     
     return redirect(url.current())
예제 #22
0
def gravatar_url(email_address, size=30, ssl_enabled=True):
    from pylons import url  # doh, we need to re-import url to mock it later
    from rhodecode import CONFIG

    _def = '*****@*****.**'  # default gravatar
    use_gravatar = str2bool(CONFIG.get('use_gravatar'))
    alternative_gravatar_url = CONFIG.get('alternative_gravatar_url', '')
    email_address = email_address or _def
    if not use_gravatar or not email_address or email_address == _def:
        f = lambda a, l: min(l, key=lambda x: abs(x - a))
        return url("/images/user%s.png" % f(size, [14, 16, 20, 24, 30]))

    if use_gravatar and alternative_gravatar_url:
        tmpl = alternative_gravatar_url
        parsed_url = urlparse.urlparse(url.current(qualified=True))
        tmpl = tmpl.replace('{email}', email_address)\
                   .replace('{md5email}', hashlib.md5(email_address.lower()).hexdigest()) \
                   .replace('{netloc}', parsed_url.netloc)\
                   .replace('{scheme}', parsed_url.scheme)\
                   .replace('{size}', str(size))
        return tmpl

    default = 'identicon'
    baseurl_nossl = "http://www.gravatar.com/avatar/"
    baseurl_ssl = "https://secure.gravatar.com/avatar/"
    baseurl = baseurl_ssl if ssl_enabled else baseurl_nossl

    if isinstance(email_address, unicode):
        #hashlib crashes on unicode items
        email_address = safe_str(email_address)
    # construct the url
    gravatar_url = baseurl + hashlib.md5(email_address.lower()).hexdigest() + "?"
    gravatar_url += urllib.urlencode({'d': default, 's': str(size)})

    return gravatar_url
예제 #23
0
파일: home.py 프로젝트: jojoblaze/Woodstock
    def authenticate(self):
        form_username = str(request.params.get('username'))
        form_password = str(request.params.get('password'))


        # Get user data from database
        user = Session.query(User).filter(User.name==form_username).first()

        if user is None: # User does not exist
            return render('/login.mako')

        # Wrong password? (MD5 hashes used here)
        
        #if user.password != md5.md5(form_password).hexdigest():
        if user.password != form_password:
            return "Bad authentication." #render('login.mako')

        # Mark user as logged in
        session['user'] = form_username
        session.save()

        if user.name == "admin":
            return redirect(url(controller='admin/menu', action='index'))
        else:
            return redirect(url.current(action='index'))
        """    
예제 #24
0
    def build_url(self,
                  page=None,
                  size=None,
                  sort=None,
                  facets=tuple(),
                  unselect_facets=tuple(),
                  **kwargs):
        '''
        b/w compat
        '''
        query = MultiDict(request.params.items())
        query.update(kwargs)
        query[self.page_param] = page if page else 1
        query[self.size_param] = size if size else self.size
        query[self.sort_param] = sort if sort else self.selected_sort

        # sanitize the the query arguments
        query_items = ([(str(key), unicode(value).encode('utf-8'))
                        for (key, value) in query.items()])
        url_base = url.current(qualified=True)
        protocol = config.get('adhocracy.protocol', 'http').strip()
        if ', ' in url_base:
            # hard coded fix for enquetebeteiligung.de
            url_base = '%s://%s' % (protocol, url_base.split(', ')[1])
        else:
            url_base = '%s://%s' % (protocol, url_base.split('://')[1])
        return url_base + "?" + urllib.urlencode(query_items)
예제 #25
0
    def generate_header_link(self, column_number, column, label_text):
        """ This handles generation of link and then decides to call
        self.default_header_ordered_column_format 
        or 
        self.default_header_column_format 
        based on if current column is the one that is used for sorting or not
        """
        from pylons import url
        # this will handle possible URL generation
        request_copy = dict(self.request.copy().GET)
        self.order_column = request_copy.pop("order_col", None)
        self.order_dir = request_copy.pop("order_dir", None)

        if column == self.order_column and self.order_dir == "asc":
            new_order_dir = "dsc"
        else:
            new_order_dir = "asc"

        url_href = url.current(order_col=column,
                               order_dir=new_order_dir,
                               **request_copy)
        label_text = HTML.tag("a", href=url_href, c=label_text)
        # Is the current column the one we're ordering on?
        if column == self.order_column:
            return self.default_header_ordered_column_format(
                column_number, column, label_text)
        else:
            return self.default_header_column_format(column_number, column,
                                                     label_text)
예제 #26
0
 def generate_header_link(self, column_number, column, label_text):
     """ This handles generation of link and then decides to call
     self.default_header_ordered_column_format 
     or 
     self.default_header_column_format 
     based on if current column is the one that is used for sorting or not
     """ 
     from pylons import url
     # this will handle possible URL generation
     request_copy = dict(self.request.copy().GET) 
     self.order_column = request_copy.pop("order_col", None)
     self.order_dir = request_copy.pop("order_dir", None)
     
     if column == self.order_column and self.order_dir == "asc":
         new_order_dir = "dsc"
     else:
         new_order_dir = "asc"
     
     url_href = url.current(order_col=column, order_dir=new_order_dir,
                            **request_copy)
     label_text = HTML.tag("a", href=url_href, c=label_text)
     # Is the current column the one we're ordering on?
     if column == self.order_column:
         return self.default_header_ordered_column_format(column_number,
                                                          column,
                                                          label_text)
     else:
         return self.default_header_column_format(column_number, column,
                                                  label_text)
예제 #27
0
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        self.user = cls.rhodecode_user
        self.user_perms = self.user.permissions
        log.debug('checking %s permissions %s for %s %s',
                  self.__class__.__name__, self.required_perms, cls, self.user)

        if self.check_permissions():
            log.debug('Permission granted for %s %s' % (cls, self.user))
            return func(*fargs, **fkwargs)

        else:
            log.debug('Permission denied for %s %s' % (cls, self.user))
            anonymous = self.user.username == 'default'

            if anonymous:
                p = url.current()

                import rhodecode.lib.helpers as h
                h.flash(_('You need to be a signed in to '
                          'view this page'),
                        category='warning')
                return redirect(url('login_home', came_from=p))

            else:
                # redirect with forbidden ret code
                return abort(403)
예제 #28
0
    def _getIndexActionURL(self):
        """
        Uses the pylons config to build a url for the index action of this contoller.
        """

        indexURL = url.current(qualified=True, action='index')
        return indexURL
예제 #29
0
	def save(self, id=None):
		log.debug('save: id %s params %s', id, str(request.params))
		user = dict()
		if id is None:
			user['name'] = request.params['name']
		else:
			user['name'] = id

		for f in ('email', 'server', 'hwkey', 'comment'):
			user[f] = request.params[f]

		user['sync'] = self._get_selected_bases(request)

		if request.params['exp'] == 'date':
			user['expired'] = request.params['expired']
		else:
			user['expired'] = '-1'
		if id is None:
			try:
				password = app_globals.rpcservice.add_user(session['user'], session['passhash'], user)
				msg = _("Your SZARP Synchronization account has been created.\n\nYour login: %s\nYour password: %s\nVisist %s to change your password and view your settings.\n\nSZARP Synchronization Server\n") % (user['name'], password, url('home', qualified = True))
				send_email(user['email'], _("SZARP sync new account"), msg)
			except Exception, e:
				log.error(str(e))
				raise e
			return redirect(url.current(action='edit', id=user['name']))
예제 #30
0
def gravatar_url(email_address, size=30):
    from pylons import url  # doh, we need to re-import url to mock it later
    _def = '*****@*****.**'
    use_gravatar = str2bool(config['app_conf'].get('use_gravatar'))
    email_address = email_address or _def
    if (not use_gravatar or not email_address or email_address == _def):
        f = lambda a, l: min(l, key=lambda x: abs(x - a))
        return url("/images/user%s.png" % f(size, [14, 16, 20, 24, 30]))

    if use_gravatar and config['app_conf'].get('alternative_gravatar_url'):
        tmpl = config['app_conf'].get('alternative_gravatar_url', '')
        parsed_url = urlparse.urlparse(url.current(qualified=True))
        tmpl = tmpl.replace('{email}', email_address)\
                   .replace('{md5email}', hashlib.md5(email_address.lower()).hexdigest()) \
                   .replace('{netloc}', parsed_url.netloc)\
                   .replace('{scheme}', parsed_url.scheme)\
                   .replace('{size}', str(size))
        return tmpl

    ssl_enabled = 'https' == request.environ.get('wsgi.url_scheme')
    default = 'identicon'
    baseurl_nossl = "http://www.gravatar.com/avatar/"
    baseurl_ssl = "https://secure.gravatar.com/avatar/"
    baseurl = baseurl_ssl if ssl_enabled else baseurl_nossl

    if isinstance(email_address, unicode):
        #hashlib crashes on unicode items
        email_address = safe_str(email_address)
    # construct the url
    gravatar_url = baseurl + hashlib.md5(
        email_address.lower()).hexdigest() + "?"
    gravatar_url += urllib.urlencode({'d': default, 's': str(size)})

    return gravatar_url
예제 #31
0
파일: auth.py 프로젝트: lmamsen/rhodecode
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        self.user = cls.rhodecode_user
        self.user_perms = self.user.permissions
        log.debug('checking %s permissions %s for %s %s',
           self.__class__.__name__, self.required_perms, cls,
               self.user)

        if self.check_permissions():
            log.debug('Permission granted for %s %s', cls, self.user)
            return func(*fargs, **fkwargs)

        else:
            log.warning('Permission denied for %s %s', cls, self.user)


            anonymous = self.user.username == 'default'

            if anonymous:
                p = url.current()

                import rhodecode.lib.helpers as h
                h.flash(_('You need to be a signed in to '
                          'view this page'),
                        category='warning')
                return redirect(url('login_home', came_from=p))

            else:
                #redirect with forbidden ret code
                return abort(403)
예제 #32
0
파일: feed.py 프로젝트: bitonic/troppotardi
    def index(self):
        """ Feed with the last images """
        feed = Atom1Feed(
            title="troppotardi.com Image Feed",
            link=url.current(qualified=True),
            description="The last 10 entries from troppotardi.com",
            language="en",
            )

        images = Image.by_day(self.db,
                              startkey=day_to_str(datetime.utcnow()),
                              descending=True,
                              limit=10)
        
        for image in images:
            feed.add_item(title=image.author + ", " + day_to_str(image.day),
                          link=url(controller='images',
                                   action='show',
                                   day=day_to_str(image.day),
                                   qualified=True),
                          description="Image of the day by " + (image.author_url and ("<a href=\"" + image.author_url + "\">" + image.author + "</a>") or image.author),
                          date=image.day,
                          )

        response.content_type = 'application/atom+xml'

        return feed.writeString('utf-8')
예제 #33
0
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        user = cls.rhodecode_user

        api_access_ok = False
        if self.api_access:
            log.debug('Checking API KEY access for %s' % cls)
            if user.api_key == request.GET.get('api_key'):
                api_access_ok = True
            else:
                log.debug("API KEY token not valid")
        loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
        log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
        if user.is_authenticated or api_access_ok:
            log.info('user %s is authenticated and granted access to %s' % (
                       user.username, loc)
            )
            return func(*fargs, **fkwargs)
        else:
            log.warn('user %s NOT authenticated on func: %s' % (
                user, loc)
            )
            p = url.current()

            log.debug('redirecting to login page with %s' % p)
            return redirect(url('login_home', came_from=p))
예제 #34
0
    def document(self):
        resp = request.environ.get('pylons.original_response')
        req = request.environ.get('pylons.original_request')
        c.came_from = url.current()
        if resp is None:
            return render("/error.mako")

        c.reason = req.environ.get('ututi.access_denied_reason', None)
        if resp.status_int in [403, 404]:
            self.form_result = {}
            self._search()
            c.came_from = url('/')
            if resp.status_int == 403:
                return render("/access_denied.mako")

            elif resp.status_int == 404:
                h.flash(_("Document at %(url)s was not found, but maybe you are interested in something else?") % {
                        'url': req.url.encode('ascii', 'ignore')})

                # if user is logged in, show search form, otherwise - login form
                try:
                    if session['login']:
                        return render('/search/index.mako')
                except KeyError:
                    return render('/login.mako')

        return render("/error.mako")
예제 #35
0
파일: menu.py 프로젝트: jojoblaze/Woodstock
 def make_order(self):
     username = session['user']
     user = Session.query(User).filter(User.name==username).first()
     
     dish_id = request.params['dish_id']
     
     o = Session.query(Order).filter(Order.date==datetime.date.today()).first()
     
     if o == None:
         o = Order()
         o.date = datetime.date.today()
         Session.add(o)
         Session.commit()
     
     od = OrderDetail()
     od.order_id = o.id
     od.user_id = user.id
     od.dish_id = dish_id
     od.quantity = request.params['quantity']
     od.notes = request.params['notes']
     od.date = datetime.date.today()
     
     Session.add(od)
     Session.commit()
     
     redirect(url.current(action='get_today_order'))
예제 #36
0
파일: cmsuser.py 프로젝트: geonetix/eencms
    def submit(self, id=None):
        if id == 'new':
            usr = model.CMSUser()
        else:
            usr = model.find_cmsuser(int(id))

        errors = []
        rp = request.POST
        usr.fullname = rp.get('fullname')
        usr.username = rp.get('username')
        if rp.get('password1') and rp.get('password1') == rp.get('password2'):
            usr.password = security.hash_password(rp.get('password1'))

        if id == 'new' and not usr.password:
            errors.append({
                'field': 'password1',
                'message': "een wachtwoord is verplicht bij nieuwe gebruikers"}
            )
        if not usr.username:
            errors.append({'field': 'username',
                           'message': "dit veld moet worden ingevuld"})

        if errors:
            session['post'] = rp
            session['errors'] = errors
            session.save()
            redirect(url.current(action='edit'))

        if id == 'new':
            model.save(usr)
        model.commit()

        return redirect(url(controller='cmsuser', action='list'))
예제 #37
0
	def delete(self, **kwargs):
		if not kwargs.has_key('id'):
			return redirect(url.current(action='index'))
		c.id = kwargs.get('id')
		c.message = "Are you sure you want to remove user %s?" % c.id
		c.action = "delete_confirmed"
		c.no_action = "index"
		return render('/confirm.mako')
예제 #38
0
 def show(self, id=None):
     """ Display a person address record."""
     c.address = Session.query(Address).get(id)
     if c.address:
         return render('/addresses/show.mako')
     else:
         flash_message(_("This record did not exist"), 'warning')
         return redirect(url.current(action='index', id=None))
예제 #39
0
 def confirm_delete(self, id=None):
     """ Show an address record and ask to confirm deletion."""
     c.address = Session.query(Address).get(id)
     if c.address:
         return render('/addresses/confirm_delete.mako')
     else:
         flash_message(_("This record did not exist"), 'warning')
         return redirect(url.current(action='index', id=None))
예제 #40
0
파일: recipe.py 프로젝트: stefanv/aandete
    def save(self):
        self.form_result['owner'] = users.get_current_user()

        r = Recipe(**self.form_result)
        r.put()

        redirect(url.current(action='view', id=r.key().id(),
                                message='Recipe saved.'))
예제 #41
0
def redirect_to(*args, **kargs):
    if 'is_active' in dir(meta.Session):
        meta.Session.flush()
        # Close causes issues if we are running under a test harness
        # Not ideal to change behaviour under test but can't see a way around it
        if meta.Session.get_bind().url.database != 'zktest':
            meta.Session.close()

    return redirect(url.current(*args, **kargs))
예제 #42
0
def redirect_auth_denial(reason):
    if response.status_int == 401:
        message = 'You are not logged in.'
        message_type = 'warning'
    else:
        message = 'You do not have the permissions to access this page.'
        message_type = 'error'

    #h.flash(message, message_type)
    redirect(url('/login', came_from=url.current()))
예제 #43
0
파일: domains.py 프로젝트: haugvald/baruwa2
    def testdestination(self, destinationid):
        "Test mail destination server"
        server = self._get_server(destinationid)
        if not server:
            abort(404)

        taskid = request.GET.get('taskid', None)
        if not taskid:
            to_addr = 'postmaster@%s' % server.domains.name
            task = test_smtp_server.apply_async(args=[
                server.address, server.port, '<>', to_addr, server.id, 3
            ])
            taskid = task.task_id
            session['taskids'].append(taskid)
            session['testdest-count'] = 1
            session.save()
            redirect(url.current(taskid=taskid))
        else:
            result = AsyncResult(taskid)
            if result is None or taskid not in session['taskids']:
                flash(_('The connection test failed try again later'))
                redirect(url('domain-detail', domainid=server.domain_id))
            if result.ready():
                if ('smtp' in result.result and 'ping' in result.result
                        and result.result['smtp'] and result.result['ping']):
                    flash(
                        _('The server: %s is up and accepting mail from us' %
                          server.address))
                else:
                    if 'ping' in result.result['errors']:
                        errors = result.result['errors']['ping']
                    else:
                        errors = result.result['errors']['smtp']
                    flash(
                        _('The server: %s is not accepting mail from us: %s') %
                        (server.address, errors))
                redirect(url('domain-detail', domainid=server.domain_id))
            else:
                session['testdest-count'] += 1
                session.save()
                if (session['testdest-count'] >= 10
                        and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                    result.revoke()
                    del session['testdest-count']
                    session.save()
                    flash_alert('Failed to initialize backend,'
                                ' try again later')
                    redirect(url('domain-detail', domainid=server.domain_id))

        c.server = server
        c.domainid = server.domain_id
        c.taskid = taskid
        c.finished = False
        return render('/domains/testdestination.html')
예제 #44
0
    def test_alternative_gravatar(self):
        from rhodecode.lib.helpers import gravatar_url
        _md5 = lambda s: hashlib.md5(s).hexdigest()

        def fake_conf(**kwargs):
            from pylons import config
            config['app_conf'] = {}
            config['app_conf']['use_gravatar'] = True
            config['app_conf'].update(kwargs)
            return config

        class fake_url():
            @classmethod
            def current(cls, *args, **kwargs):
                return 'https://server.com'

        with mock.patch('pylons.url', fake_url):
            fake = fake_conf(
                alternative_gravatar_url='http://test.com/{email}')
            with mock.patch('pylons.config', fake):
                from pylons import url
                assert url.current() == 'https://server.com'
                grav = gravatar_url(email_address='*****@*****.**', size=24)
                assert grav == 'http://test.com/[email protected]'

            fake = fake_conf(
                alternative_gravatar_url='http://test.com/{email}')
            with mock.patch('pylons.config', fake):
                grav = gravatar_url(email_address='*****@*****.**', size=24)
                assert grav == 'http://test.com/[email protected]'

            fake = fake_conf(
                alternative_gravatar_url='http://test.com/{md5email}')
            with mock.patch('pylons.config', fake):
                em = '*****@*****.**'
                grav = gravatar_url(email_address=em, size=24)
                assert grav == 'http://test.com/%s' % (_md5(em))

            fake = fake_conf(
                alternative_gravatar_url='http://test.com/{md5email}/{size}')
            with mock.patch('pylons.config', fake):
                em = '*****@*****.**'
                grav = gravatar_url(email_address=em, size=24)
                assert grav == 'http://test.com/%s/%s' % (_md5(em), 24)

            fake = fake_conf(
                alternative_gravatar_url='{scheme}://{netloc}/{md5email}/{size}'
            )
            with mock.patch('pylons.config', fake):
                em = '*****@*****.**'
                grav = gravatar_url(email_address=em, size=24)
                assert grav == 'https://server.com/%s/%s' % (_md5(em), 24)
예제 #45
0
 def build_url(self, request, facet_values):
     '''
     Build an url from the *request* and the *facet_value*
     '''
     params = self.build_params(request, facet_values)
     url_base = url.current(qualified=True)
     protocol = config.get('adhocracy.protocol', 'http').strip()
     if ', ' in url_base:
         # hard coded fix for enquetebeteiligung.de
         url_base = '%s://%s' % (protocol, url_base.split(', ')[1])
     else:
         url_base = '%s://%s' % (protocol, url_base.split('://')[1])
     return url_base + "?" + urllib.urlencode(params)
예제 #46
0
    def test_alternative_gravatar(self):
        from kallithea.lib.helpers import gravatar_url
        _md5 = lambda s: hashlib.md5(s).hexdigest()

        #mock pylons.url
        class fake_url(object):
            @classmethod
            def current(cls, *args, **kwargs):
                return 'https://server.com'

        #mock pylons.tmpl_context
        def fake_tmpl_context(_url):
            _c = AttributeDict()
            _c.visual = AttributeDict()
            _c.visual.use_gravatar = True
            _c.visual.gravatar_url = _url

            return _c


        with mock.patch('pylons.url', fake_url):
            fake = fake_tmpl_context(_url='http://test.com/{email}')
            with mock.patch('pylons.tmpl_context', fake):
                    from pylons import url
                    assert url.current() == 'https://server.com'
                    grav = gravatar_url(email_address='*****@*****.**', size=24)
                    assert grav == 'http://test.com/[email protected]'

            fake = fake_tmpl_context(_url='http://test.com/{email}')
            with mock.patch('pylons.tmpl_context', fake):
                grav = gravatar_url(email_address='*****@*****.**', size=24)
                assert grav == 'http://test.com/[email protected]'

            fake = fake_tmpl_context(_url='http://test.com/{md5email}')
            with mock.patch('pylons.tmpl_context', fake):
                em = '*****@*****.**'
                grav = gravatar_url(email_address=em, size=24)
                assert grav == 'http://test.com/%s' % (_md5(em))

            fake = fake_tmpl_context(_url='http://test.com/{md5email}/{size}')
            with mock.patch('pylons.tmpl_context', fake):
                em = '*****@*****.**'
                grav = gravatar_url(email_address=em, size=24)
                assert grav == 'http://test.com/%s/%s' % (_md5(em), 24)

            fake = fake_tmpl_context(_url='{scheme}://{netloc}/{md5email}/{size}')
            with mock.patch('pylons.tmpl_context', fake):
                em = '*****@*****.**'
                grav = gravatar_url(email_address=em, size=24)
                assert grav == 'https://server.com/%s/%s' % (_md5(em), 24)
예제 #47
0
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        user = cls.authuser
        loc = "%s:%s" % (cls.__class__.__name__, func.__name__)

        # check if our IP is allowed
        ip_access_valid = True
        if not user.ip_allowed:
            from kallithea.lib import helpers as h
            h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr))),
                    category='warning')
            ip_access_valid = False

        # check if we used an APIKEY and it's a valid one
        # defined whitelist of controllers which API access will be enabled
        _api_key = request.GET.get('api_key', '')
        api_access_valid = allowed_api_access(loc, api_key=_api_key)

        # explicit controller is enabled or API is in our whitelist
        if self.api_access or api_access_valid:
            log.debug('Checking API KEY access for %s' % cls)
            if _api_key and _api_key in user.api_keys:
                api_access_valid = True
                log.debug('API KEY ****%s is VALID' % _api_key[-4:])
            else:
                api_access_valid = False
                if not _api_key:
                    log.debug("API KEY *NOT* present in request")
                else:
                    log.warning("API KEY ****%s *NOT* valid" % _api_key[-4:])

        log.debug('Checking if %s is authenticated @ %s' %
                  (user.username, loc))
        reason = 'RegularAuth' if user.is_authenticated else 'APIAuth'

        if ip_access_valid and (user.is_authenticated or api_access_valid):
            log.info(
                'user %s authenticating with:%s IS authenticated on func %s ' %
                (user, reason, loc))
            return func(*fargs, **fkwargs)
        else:
            log.warning(
                'user %s authenticating with:%s NOT authenticated on func: %s: '
                'IP_ACCESS:%s API_ACCESS:%s' %
                (user, reason, loc, ip_access_valid, api_access_valid))
            p = url.current()

            log.debug('redirecting to login page with %s' % p)
            return redirect(url('login_home', came_from=p))
예제 #48
0
    def _validate_came_from(self, came_from):
        if not came_from:
            return came_from

        parsed = urlparse.urlparse(came_from)
        server_parsed = urlparse.urlparse(url.current())
        allowed_schemes = ['http', 'https']
        if parsed.scheme and parsed.scheme not in allowed_schemes:
            log.error('Suspicious URL scheme detected %s for url %s' %
                      (parsed.scheme, parsed))
            came_from = url('home')
        elif server_parsed.netloc != parsed.netloc:
            log.error('Suspicious NETLOC detected %s for url %s server url '
                      'is: %s' % (parsed.netloc, parsed, server_parsed))
            came_from = url('home')
        return came_from
예제 #49
0
 def index(self, id=None):
     if id:
         record = meta.Session.query(model.Files).filter_by(id=id).first()
     else:
         record = model.Files()
     assert record is not None, repr(id)
     c.fs = Files.bind(record, data=request.POST or None)
     if request.POST and c.fs.validate():
         c.fs.sync()
         if id:
             meta.Session.merge(record)
         else:
             meta.Session.add(record)
         meta.Session.commit()
         redirect(url.current(id=record.id))
     return render('/form.mako')
예제 #50
0
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        self.user = cls.rhodecode_user

        log.debug('Checking if user is not anonymous @%s' % cls)

        anonymous = self.user.username == 'default'

        if anonymous:
            p = url.current()

            import rhodecode.lib.helpers as h
            h.flash(_('You need to be a registered user to '
                      'perform this action'),
                    category='warning')
            return redirect(url('login_home', came_from=p))
        else:
            return func(*fargs, **fkwargs)
예제 #51
0
    def build_url(self,
                  page=None,
                  size=None,
                  sort=None,
                  facets=tuple(),
                  unselect_facets=tuple(),
                  **kwargs):
        '''
        b/w compat
        '''
        query = MultiDict(request.params.items())
        query.update(kwargs)
        query["%s_page" % self.name] = page if page else 1
        query["%s_size" % self.name] = size if size else self.size
        query["%s_sort" % self.name] = sort if sort else self.selected_sort

        # sanitize the the query arguments
        query_items = ([(str(key), unicode(value).encode('utf-8'))
                        for (key, value) in query.items()])
        url_base = url.current(qualified=True)
        return url_base + "?" + urllib.urlencode(query_items)
예제 #52
0
    def submit(self, id=None):
        if id == 'new':
            usr = model.CMSUser()
        else:
            usr = model.find_cmsuser(int(id))

        errors = []
        rp = request.POST
        usr.fullname = rp.get('fullname')
        usr.username = rp.get('username')
        if rp.get('password1') and rp.get('password1') == rp.get('password2'):
            usr.password = security.hash_password(rp.get('password1'))

        if id == 'new' and not usr.password:
            errors.append({
                'field':
                'password1',
                'message':
                "een wachtwoord is verplicht bij nieuwe gebruikers"
            })
        if not usr.username:
            errors.append({
                'field': 'username',
                'message': "dit veld moet worden ingevuld"
            })

        if errors:
            session['post'] = rp
            session['errors'] = errors
            session.save()
            redirect(url.current(action='edit'))

        if id == 'new':
            model.save(usr)
        model.commit()

        return redirect(url(controller='cmsuser', action='list'))
예제 #53
0
    def stat_calculator(self):
        """Calculates, well, stats."""
        # XXX this form handling is all pretty bad.  consider ripping it out
        # and really thinking about how this ought to work.
        # possible TODO:
        # - more better error checking
        # - track effort gained on the fly (as well as exp for auto level up?)
        # - track evolutions?
        # - graphs of potential stats?
        #   - given a pokemon and its genes and effort, graph all stats by level
        #   - given a pokemon and its gene results, graph approximate stats by level...?
        #   - given a pokemon, graph its min and max possible calc'd stats...
        # - this logic is pretty hairy; use a state object?

        # Add the stat-based fields
        stat_query = (db.pokedex_session.query(
            tables.Stat).filter(tables.Stat.is_battle_only == False))

        c.stats = (stat_query.order_by(tables.Stat.id).all())

        hidden_power_stats = (stat_query.order_by(
            tables.Stat.game_index).all())

        # Make sure there are the same number of level, stat, and effort
        # fields.  Add an extra one (for more data), as long as we're not about
        # to shorten
        num_dupes = c.num_data_points = len(request.GET.getall('level'))
        if not request.GET.get('shorten', False):
            num_dupes += 1

        class F(StatCalculatorForm):
            level = DuplicateField(
                fields.IntegerField(
                    u'Level',
                    default=100,
                    validators=[wtforms.validators.NumberRange(1, 100)]),
                min_entries=num_dupes,
            )
            stat = DuplicateField(
                StatField(
                    c.stats,
                    fields.IntegerField(default=0,
                                        validators=[
                                            wtforms.validators.NumberRange(
                                                min=0, max=700)
                                        ])),
                min_entries=num_dupes,
            )
            effort = DuplicateField(
                StatField(
                    c.stats,
                    fields.IntegerField(default=0,
                                        validators=[
                                            wtforms.validators.NumberRange(
                                                min=0, max=255)
                                        ])),
                min_entries=num_dupes,
            )

        ### Parse form and so forth
        c.form = F(request.GET)

        c.results = None  # XXX shim
        if not request.GET or not c.form.validate():
            return render('/pokedex/gadgets/stat_calculator.mako')

        if not c.num_data_points:
            # Zero?  How did you manage that?
            # XXX this doesn't actually appear in the page  :D
            c.form.level.errors.append(u"Please enter at least one level")
            return render('/pokedex/gadgets/stat_calculator.mako')

        # Possible shorten and redirect
        if c.form.needs_shortening:
            # This is stupid, but update_params doesn't understand unicode
            kwargs = c.form.short_formdata
            for key, vals in kwargs.iteritems():
                kwargs[key] = [unicode(val).encode('utf8') for val in vals]

            redirect(h.update_params(url.current(), **kwargs))

        def filter_genes(genes, f):
            """Teeny helper function to only keep possible genes that fit the
            given lambda.
            """
            genes &= set(gene for gene in genes if f(gene))

        # Okay, do some work!
        # Dumb method for now -- XXX change this to do a binary search.
        # Run through every possible value for each stat, see if it matches
        # input, and give the green light if so.
        pokemon = c.pokemon = c.form.pokemon.data
        nature = c.form.nature.data
        if nature and nature.is_neutral:
            # Neutral nature is equivalent to none at all
            nature = None
        # Start with lists of possibly valid genes and cut down from there
        c.valid_range = defaultdict(dict)  # stat => level => (min, max)
        valid_genes = {}
        # Stuff for finding the next useful level
        level_indices = sorted(range(c.num_data_points),
                               key=lambda i: c.form.level[i].data)
        max_level_index = level_indices[-1]
        max_given_level = c.form.level[max_level_index].data
        c.next_useful_level = 100

        for stat in c.stats:
            ### Bunch of setup, per stat
            # XXX let me stop typing this, christ
            if stat.identifier == u'hp':
                func = pokedex.formulae.calculated_hp
            else:
                func = pokedex.formulae.calculated_stat

            base_stat = pokemon.base_stat(stat, 0)
            if not base_stat:
                valid_genes[stat] = set(range(32))
                continue

            nature_mod = 1.0
            if not nature:
                pass
            elif nature.increased_stat == stat:
                nature_mod = 1.1
            elif nature.decreased_stat == stat:
                nature_mod = 0.9

            meta_calculate_stat = functools.partial(func,
                                                    base_stat=base_stat,
                                                    nature=nature_mod)

            # Start out with everything being considered valid
            valid_genes[stat] = set(range(32))

            for i in range(c.num_data_points):
                stat_in = c.form.stat[i][stat].data
                effort_in = c.form.effort[i][stat].data
                level = c.form.level[i].data

                calculate_stat = functools.partial(meta_calculate_stat,
                                                   effort=effort_in,
                                                   level=level)

                c.valid_range[stat][level] = min_stat, max_stat = \
                    calculate_stat(iv=0), calculate_stat(iv=31)

                ### Actual work!
                # Quick simple check: if the input is totally outside the valid
                # range, no need to calculate anything
                if not min_stat <= stat_in <= max_stat:
                    valid_genes[stat] = set()
                if not valid_genes[stat]:
                    continue

                # Run through and maybe invalidate each gene
                filter_genes(valid_genes[stat],
                             lambda gene: calculate_stat(iv=gene) == stat_in)

            # Find the next "useful" level.  This is the lowest level at which
            # at least two possible genes give different stats, given how much
            # effort the Pokémon has now.
            # TODO should this show the *highest* level necessary to get exact?
            if valid_genes[stat]:
                min_gene = min(valid_genes[stat])
                max_gene = max(valid_genes[stat])
                max_effort = c.form.effort[max_level_index][stat].data
                while level < c.next_useful_level and \
                    meta_calculate_stat(level=level, effort=max_effort, iv=min_gene) == \
                    meta_calculate_stat(level=level, effort=max_effort, iv=max_gene):

                    level += 1
                c.next_useful_level = level

        c.form.level[-1].data = c.next_useful_level

        # Hidden Power type
        if c.form.hp_type.data:
            # Shift the type id to make Fighting (id=2) #0
            hp_type = c.form.hp_type.data.id - 2

            # See below for how this is calculated.
            # We know x * 15 // 63 == hp_type, and want a range for x.
            # hp_type * 63 / 15 is the LOWER bound, though you need to ceil()
            # it to find the lower integral bound.
            # The same thing for (hp_type + 1) is the lower bound for the next
            # type, which is one more than our upper bound.  Cool.
            min_x = int(math.ceil(hp_type * 63 / 15))
            max_x = int(math.ceil((hp_type + 1) * 63 / 15) - 1)

            # Now we need to find how many bits from the left will stay the
            # same throughout this x-range, so we know that those bits must
            # belong to the corresponding stats.  Easy if you note that, if
            # min_x and max_x have the same leftmost n bits, so will every
            # integer between them.
            first_good_bit = None
            for n in range(6):
                # Convert "3" to 0b111000
                # 3 -> 0b1000 -> 0b111 -> 0b111000
                mask = 63 ^ ((1 << n) - 1)
                if min_x & mask == max_x & mask:
                    first_good_bit = n
                    break
            if first_good_bit is not None:
                # OK, cool!  Now we know some number of stats are either
                # definitely odd or definitely even.
                for stat_id in range(first_good_bit, 6):
                    bit = (min_x >> stat_id) & 1
                    stat = hidden_power_stats[stat_id]
                    filter_genes(valid_genes[stat],
                                 lambda gene: gene & 1 == bit)

        # Characteristic; needs to be last since it imposes a maximum
        hint = c.form.hint.data
        if hint:
            # Knock out everything that doesn't match its mod-5
            filter_genes(valid_genes[hint.stat],
                         lambda gene: gene % 5 == hint.gene_mod_5)

            # Also, the characteristic is only shown for the highest gene.  So,
            # no other stat can be higher than the new maximum for the hinted
            # stat.  (Need the extra -1 in case there are actually no valid
            # genes left; max() dies with an empty sequence.)
            max_gene = max(itertools.chain(valid_genes[hint.stat], (-1, )))
            for genes in valid_genes.values():
                filter_genes(genes, lambda gene: gene <= max_gene)

        # Possibly calculate Hidden Power's type and power, if the results are
        # exact
        c.exact = all(len(genes) == 1 for genes in valid_genes.values())
        if c.exact:
            # HP uses bit 0 of each gene for the type, and bit 1 for the power.
            # These bits are used to make new six-bit numbers, where HP goes to
            # bit 0, Attack to bit 1, etc.
            type_det = 0
            power_det = 0
            for i, stat in enumerate(hidden_power_stats):
                stat_value, = valid_genes[stat]
                type_det += (stat_value & 0x01) << i
                power_det += (stat_value & 0x02) >> 1 << i

            # Our types are also in the correct order, except that we start
            # from 1 rather than 0, and HP skips Normal
            c.hidden_power_type = db.pokedex_session.query(tables.Type) \
                .get(type_det * 15 // 63 + 2)
            c.hidden_power_power = power_det * 40 // 63 + 30

            # Used for a link
            c.hidden_power = db.pokedex_session.query(tables.Move) \
                .filter_by(identifier='hidden-power').one()

        # Turn those results into something more readable.
        # Template still needs valid_genes for drawing the graph
        c.results = {}
        c.valid_genes = valid_genes
        for stat in c.stats:
            # 1, 2, 3, 5 => "1-3, 5"
            # Find consecutive ranges of numbers and turn them into strings.
            # nb: The final dummy iteration with n = None is to more easily add
            # the last range to the parts list
            left_endpoint = None
            parts = []
            elements = sorted(valid_genes[stat])

            for last_n, n in zip([None] + elements, elements + [None]):
                if (n is None and left_endpoint is not None) or \
                    (last_n is not None and last_n + 1 < n):

                    # End of a subrange; break off what we have
                    if left_endpoint == last_n:
                        parts.append(u"{0}".format(last_n))
                    else:
                        parts.append(u"{0}–{1}".format(left_endpoint, last_n))

                if left_endpoint is None or last_n + 1 < n:
                    # Starting a new subrange; remember the new left end
                    left_endpoint = n

            c.results[stat] = u', '.join(parts)

        c.stat_graph_chunk_color = stat_graph_chunk_color

        c.prompt_for_more = (not c.exact
                             and c.next_useful_level > max_given_level)

        return render('/pokedex/gadgets/stat_calculator.mako')
예제 #54
0
    def compare_pokemon(self):
        u"""Pokémon comparison.  Takes up to eight Pokémon and shows a page
        that lists their stats, moves, etc. side-by-side.
        """
        # Note that this gadget doesn't use wtforms at all, since there're only
        # two fields and the major one is handled very specially.

        c.did_anything = False

        # Form controls use version group
        # We join with VGPMM to filter out version groups which we lack move
        # data for. *coughxycough*
        c.version_groups = db.pokedex_session.query(tables.VersionGroup) \
            .join(tables.VersionGroupPokemonMoveMethod) \
            .order_by(tables.VersionGroup.order.asc()) \
            .options(eagerload('versions')) \
            .all()
        # Grab the version to use for moves, defaulting to the most current
        try:
            c.version_group = db.pokedex_session.query(tables.VersionGroup) \
                .get(request.params['version_group'])
        except (KeyError, NoResultFound):
            c.version_group = c.version_groups[-1]

        # Some manual URL shortening, if necessary...
        if request.params.get('shorten', False):
            short_params = self._shorten_compare_pokemon(
                request.params.getall('pokemon'))
            redirect(url.current(**short_params))

        FoundPokemon = namedtuple('FoundPokemon',
                                  ['pokemon', 'form', 'suggestions', 'input'])

        # The Pokémon themselves go into c.pokemon.  This list should always
        # have eight FoundPokemon elements
        c.found_pokemon = [None] * self.NUM_COMPARED_POKEMON

        # Run through the list, ensuring at least 8 Pokémon are entered
        pokemon_input = request.params.getall('pokemon') \
            + [u''] * self.NUM_COMPARED_POKEMON
        for i in range(self.NUM_COMPARED_POKEMON):
            raw_pokemon = pokemon_input[i].strip()
            if not raw_pokemon:
                # Use a junk placeholder tuple
                c.found_pokemon[i] = FoundPokemon(pokemon=None,
                                                  form=None,
                                                  suggestions=None,
                                                  input=u'')
                continue

            results = db.pokedex_lookup.lookup(
                raw_pokemon, valid_types=['pokemon_species', 'pokemon_form'])

            # Two separate things to do here.
            # 1: Use the first result as the actual Pokémon
            pokemon = None
            form = None
            if results:
                result = results[0].object
                c.did_anything = True

                # 1.5: Deal with form matches
                if isinstance(result, tables.PokemonForm):
                    pokemon = result.pokemon
                    form = result
                else:
                    pokemon = result.default_pokemon
                    form = pokemon.default_form

            # 2: Use the other results as suggestions.  Doing this informs the
            # template that this was a multi-match
            suggestions = None
            if len(results) == 1 and results[0].exact:
                # Don't do anything for exact single matches
                pass
            else:
                # OK, extract options.  But no more than, say, three.
                # Remember both the language and the Pokémon, in the case of
                # foreign matches
                suggestions = [(_.name, _.iso3166) for _ in results[1:4]]

            # Construct a tuple and slap that bitch in there
            c.found_pokemon[i] = FoundPokemon(pokemon, form, suggestions,
                                              raw_pokemon)

        # There are a lot of links to similar incarnations of this page.
        # Provide a closure for constructing the links easily
        def create_comparison_link(target, replace_with=None, move=0):
            u"""Manipulates the list of Pokémon before creating a link.

            `target` is the FoundPokemon to be operated upon.  It can be either
            replaced with a new string or moved left/right.
            """

            new_found_pokemon = c.found_pokemon[:]

            # Do the swapping first
            if move:
                idx1 = new_found_pokemon.index(target)
                idx2 = (idx1 + move) % len(new_found_pokemon)
                new_found_pokemon[idx1], new_found_pokemon[idx2] = \
                    new_found_pokemon[idx2], new_found_pokemon[idx1]

            # Construct a new query
            query_pokemon = []
            for found_pokemon in new_found_pokemon:
                if found_pokemon is None:
                    # Empty slot
                    query_pokemon.append(u'')
                elif found_pokemon is target and replace_with != None:
                    # Substitute a new Pokémon
                    query_pokemon.append(replace_with)
                else:
                    # Keep what we have now
                    query_pokemon.append(found_pokemon.input)

            short_params = self._shorten_compare_pokemon(query_pokemon)
            return url.current(**short_params)

        c.create_comparison_link = create_comparison_link

        # Setup only done if the page is actually showing
        if c.did_anything:
            c.stats = db.pokedex_session.query(tables.Stat) \
                .filter(~ tables.Stat.is_battle_only) \
                .all()

            # Relative numbers -- breeding and stats
            # Construct a nested dictionary of label => pokemon => (value, pct)
            # `pct` is percentage from the minimum to maximum value
            c.relatives = dict()
            # Use the label from the page as the key, because why not
            relative_things = [
                (u'Base EXP', lambda pokemon: pokemon.base_experience),
                (u'Base happiness',
                 lambda pokemon: pokemon.species.base_happiness),
                (u'Capture rate',
                 lambda pokemon: pokemon.species.capture_rate),
            ]

            def relative_stat_factory(local_stat):
                return lambda pokemon: pokemon.base_stat(local_stat, 0)

            for stat in c.stats:
                relative_things.append(
                    (stat.name, relative_stat_factory(stat)))

            relative_things.append((u'Base stat total', lambda pokemon: sum(
                pokemon.base_stat(stat, 0) for stat in c.stats)))

            # Assemble the data
            unique_pokemon = set(fp.pokemon for fp in c.found_pokemon
                                 if fp.pokemon)
            for label, getter in relative_things:
                c.relatives[label] = dict()

                # Get all the values at once; need to get min and max to figure
                # out relative position
                numbers = dict()
                for pokemon in unique_pokemon:
                    numbers[pokemon] = getter(pokemon)

                min_number = min(numbers.values())
                max_number = max(numbers.values())

                # Rig a little function to figure out the percentage, making
                # sure to avoid division by zero
                if min_number == max_number:
                    calc = lambda n: 1.0
                else:
                    calc = lambda n: 1.0 * (n - min_number) \
                                         / (max_number - min_number)

                for pokemon in unique_pokemon:
                    c.relatives[label][pokemon] \
                        = numbers[pokemon], calc(numbers[pokemon])

            ### Relative sizes
            raw_heights = dict(
                enumerate(fp.pokemon.height if fp and fp.pokemon else 0
                          for fp in c.found_pokemon))
            raw_heights['trainer'] = pokedex_helpers.trainer_height
            c.heights = pokedex_helpers.scale_sizes(raw_heights)

            raw_weights = dict(
                enumerate(fp.pokemon.weight if fp and fp.pokemon else 0
                          for fp in c.found_pokemon))
            raw_weights['trainer'] = pokedex_helpers.trainer_weight
            c.weights = pokedex_helpers.scale_sizes(raw_weights, dimensions=2)

            ### Moves
            # Constructs a table like the pokemon-moves table, except each row
            # is a move and it indicates which Pokémon learn it.  Still broken
            # up by method.
            # So, need a dict of method => move => pokemons.
            c.moves = defaultdict(lambda: defaultdict(set))
            # And similarly for level moves, level => pokemon => moves
            c.level_moves = defaultdict(lambda: defaultdict(list))
            q = db.pokedex_session.query(tables.PokemonMove) \
                .filter(tables.PokemonMove.version_group == c.version_group) \
                .filter(tables.PokemonMove.pokemon_id.in_(
                    _.id for _ in unique_pokemon)) \
                .options(
                    eagerload('move'),
                    eagerload('method'),
                )
            for pokemon_move in q:
                c.moves[pokemon_move.method][pokemon_move.move].add(
                    pokemon_move.pokemon)

                if pokemon_move.level:
                    c.level_moves[pokemon_move.level] \
                        [pokemon_move.pokemon].append(pokemon_move.move)

            # Get TM/HM numbers for display purposes
            c.machines = dict((machine.move, machine.machine_number)
                              for machine in c.version_group.machines)

        return render('/pokedex/gadgets/compare_pokemon.mako')
예제 #55
0
	def delete_confirmed(self, id):
		app_globals.rpcservice.remove_user(session['user'], session['passhash'], id)
		return redirect(url.current(action='index'))
예제 #56
0
	def turnoff_key(self, id):
		app_globals.rpcservice.turnoff_key(session['user'], session['passhash'], id)
		return redirect(url.current(action='edit'))
예제 #57
0
    def index(self, repo_name):
        c.dbrepo = dbrepo = c.rhodecode_db_repo
        c.following = self.scm_model.is_following_repo(
            repo_name, self.rhodecode_user.user_id)

        def url_generator(**kw):
            return url('shortlog_home', repo_name=repo_name, size=10, **kw)

        c.repo_changesets = RepoPage(c.rhodecode_repo,
                                     page=1,
                                     items_per_page=10,
                                     url=url_generator)

        if self.rhodecode_user.username == 'default':
            # for default(anonymous) user we don't need to pass credentials
            username = ''
            password = ''
        else:
            username = str(self.rhodecode_user.username)
            password = '******'

        parsed_url = urlparse(url.current(qualified=True))

        default_clone_uri = '{scheme}://{user}{pass}{netloc}{path}'

        uri_tmpl = config.get('clone_uri', default_clone_uri)
        uri_tmpl = uri_tmpl.replace('{', '%(').replace('}', ')s')
        decoded_path = safe_unicode(urllib.unquote(parsed_url.path))
        uri_dict = {
            'user': username,
            'pass': password,
            'scheme': parsed_url.scheme,
            'netloc': parsed_url.netloc,
            'path': decoded_path
        }

        uri = uri_tmpl % uri_dict
        # generate another clone url by id
        uri_dict.update({
            'path':
            decoded_path.replace(repo_name, '_%s' % c.dbrepo.repo_id)
        })
        uri_id = uri_tmpl % uri_dict

        c.clone_repo_url = uri
        c.clone_repo_url_id = uri_id
        c.repo_tags = OrderedDict()
        for name, hash_ in c.rhodecode_repo.tags.items()[:10]:
            try:
                c.repo_tags[name] = c.rhodecode_repo.get_changeset(hash_)
            except ChangesetError:
                c.repo_tags[name] = EmptyChangeset(hash_)

        c.repo_branches = OrderedDict()
        for name, hash_ in c.rhodecode_repo.branches.items()[:10]:
            try:
                c.repo_branches[name] = c.rhodecode_repo.get_changeset(hash_)
            except ChangesetError:
                c.repo_branches[name] = EmptyChangeset(hash_)

        td = date.today() + timedelta(days=1)
        td_1m = td - timedelta(days=calendar.mdays[td.month])
        td_1y = td - timedelta(days=365)

        ts_min_m = mktime(td_1m.timetuple())
        ts_min_y = mktime(td_1y.timetuple())
        ts_max_y = mktime(td.timetuple())

        if dbrepo.enable_statistics:
            c.show_stats = True
            c.no_data_msg = _('No data loaded yet')
            run_task(get_commits_stats, c.dbrepo.repo_name, ts_min_y, ts_max_y)
        else:
            c.show_stats = False
            c.no_data_msg = _('Statistics are disabled for this repository')
        c.ts_min = ts_min_m
        c.ts_max = ts_max_y

        stats = self.sa.query(Statistics)\
            .filter(Statistics.repository == dbrepo)\
            .scalar()

        c.stats_percentage = 0

        if stats and stats.languages:
            c.no_data = False is dbrepo.enable_statistics
            lang_stats_d = json.loads(stats.languages)
            c.commit_data = stats.commit_activity
            c.overview_data = stats.commit_activity_combined

            lang_stats = ((x, {
                "count": y,
                "desc": LANGUAGES_EXTENSIONS_MAP.get(x)
            }) for x, y in lang_stats_d.items())

            c.trending_languages = json.dumps(
                sorted(lang_stats, reverse=True, key=lambda k: k[1])[:10])
            last_rev = stats.stat_on_revision + 1
            c.repo_last_rev = c.rhodecode_repo.count()\
                if c.rhodecode_repo.revisions else 0
            if last_rev == 0 or c.repo_last_rev == 0:
                pass
            else:
                c.stats_percentage = '%.2f' % ((float(
                    (last_rev)) / c.repo_last_rev) * 100)
        else:
            c.commit_data = json.dumps({})
            c.overview_data = json.dumps([[ts_min_y, 0], [ts_max_y, 10]])
            c.trending_languages = json.dumps({})
            c.no_data = True

        c.enable_downloads = dbrepo.enable_downloads
        if c.enable_downloads:
            c.download_options = self._get_download_links(c.rhodecode_repo)

        c.readme_data, c.readme_file = self.__get_readme_data(
            c.rhodecode_db_repo.repo_name, c.rhodecode_repo)
        return render('summary/summary.html')
예제 #58
0
 def url_generator(**kw):
     return url.current(filter=c.search_term, **kw)