Ejemplo n.º 1
0
    def signout_confirm(self, id=None):
        """ Confirm user wants to sign out
        """
        if id is not None:
            redirect_to(action='signout_confirm', id=None)

        return render('/person/signout.mako')
Ejemplo n.º 2
0
 def do_email_students(self):
     log.debug(str(request.params))
     user = h.get_user(request.environ)
     student_ids_str = request.params['student_ids']
     student_ids = ah.fileset_id_string_to_id_list(student_ids_str)
     students = Student.query.filter(Student.id.in_(student_ids)).all()
     students = filter(lambda student: request.params.has_key(str(student.id)), students)
     for student in students:
         check_student_access(student)
     subject = request.params['subject']
     body = request.params['body']
     from_addr = (user.givenName+" "+user.surName,user.name + '@illinois.edu')
     reply_to = user.name + '@illinois.edu'
     to_addrs = map(lambda student: (student.displayName, student.netid + "@illinois.edu"), students)
     from turbomail import Message
     message = Message()
     message.subject = subject
     message.plain = body
     message.author = from_addr
     message.reply_to = reply_to
     message.to = to_addrs
     message.cc = from_addr
     message.send()
     if request.params.has_key('assignment_id'):
         return redirect_to(controller='view_analysis', action='view', id=request.params['assignment_id'])
     else:
         return redirect_to(controller='view_analysis', action='list')
Ejemplo n.º 3
0
 def pending(self, id):
     volunteer = Volunteer.find_by_id(id)
     volunteer.accepted = None
     volunteer.ticket_type = None
     meta.Session.commit()
     h.flash("Status Updated")
     redirect_to(action="index", id=None)
Ejemplo n.º 4
0
    def _new(self):
        # Do we allow account creation?
        if lca_info['account_creation']:
            """Create a new person submit.
            """

            # Remove fields not in class
            results = self.form_result['person']
            del results['password_confirm']
            del results['email_address2']
            c.person = Person(**results)
            c.person.email_address = c.person.email_address.lower()
            meta.Session.add(c.person)

            #for sn in self.form_result['social_network']:
            #   network = SocialNetwork.find_by_name(sn['name'])
            #   if sn['account_name']:
            #       c.person.social_networks[network] = sn['account_name']

            meta.Session.commit()

            if lca_rego['confirm_email_address'] == 'no':
                redirect_to(controller='person', action='confirm', confirm_hash=c.person.url_hash)
            else:
                email(c.person.email_address, render('/person/new_person_email.mako'))
                return render('/person/thankyou.mako')
        else:
            return render('/not_allowed.mako')
Ejemplo n.º 5
0
 def _edit(self, id):
     results = self.form_result["volunteer"]
     c.volunteer = Volunteer.find_by_id(id)
     for key in self.form_result["volunteer"]:
         setattr(c.volunteer, key, self.form_result["volunteer"][key])
     meta.Session.commit()
     redirect_to(action="view", id=c.volunteer.id)
Ejemplo n.º 6
0
 def create(self):
     propertyId = request.POST['propertyId']
     input = request.POST['units']
     input = input.strip(' ')
     
     if input.startswith(('x ', 'X ')):
         errorslist = self.deleteValidate()
         
         if errorslist:
             unitJSON = {
                 'errors': errorslist
             }
             return json.dumps(unitJSON)
         
         input = input.strip(' ')
         input = input.lstrip('x')
         input = input.lstrip('X')
         input = input.replace(' ', '')
         model.Unit.delete_units(input, propertyId)
     else:
         errorslist = self.addValidate()
         
         if errorslist:
             unitJSON = {
                 'errors': errorslist
             }
             return json.dumps(unitJSON)
         
         input = input.replace(' ', '')
         model.Unit.add_units(input, propertyId)
     
     redirect_to(protocol=settings.PROTOCOL, controller='property', action='json', id=propertyId)
Ejemplo n.º 7
0
    def index(self):
        # Check access and redirect
        if not h.auth.authorized(h.auth.has_organiser_role):
            redirect_to(action="new")

        c.volunteer_collection = Volunteer.find_all()
        return render("volunteer/list.mako")
Ejemplo n.º 8
0
    def submit(self):
        """
        Verify username and password
        """
        # Both fields filled?
        form_username = str(request.params.get('username'))
        form_password = str(request.params.get('password'))

        # Get user data from database
        db_user = meta.Session.query(User).filter(User.username==form_username).first()
        if db_user is None: # User does not exist
            return render('login.mako')

        # AUTHENTIC USER HERE
        #if db_user.passwd != md5.md5(form_password).hexdigest():
        #    return render('login.mako')

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

        # Send user back to the page he originally wanted to get to
        if session.get('path_before_login'):
            redirect_to(session['path_before_login'])
        else: # if previous target is unknown just send the user to a welcome page
            return redirect_to(controller='application', action='index')
Ejemplo n.º 9
0
    def save(self):
        up = UserProperty(session['identifier'],
                          self.form_result['nickname'],
                          int(self.form_result['time_diff']))

        self.ups.save(up)
        redirect_to('now')
Ejemplo n.º 10
0
    def _delete(self, id):
        c.rego_note = RegoNote.find_by_id(id)
        meta.Session.delete(c.rego_note)
        meta.Session.commit()

        h.flash("Rego note has been deleted.")
        redirect_to("index")
Ejemplo n.º 11
0
 def changepassword (self, id=None):
     user = h.checkuser(id)
     h.requirerights(user_is=id)
     user.password = md5(self.form_result['newpass'].encode('utf-8')).hexdigest()
     meta.Session.commit()
     h.flashmsg (u"Пароль был изменён")
     redirect_to(h.url_for(controller='usercontrol', action='list', id=None))
Ejemplo n.º 12
0
 def take(self, id=None):
     order = h.checkorder(id)
     # Теперь - проверка прав доступа (ответственный подразделения, могущего выполнять заявки)
     if not (h.have_role("appointer") and order.status_id == 1):
         abort(403)
     elif h.have_role("guest"):
         abort(401)
     act = model.Action()
     act.order_id = order.id
     act.status = meta.Session.query(model.Status).get(2)
     act.div_id = session["division"]
     # Заполним исполнителей заявки
     for pid in self.form_result["performers"]:
         perf = meta.Session.query(model.Person).get(pid)
         act.performers.append(perf)
         order.order_performers.append(model.OrderPerformer(person=perf, current=True))
     order.status = meta.Session.query(model.Status).get(2)
     order.perf_id = session["division"]
     meta.Session.add(act)
     # Готово!
     meta.Session.commit()
     h.flashmsg(
         u"Вы взяли заявку № "
         + h.strong(order.id)
         + u" для выполнения себе. Исполнители: %s" % (u", ".join([h.name(x) for x in act.performers]))
     )
     redirect_to(h.url_for(controller="order", action="view", id=order.id))
Ejemplo n.º 13
0
 def revoke(self, id=None):
     """Отзыв заявки её создателем (например, решили проблему сами или «ложная тревога»)."""
     order = h.checkorder(id)
     # Заявка должна быть свободна!
     if order.status.id != 1:
         abort(403)
     # Проверка прав доступа (админ либо ответственный подразделения, создавшего заявку)
     if not (
         h.have_role("admin")
         or (
             session.has_key("division")
             and session.has_key("creator")
             and session["creator"]
             and order.cust_id == session["division"]
         )
     ):
         abort(401)
     # Заявка готова, но никто её не сделал
     order.status = meta.Session.query(model.Status).get(15)
     order.performers = []
     order.performer = None
     # Добавление записи в журнал действий над заявкой
     act = model.Action()
     act.order_id = order.id
     act.status = meta.Session.query(model.Status).get(15)
     act.division = meta.Session.query(model.Division).get(session["division"])
     act.performers.append(meta.Session.query(model.Person).get(session["id"]))
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         act.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     meta.Session.add(act)
     # Готово
     meta.Session.commit()
     h.flashmsg(u"Заявка № " + h.strong(order.id) + u" отозвана.")
     redirect_to(h.url_for(controller="order", action="view", id=order.id))
Ejemplo n.º 14
0
    def _delete(self, id):
        c.special_offer = SpecialOffer.find_by_id(id)
        meta.Session.delete(c.special_offer)
        meta.Session.commit()

        h.flash("Special Offer has been deleted.")
        redirect_to('index')
Ejemplo n.º 15
0
    def add(self):
        if request.POST:
            c.name = request.POST.get('name')
            c.description = request.POST.get('description')
            c.identifier = request.POST.get('identifier')
            c.homepage = request.POST.get('homepage')
            c.is_public = request.POST.get('is_public') or False
            
            if not c.name:
                c.error = 'You must enter a name'
                return render('/projects/add.mao')

            if not c.identifier:
                c.error = 'You must enter an identifier'
                return render('/projects/add.mao')
            
            project = Project()
            project.name = c.name
            project.description = c.description
            project.homepage = c.homepage
            project.is_public = c.is_public
            project.identifier = c.identifier
            db.add(project)
            db.commit()
            redirect_to(action='show', id=c.identifier)
        
        return render('/projects/add.mao')
Ejemplo n.º 16
0
 def update(self):
     errorslist = self.validate()
     if errorslist:
         conJSON = {'errors': errorslist}
         return json.dumps(conJSON)
     
     contact_id = request.POST['contactId']
     type = request.POST['type']
     if int(request.POST['newtype']):
         type_id = str(uuid.uuid1())
         model.Contact_type.create(id=type_id, label=type)
     else:
         type_id = type
     
     model.Contact.update(
                          id=contact_id,
                          typeid=type_id,
                          label=request.POST['label'],
                          address=request.POST['address'],
                          city=request.POST['city'],
                          state=request.POST['state'],
                          zip=request.POST['zip'],
                          phone=request.POST['phone'],
                          email=request.POST['email'],
                          description=request.POST['description']
                          )
     redirect_to(controller='contacts', action='json', type='all')
Ejemplo n.º 17
0
    def _delete(self, id):
        c.event = Event.find_by_id(id)
        meta.Session.delete(c.event)
        meta.Session.commit()

        h.flash("Event has been deleted.")
        redirect_to('index')
Ejemplo n.º 18
0
    def _delete(self, id):
        c.time_slot = TimeSlot.find_by_id(id)
        meta.Session.delete(c.time_slot)
        meta.Session.commit()

        h.flash("Time Slot has been deleted.")
        redirect_to('index')
Ejemplo n.º 19
0
    def _delete(self, id):
        c.rego_room = RegoRoom.find_by_id(id)
        meta.Session.delete(c.rego_room)
        meta.Session.commit()

        h.flash("Rego room has been deleted.")
        redirect_to('index')
Ejemplo n.º 20
0
 def makecomplaint (self):
     order = meta.Session.query(model.Order).filter_by(id=self.form_result['id']).first()
     if order is None:
         abort(404)
     if order.deleted:
         abort(410)
     # Теперь - проверка прав доступа (ответственный подразделения, подавшего эту заявку)
     if not (session.has_key('division') and session['division']):
         abort(401)
     if not (h.have_role('creator') and order.cust_id == session['division']):
         abort(403)
     complaint = model.Action()
     complaint.order_id = order.id
     complaint.status = meta.Session.query(model.Status).get(6)
     complaint.div_id = session['division']
     perf = meta.Session.query(model.Person).get(session['id'])
     complaint.performers.append(perf)
     # Если претензию подаёт оператор, то и его добавим
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         complaint.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     complaint.description = self.form_result['description']
     meta.Session.add (complaint)
     order.status = meta.Session.query(model.Status).get(6)
     # Обновляем создателей заявки
     if perf not in order.customers:
         order.customers.append(perf)
     meta.Session.commit()
     h.flashmsg (u"Жалоба подана. Всех лишат зарплаты. Дело заявки № " + h.strong(order.id) + u" будет сделано.")
     redirect_to(h.url_for(controller='order', action='view', id=order.id)) 
Ejemplo n.º 21
0
 def makethank (self):
     order = meta.Session.query(model.Order).filter_by(id=self.form_result['id']).first()
     if order is None:
         abort(404)
     if order.deleted:
         abort(410)
     # Теперь - проверка прав доступа (ответственный подразделения, подавшего эту заявку)
     if not (session.has_key('division') and session['division']):
         abort(401)
     if not (h.have_role('creator') and order.cust_id == session['division']):
         abort(403)
     thank = model.Action()
     thank.order_id = order.id
     thank.status = meta.Session.query(model.Status).get(14)
     thank.div_id = session['division']
     perf = meta.Session.query(model.Person).get(session['id'])
     thank.performers.append(perf)
     # Если претензию подаёт оператор, то и его добавим
     if session.has_key("operator_id") and session["id"] != session["operator_id"]:
         thank.performers.append(meta.Session.query(model.Person).get(session["operator_id"]))
     thank.description = self.form_result['description']
     meta.Session.add (thank)
     meta.Session.commit()
     h.flashmsg (u"Спасибо за " + h.literal("«") + u"спасибо" + h.literal("»") + "!")
     redirect_to(h.url_for(controller='order', action='view', id=order.id)) 
Ejemplo n.º 22
0
    def _review(self, id):
        """Review a funding application.
        """
        c.funding = Funding.find_by_id(id)
        c.signed_in_person = h.signed_in_person()
        c.next_review_id = Funding.find_next_proposal(c.funding.id, c.funding.type.id, c.signed_in_person.id)

        person = c.signed_in_person
        if person in [ review.reviewer for review in c.funding.reviews]:
            h.flash('Already reviewed')
            return redirect_to(action='review', id=c.next_review_id)

        results = self.form_result['review']
        if results['score'] == 'null':
          results['score'] = None

        review = FundingReview(**results)

        meta.Session.add(review)
        c.funding.reviews.append(review)

        review.reviewer = person

        meta.Session.commit()
        if c.next_review_id:
            return redirect_to(action='review', id=c.next_review_id)

        h.flash("No more funding applications to review")

        return redirect_to(action='review_index')
Ejemplo n.º 23
0
    def _review(self, id):
        """Review a proposal.
        """
        c.proposal = Proposal.find_by_id(id)
        c.signed_in_person = h.signed_in_person()
        c.next_review_id = Proposal.find_next_proposal(c.proposal.id, c.proposal.type.id, c.signed_in_person.id)

        # TODO: currently not enough (see TODOs in model/proposal.py)
        #if not h.auth.authorized(h.auth.has_organiser_role):
        #    # You can't review your own proposal
        #    for person in c.proposal.people:
        #        if person.id == c.signed_in_person.id:
        #            h.auth.no_role()

        person = c.signed_in_person
        if person in [ review.reviewer for review in c.proposal.reviews]:
            h.flash('Already reviewed')
            return redirect_to(action='review', id=c.next_review_id)

        results = self.form_result['review']
        review = Review(**results)

        meta.Session.add(review)
        c.proposal.reviews.append(review)

        review.reviewer = person

        meta.Session.commit()

        if c.next_review_id:
            return redirect_to(action='review', id=c.next_review_id)

        h.flash("No more papers to review")

        return redirect_to(action='review_index')
Ejemplo n.º 24
0
    def _delete(self, id):
        c.location = Location.find_by_id(id)
        meta.Session.delete(c.location)
        meta.Session.commit()

        h.flash("Location has been deleted.")
        redirect_to('index')
Ejemplo n.º 25
0
 def save(self, id=None):
     """Save a record and redirect to new or edit."""
     rock_q = model.meta.Session.query(model.Rock)
     rock = rock_q.filter_by(id=id).first()
     if not rock:
         # if the record did not exist yet
         rock = model.Rock()
     rock.geo_zone = request.POST.get("geo_zone", "")
     rock.geo_group = request.POST.get("geo_group", "")
     rock.rock_number = request.POST.get("rock_number", "")
     rock.rock_name = request.POST.get("rock_name", "")
     rock.x = request.POST.get("x", "")
     rock.y = request.POST.get("y", "")
     rock.z = request.POST.get("z", "")
     rock.length = request.POST.get("length", "")
     rock.width = request.POST.get("width", "")
     rock.geo_context_torrent = request.POST.get("geo_context_torrent", "")
     rock.geo_context_lake = request.POST.get("geo_context_lake", "")
     rock.geo_context_bog = request.POST.get("geo_context_bog", "")
     rock.geo_context_pass = request.POST.get("geo_context_pass", "")
     rock.geo_context_summit = request.POST.get("geo_context_summit", "")
     rock.rock_type = request.POST.get("rock_type", "")
     rock.outcrop_type = request.POST.get("outcrop_type", "")
     rock.provision = request.POST.get("provision", "")
     rock.description = request.POST.get("description", "")
     model.meta.Session.save_or_update(rock)
     model.meta.Session.commit()
     # Issue a redirect based on the submit button
     if "new_button" in request.POST.keys():
         return redirect_to(action="new")
     elif "edit_button" in request.POST.keys():
         return redirect_to(url_for(action="edit", id=rock.id))
     elif "delete_button" in request.POST.keys():
         return redirect_to(url_for(action="delete", id=rock.id))
Ejemplo n.º 26
0
 def save(self):
     """Save user's data to the userId given.
     """
     propertyFilter = request.POST['propertyId'] != 'false' and request.POST['propertyId'] or None 
     userId = request.POST['userId']
     fname = request.POST['fname'].strip()
     lname = request.POST['lname'].strip()
     email = request.POST['email'].strip()
     phone = request.POST['phone'].strip()
     admin = request.POST['admin']
     
     errorslist = self.validate(action='update')
     
     if errorslist:
         userJSON = {
             'errors': errorslist
         }
         return json.dumps(userJSON)
     
     user = meta.Session.query(model.Manager).filter_by(id=userId).first()
     user.first_name = fname
     user.last_name = lname
     user.email = email
     user.phone = phone
     user.type = int(admin) and 'admin' or 'manager'
     
     meta.Session.commit()
     session.save()
     redirect_to(controller='user', action='json', id=propertyFilter)
Ejemplo n.º 27
0
    def save(self):
        up = UserProperty(request.environ['REMOTE_USER'],
                          self.form_result['nickname'],
                          int(self.form_result['time_diff']))

        self.ups.put_item(up)
        redirect_to('now')
Ejemplo n.º 28
0
    def _delete(self, id):
        c.schedule = Schedule.find_by_id(id)
        meta.Session.delete(c.schedule)
        meta.Session.commit()

        h.flash("Schedule has been deleted.")
        redirect_to('index')
Ejemplo n.º 29
0
    def _delete(self, id):
        c.stream = Stream.find_by_id(id)
        meta.Session.delete(c.stream)
        meta.Session.commit()

        h.flash("Stream has been deleted.")
        redirect_to('index')
Ejemplo n.º 30
0
 def _delete_me(self, deck_id=None):
     if users.is_current_user_admin():
         deck = Deck.get_all_by_id_base30(deck_id)
         db.delete(deck)
         redirect_to(h.url_for("/"))
     else:
         abort(401)
Ejemplo n.º 31
0
def set_subreddit():
    #the r parameter gets added by javascript for POST requests so we
    #can reference c.site in api.py
    sr_name = request.environ.get("subreddit", request.POST.get('r'))
    domain = request.environ.get("domain")

    can_stale = request.method.upper() in ('GET', 'HEAD')

    c.site = Frontpage
    if not sr_name:
        #check for cnames
        cname = request.environ.get('legacy-cname')
        if cname:
            sr = Subreddit._by_domain(cname) or Frontpage
            domain = g.domain
            if g.domain_prefix:
                domain = ".".join((g.domain_prefix, domain))
            redirect_to('http://%s%s' % (domain, sr.path), _code=301)
    elif sr_name == 'r':
        #reddits
        c.site = Sub
    elif '+' in sr_name:
        sr_names = sr_name.split('+')
        srs = Subreddit._by_name(sr_names, stale=can_stale).values()
        if All in srs:
            c.site = All
        elif Friends in srs:
            c.site = Friends
        else:
            srs = [sr for sr in srs if not isinstance(sr, FakeSubreddit)]
            if not srs:
                c.site = MultiReddit([], sr_name)
            elif len(srs) == 1:
                c.site = srs[0]
            else:
                c.site = MultiReddit(srs, sr_name)
    elif '-' in sr_name:
        sr_names = sr_name.split('-')
        if not sr_names[0].lower() == All.name.lower():
            redirect_to("/subreddits/search?q=%s" % sr_name)
        srs = Subreddit._by_name(sr_names[1:], stale=can_stale).values()
        srs = [sr for sr in srs if not isinstance(sr, FakeSubreddit)]
        if not srs:
            c.site = All
        else:
            c.site = AllMinus(srs)
    else:
        try:
            c.site = Subreddit._by_name(sr_name, stale=can_stale)
        except NotFound:
            sr_name = chksrname(sr_name)
            if sr_name:
                redirect_to("/subreddits/search?q=%s" % sr_name)
            elif not c.error_page and not request.path.startswith(
                    "/api/login/"):
                abort(404)

    #if we didn't find a subreddit, check for a domain listing
    if not sr_name and isinstance(c.site, DefaultSR) and domain:
        c.site = DomainSR(domain)

    if isinstance(c.site, FakeSubreddit):
        c.default_sr = True
Ejemplo n.º 32
0
 def GET_wiki_redirect(self, page='index'):
     return redirect_to(str("%s/%s" % (c.wiki_base_url, page)), _code=301)
Ejemplo n.º 33
0
 def GET_redirect(self, dest):
     return redirect_to(str(dest))
Ejemplo n.º 34
0
    def _check_perms(self, checks=PERM_CHECK_WS | PERM_CHECK_USER):
        log.debug("_check_perms() called.")

        if checks & PERM_CHECK_WS:
            # Get workspace flags from KCD.
            kcd_workspace = KcdKwsList.get_by(kws_id=c.workspace.id)
            kcd_ws_flags = kcd_workspace.flags

            # Detect if workspace is deleted.
            if kcd_ws_flags & KANP_KWS_FLAG_DELETE:
                log.debug(
                    "_check_perms(): workspace deleted... unlogging and redirecting."
                )
                init_session(c.workspace, reinit=True)
                redirect_to(
                    url('message_show',
                        workspace_id=c.workspace.id,
                        warning_code='workspace_deleted'))

            # Detect if workspace was changed from non-secure to secure.
            if kcd_ws_flags & KANP_KWS_FLAG_SECURE and not session['secure']:
                log.debug(
                    "Reinitializing session because workspace changed from non-secure to secure."
                )
                if not c.workspace.public:
                    email_id = None
                    if 'email_id' in session and session['email_id']:
                        email_id = session['email_id']
                    if email_id:
                        init_session(c.workspace, reinit=True)
                        return redirect_to(
                            url('invitation_url',
                                workspace_id=c.workspace.id,
                                email_id=email_id,
                                warning_code='nstos'))

                init_session(c.workspace, reinit=True)
                return redirect_to(url('teambox', workspace_id=c.workspace.id))

        if checks & PERM_CHECK_USER:
            if 'user' in session and session['user']:
                # Get user flags from KCD.
                kcd_user = KcdUser.get_by(kws_id=c.workspace.id,
                                          user_id=session['user']['id'])
                kcd_user_flags = kcd_user.flags

                # Detect if user is out.
                user_locked = bool(kcd_user_flags & KANP_USER_FLAG_LOCK)
                user_banned = bool(kcd_user_flags & KANP_USER_FLAG_BAN)
                user_generic_out = False
                if session['mode'] == MODE_WS and not c.is_admin:
                    # User is logged as a regular user (workspace mode).
                    if not Invitation.get_by(email_id=session['email_id']):
                        # Invitation email no longer exist.
                        user_generic_out = True

                # Destroy session if needed.
                if user_locked or user_banned or user_generic_out:
                    init_session(c.workspace, reinit=True)

                # Set URL for redirecting.
                u = None
                if user_locked:
                    u = url('message_show',
                            workspace_id=c.workspace.id,
                            warning_code='user_locked')
                    log.debug(
                        "_check_perms(): user locked... redirecting to '%s'." %
                        (str(u)))
                elif user_banned:
                    u = url('message_show',
                            workspace_id=c.workspace.id,
                            warning_code='user_banned')
                    log.debug(
                        "_check_perms(): user banned... redirecting to '%s'." %
                        (str(u)))
                elif user_generic_out:
                    u = url('message_show',
                            workspace_id=c.workspace.id,
                            warning_code='user_generic_out')
                    log.debug(
                        "_check_perms(): user out, we don't know why... redirecting to '%s'."
                        % (str(u)))
                if u: redirect_to(u)
Ejemplo n.º 35
0
    def pre(self):
        record_timings = g.admin_cookie in request.cookies or g.debug
        admin_bar_eligible = response.content_type == 'text/html'
        if admin_bar_eligible and record_timings:
            g.stats.start_logging_timings()

        # set up stuff needed in base templates at error time here.
        c.js_preload = JSPreload()

        MinimalController.pre(self)

        set_cnameframe()

        # populate c.cookies unless we're on the unsafe media_domain
        if request.host != g.media_domain or g.media_domain == g.domain:
            cookie_counts = collections.Counter()
            try:
                for k, v in request.cookies.iteritems():
                    # minimalcontroller can still set cookies
                    if k not in c.cookies:
                        # we can unquote even if it's not quoted
                        c.cookies[k] = Cookie(value=unquote(v), dirty=False)
                        cookie_counts[Cookie.classify(k)] += 1
            except CookieError:
                #pylons or one of the associated retarded libraries
                #can't handle broken cookies
                request.environ['HTTP_COOKIE'] = ''

            for cookietype, count in cookie_counts.iteritems():
                g.stats.simple_event("cookie.%s" % cookietype, count)

        delete_obsolete_cookies()

        # the user could have been logged in via one of the feeds
        maybe_admin = False
        is_otpcookie_valid = False

        # no logins for RSS feed unless valid_feed has already been called
        if not c.user:
            if c.extension != "rss":
                authenticate_user()

                admin_cookie = c.cookies.get(g.admin_cookie)
                if c.user_is_loggedin and admin_cookie:
                    maybe_admin, first_login = valid_admin_cookie(
                        admin_cookie.value)

                    if maybe_admin:
                        self.enable_admin_mode(c.user, first_login=first_login)
                    else:
                        self.disable_admin_mode(c.user)

                otp_cookie = read_user_cookie(g.otp_cookie)
                if c.user_is_loggedin and otp_cookie:
                    is_otpcookie_valid = valid_otp_cookie(otp_cookie)

            if not c.user:
                c.user = UnloggedUser(get_browser_langs())
                # patch for fixing mangled language preferences
                if (not isinstance(c.user.pref_lang, basestring) or not all(
                        isinstance(x, basestring)
                        for x in c.user.pref_content_langs)):
                    c.user.pref_lang = g.lang
                    c.user.pref_content_langs = [g.lang]
                    c.user._commit()
        if c.user_is_loggedin:
            if not c.user._loaded:
                c.user._load()
            c.modhash = c.user.modhash()
            if hasattr(c.user, 'msgtime') and c.user.msgtime:
                c.have_messages = c.user.msgtime
            c.show_mod_mail = Subreddit.reverse_moderator_ids(c.user)
            c.have_mod_messages = getattr(c.user, "modmsgtime", False)
            c.user_is_admin = maybe_admin and c.user.name in g.admins
            c.user_special_distinguish = c.user.special_distinguish()
            c.user_is_sponsor = c.user_is_admin or c.user.name in g.sponsors
            c.otp_cached = is_otpcookie_valid
            if not isinstance(c.site,
                              FakeSubreddit) and not g.disallow_db_writes:
                c.user.update_sr_activity(c.site)

        c.over18 = over18()
        set_obey_over18()

        #set_browser_langs()
        set_host_lang()
        set_iface_lang()
        set_content_lang()
        set_recent_clicks()
        # used for HTML-lite templates
        set_colors()

        # set some environmental variables in case we hit an abort
        if not isinstance(c.site, FakeSubreddit):
            request.environ['REDDIT_NAME'] = c.site.name

        # random reddit trickery -- have to do this after the content lang is set
        if c.site == Random:
            c.site = Subreddit.random_reddit(user=c.user)
            redirect_to("/" + c.site.path.strip('/') + request.path)
        elif c.site == RandomSubscription:
            if c.user.gold:
                c.site = Subreddit.random_subscription(c.user)
                redirect_to('/' + c.site.path.strip('/') + request.path)
            else:
                redirect_to('/gold/about')
        elif c.site == RandomNSFW:
            c.site = Subreddit.random_reddit(over18=True, user=c.user)
            redirect_to("/" + c.site.path.strip('/') + request.path)

        if not request.path.startswith("/api/login/"):
            # is the subreddit banned?
            if c.site.spammy() and not c.user_is_admin and not c.error_page:
                ban_info = getattr(c.site, "ban_info", {})
                if "message" in ban_info:
                    message = ban_info['message']
                else:
                    sitelink = url_escape(add_sr("/"))
                    subject = ("/r/%s has been incorrectly banned" %
                               c.site.name)
                    link = ("/r/redditrequest/submit?url=%s&title=%s" %
                            (sitelink, subject))
                    message = strings.banned_subreddit_message % dict(
                        link=link)
                errpage = pages.RedditError(strings.banned_subreddit_title,
                                            message,
                                            image="subreddit-banned.png")
                request.environ['usable_error_content'] = errpage.render()
                self.abort404()

            # check if the user has access to this subreddit
            if not c.site.can_view(c.user) and not c.error_page:
                public_description = c.site.public_description
                errpage = pages.RedditError(strings.private_subreddit_title,
                                            strings.private_subreddit_message,
                                            image="subreddit-private.png",
                                            sr_description=public_description)
                request.environ['usable_error_content'] = errpage.render()
                self.abort403()

            #check over 18
            if (c.site.over_18 and not c.over18
                    and request.path not in ("/frame", "/over18")
                    and c.render_style == 'html'):
                return self.intermediate_redirect("/over18")

        #check whether to allow custom styles
        c.allow_styles = True
        c.can_apply_styles = self.allow_stylesheets
        if g.css_killswitch:
            c.can_apply_styles = False
        #if the preference is set and we're not at a cname
        elif not c.user.pref_show_stylesheets and not c.cname:
            c.can_apply_styles = False
        #if the site has a cname, but we're not using it
        elif c.site.domain and c.site.css_on_cname and not c.cname:
            c.can_apply_styles = False

        c.show_admin_bar = admin_bar_eligible and (c.user_is_admin or g.debug)
        if not c.show_admin_bar:
            g.stats.end_logging_timings()

        hooks.get_hook("reddit.request.begin").call()

        c.request_timer.intermediate("base-pre")
Ejemplo n.º 36
0
    def demo_up(self):
        event = meta.Session.query(model.Event).filter(
            model.Event.id == 1
        ).one()

        user = meta.Session.query(model.User).filter(
            model.User.nickname == 'demo'
        ).one()

        for node in event.persons: meta.Session.delete(node)
        for node in event.reports: meta.Session.delete(node)
        for node in event.albums: meta.Session.delete(node)

        meta.Session.commit()

        dir = config['demo_dir']

        info_file = os.path.join(dir, 'info.yml')
        info = codecs.open(info_file, 'r', 'utf-8')
        info = yaml.load(info)

        event.title = info['title']
        if 'summary' in info:
            event.summary = info['summary']
        if 'start' in info:
            event.start = info['start']
        if 'finish' in info:
            event.finish = info['finish']
        event.node_user = user
        event.created = datetime.now()

        if 'albums' in info:
            for album in info['albums']:
                node = model.Album()
                node.settings = picasa.photos(album['user'], album['albumid'], 15)
                node.node_user = user
                node.event = event
                meta.Session.add(node)


        persons_dir = os.path.join(dir, u'persons')
        for file in os.listdir(persons_dir):
            path =  os.path.join(persons_dir, file)
            if os.path.isfile(path):
                node = model.Person()
                node.fullname = file.split('.')[0]
                node.avatar = avatar_prepare(open(path, 'r'))
                node.node_user = user
                node.event = event
                meta.Session.add(node)

        reports_dir = os.path.join(dir, u'reports')
        for file in os.listdir(reports_dir):
            path =  os.path.join(reports_dir, file)
            if os.path.isfile(path):
                text = codecs.open(path, 'r', 'utf-8').read()
                node = model.Report()
                node.title = file.split('.')[0]
                node.content = text
                node.node_user = user
                node.event = event
                meta.Session.add(node)

        meta.Session.commit()

        flash(u'Демонстрация обновлена')
        return redirect_to('demo')
Ejemplo n.º 37
0
    def __before__(self, action, controller, workspace_id=None, email_id=None):

        log.debug("Request to %s.%s, workspace_id=%s, email_id=%s, session_id=%s." % \
            ( controller, action, str(workspace_id), str(email_id), str(session.id) ) )

        # Detect changes in configuration.
        def config_has_changed():
            model.new_engine()
            kcd_model.new_engine()

        detect_cached_config_change(config_has_changed,
                                    config['master_file_path'])

        # Get cached master configuration.
        c.mc = get_cached_master_config()

        # Initialize models in local thread.
        model.init_local()
        kcd_model.init_local()

        # Initialize context variables.
        c.perms = KWMOPermissions()
        c.logout_url = None
        c.glob_messages = []

        # Prevent page caching.
        response.headers['Cache-Control'] = 'no-cache, must-revalidate'
        response.headers['Max-Age'] = '0'
        response.headers['Expires'] = 'Sat, 26 Jul 1997 05:00:00 GMT'

        # Detect global message passed in session (flash).
        if 'uimessage' in session:
            c.glob_messages.append(session['uimessage'])
            del session['uimessage']
            session.save()

        # Detect global message passed in a GET variable.
        for var_name, callable in self.glob_msg_var_name_to_callable_map.items(
        ):
            code = request.GET.get(var_name, None)
            if code:
                callable(code=code)
                break

        if workspace_id:
            # Get workspace.
            ws = Workspace.get_by(id=workspace_id)
            if not ws:
                log.warn("Workspace %s does not exit." % (workspace_id))
                abort(404)  # Not reliable here!

            # Initialize some context variables.
            c.workspace = ws
            c.is_admin = False
            if 'admin' in session and session['admin'] == True:
                c.is_admin = True
            if 'user_id' in session and session['user_id']:
                # User is logged.
                c.logout_url = url('teambox_logout',
                                   workspace_id=c.workspace.id)
                if c.is_admin:
                    # User is admin.
                    c.logout_url = url('teambox_admin_logout',
                                       workspace_id=c.workspace.id)

            if 'initialized' in session:
                # Session is initialized.

                if not 'version' in session:
                    # Update session.
                    log.debug("Updating session.")
                    from kwmo.lib.updates import update_session_v1
                    update_session_v1(c, session)

                    # Save session.
                    session.save()

                # Fill the permission object with the session permissions dictionary.
                c.perms.from_dict(session['perms'])

            else:
                # Initialize session.
                init_session(ws)

            # Detect some workspace property changes.
            self._check_workspace_prop(controller, action)

            # Detect perm_check.
            if ws.last_perm_check_id > session['last_perm_check_id']:
                session['last_perm_check_id'] = ws.last_perm_check_id
                session.save()
                self._check_perms()

            # Set welcome name to use in the header partial
            if (('user_id' in session) and ('user' in session)
                    and session['user']):
                if c.is_admin:
                    c.welcome_name = 'Administrator'
                elif session['user']['admin_name']:
                    c.welcome_name = session['user']['admin_name']
                elif session['user']['real_name']:
                    c.welcome_name = session['user']['real_name']
                else:
                    c.welcome_name = session['user']['email']

            # Check session expiration if set.
            if 'expiration_time' in session and \
                    not (controller == 'admin_teambox' and action == 'login'):
                if time.time() > session['expiration_time']:
                    log.debug("Admin session expired.")
                    init_session(c.workspace, reinit=True)
                    redirect_to(
                        url('message_show',
                            workspace_id=c.workspace.id,
                            warning_code='admin_sess_expired'))

            # Authenticate
            if action in self.requires_auth:
                if 'user_id' not in session:
                    redirect_to(
                        url('invite_resend_show', workspace_id=workspace_id))
Ejemplo n.º 38
0
 def logout(self):
     c.message = u'Logout success'
     return redirect_to('/')
Ejemplo n.º 39
0
    def do_wordpress_login_logout(self, environ, new_headers):
        '''Looks at cookies and auth_tkt and may tell auth_tkt to log-in or log-out
        to a WordPress user.'''
        is_ckan_cookie, wordpress_session_id = self._parse_cookies(environ)
        # Is there a WordPress cookie? We may want to do a log-in for it.
        if wordpress_session_id:
            #log.error('Got this:' + wordpress_session_id)
            # Look at any authtkt logged in user details
            authtkt_identity = environ.get('repoze.who.identity')
            if authtkt_identity:
                authtkt_user_name = authtkt_identity[
                    'repoze.who.userid']  #same as environ.get('REMOTE_USER', '')
                authtkt_wordpress_session_id = authtkt_identity['userdata']
            else:
                authtkt_user_name = ''
                authtkt_wordpress_session_id = ''

            if not authtkt_user_name:
                # authtkt not logged in, so log-in with the WordPress cookie
                self._do_wordpress_login(environ, wordpress_session_id,
                                         new_headers)
                return
            #elif authtkt_user_name.startswith(self._user_name_prefix):
            else:
                # A WordPress user is logged in with authtkt.
                # See if that the authtkt matches the wp cookie's session
                if authtkt_wordpress_session_id != wordpress_session_id:
                    # WordPress cookie session has changed, so tell authkit to forget the old one
                    # before we do the new login.
                    log.error(
                        'WordPress cookie session has changed from %r to %r.',
                        authtkt_wordpress_session_id, wordpress_session_id)
                    self._log_out(environ, new_headers)
                    self._do_wordpress_login(environ, wordpress_session_id,
                                             new_headers)
                    return
                else:
                    log.debug('WordPress cookie session stayed the same.')
                    # WordPress cookie session matches the authtkt - leave user logged in

                    # Just check that authtkt cookie is not too old - in the
                    # mean-time, WordPress may have invalidated the user, for example.
                    if self.is_authtkt_cookie_too_old(authtkt_identity):
                        log.info('Rechecking WordPress cookie')
                        self._log_out(environ, new_headers)
                        self._do_wordpress_login(environ, wordpress_session_id,
                                                 new_headers)
                    return
            #else:
            # There's a WordPress cookie, but user is logged in as a normal CKAN user.
            # Ignore the WordPress cookie.
            #return
        elif not wordpress_session_id and is_ckan_cookie:
            # Deal with the case where user is logged out of WordPress
            # i.e. user WAS were logged in with WordPress and the cookie was
            # deleted (probably because WordPress logged out)

            # Is the logged in user a WordPress user?
            user_name = environ.get('REMOTE_USER', '')
            if user_name and user_name.startswith(self._user_name_prefix):
                log.error(
                    'Was logged in as WordPress user %r but WordPress cookie no longer there. Forcing logout.',
                    user_name)
            else:
                log.error(
                    'User %r was logged into CKAN but not WordPress. Forcing logout.',
                    user_name)
            # Force log out.
            self._log_out(environ, new_headers)
            # Redirect to the same URL to ensure no more cookies get set up and our force log out comes in effect.
            #redirect_to('http://' + config.get('wordpress_url', 'www.hri.fi') + environ['REQUEST_URI'])
            redirect_to('http://' + config.get('wordpress_url', 'www.hri.fi') +
                        '/fi/wp-login.php?action=logout')
Ejemplo n.º 40
0
def set_subreddit():
    #the r parameter gets added by javascript for POST requests so we
    #can reference c.site in api.py
    sr_name = request.environ.get("subreddit", request.POST.get('r'))
    domain = request.environ.get("domain")

    can_stale = request.method.upper() in ('GET', 'HEAD')

    c.site = Frontpage
    if not sr_name:
        #check for cnames
        cname = request.environ.get('legacy-cname')
        if cname:
            sr = Subreddit._by_domain(cname) or Frontpage
            domain = g.domain
            if g.domain_prefix:
                domain = ".".join((g.domain_prefix, domain))
            redirect_to('http://%s%s' % (domain, sr.path), _code=301)
    elif sr_name == 'r':
        #reddits
        c.site = Sub
    elif '+' in sr_name:
        sr_names = sr_name.split('+')
        srs = Subreddit._by_name(sr_names, stale=can_stale).values()
        if All in srs:
            c.site = All
        elif Friends in srs:
            c.site = Friends
        else:
            srs = [sr for sr in srs if not isinstance(sr, FakeSubreddit)]
            multi_path = '/r/' + sr_name
            if not srs:
                c.site = MultiReddit(multi_path, [])
            elif len(srs) == 1:
                c.site = srs[0]
            else:
                c.site = MultiReddit(multi_path, srs)
    elif '-' in sr_name:
        sr_names = sr_name.split('-')
        base_sr_name, exclude_sr_names = sr_names[0], sr_names[1:]
        srs = Subreddit._by_name(sr_names, stale=can_stale)
        base_sr = srs.pop(base_sr_name, None)
        exclude_srs = [
            sr for sr in srs.itervalues() if not isinstance(sr, FakeSubreddit)
        ]

        if base_sr == All:
            if exclude_srs:
                c.site = AllMinus(exclude_srs)
            else:
                c.site = All
        elif base_sr == Mod:
            if exclude_srs:
                c.site = ModMinus(exclude_srs)
            else:
                c.site = Mod
        else:
            redirect_to("/subreddits/search?q=%s" % sr_name)
    else:
        try:
            c.site = Subreddit._by_name(sr_name, stale=can_stale)
        except NotFound:
            sr_name = chksrname(sr_name)
            if sr_name:
                redirect_to("/subreddits/search?q=%s" % sr_name)
            elif not c.error_page and not request.path.startswith(
                    "/api/login/"):
                abort(404)

    #if we didn't find a subreddit, check for a domain listing
    if not sr_name and isinstance(c.site, DefaultSR) and domain:
        # Redirect IDN to their IDNA name if necessary
        try:
            idna = _force_unicode(domain).encode("idna")
            if idna != domain:
                redirect_to("/domain/%s%s" %
                            (idna, request.environ["PATH_INFO"]))
        except UnicodeError:
            domain = ''  # Ensure valid_ascii_domain fails
        if not c.error_page and not valid_ascii_domain.match(domain):
            abort(404)
        c.site = DomainSR(domain)

    if isinstance(c.site, FakeSubreddit):
        c.default_sr = True
Ejemplo n.º 41
0
 def demo(self):
     event = meta.Session.query(model.Event).filter(
         model.Event.id == 1
     ).one()
     redirect_to(event.url())
Ejemplo n.º 42
0
 def index(self):
     # Redirect to help index page
     return redirect_to(action="wiki", id="HelpIndex")
Ejemplo n.º 43
0
 def login(self):
     c.message = u'Login success'
     return redirect_to('/')
Ejemplo n.º 44
0
    def GET_badge(self, meetup, topic):
        if meetup.state not in BADGE_STATES:
            return redirect_to("/meetup/%s" % str(meetup._id))

        content = pages.QrCodeBadge(meetup, c.user, topic)
        return pages.MeatspaceBadgePage(content=content).render()
Ejemplo n.º 45
0
    def pre(self):
        MinimalController.pre(self)

        set_cnameframe()

        # populate c.cookies unless we're on the unsafe media_domain
        if request.host != g.media_domain or g.media_domain == g.domain:
            try:
                for k, v in request.cookies.iteritems():
                    # we can unquote even if it's not quoted
                    c.cookies[k] = Cookie(value=unquote(v), dirty=False)
            except CookieError:
                #pylons or one of the associated retarded libraries
                #can't handle broken cookies
                request.environ['HTTP_COOKIE'] = ''

        c.response_wrappers = []
        c.firsttime = firsttime()


        (c.user, maybe_admin) = \
            valid_cookie(c.cookies[g.login_cookie].value
                         if g.login_cookie in c.cookies
                         else '')

        if c.user:
            c.user_is_loggedin = True
        else:
            c.user = UnloggedUser(get_browser_langs())
            # patch for fixing mangled language preferences
            if (not isinstance(c.user.pref_lang, basestring) or not all(
                    isinstance(x, basestring)
                    for x in c.user.pref_content_langs)):
                c.user.pref_lang = g.lang
                c.user.pref_content_langs = [g.lang]
                c.user._commit()
        if c.user_is_loggedin:
            if not c.user._loaded:
                c.user._load()
            c.modhash = c.user.modhash()
            if request.method.lower() == 'get':
                read_mod_cookie()
            if hasattr(c.user, 'msgtime') and c.user.msgtime:
                c.have_messages = c.user.msgtime
            if hasattr(c.user, 'modmsgtime'):
                c.show_mod_mail = True
                if c.user.modmsgtime:
                    c.have_mod_messages = c.user.modmsgtime
            else:
                c.show_mod_mail = Subreddit.reverse_moderator_ids(c.user)
            c.user_is_admin = maybe_admin and c.user.name in g.admins
            c.user_is_sponsor = c.user_is_admin or c.user.name in g.sponsors
            if not g.disallow_db_writes:
                c.user.update_last_visit(c.start_time)

        c.over18 = over18()

        #set_browser_langs()
        set_host_lang()
        set_content_type()
        set_iface_lang()
        set_content_lang()
        set_recent_reddits()
        set_recent_clicks()
        # used for HTML-lite templates
        set_colors()

        # set some environmental variables in case we hit an abort
        if not isinstance(c.site, FakeSubreddit):
            request.environ['REDDIT_NAME'] = c.site.name

        # random reddit trickery -- have to do this after the content lang is set
        if c.site == Random:
            c.site = Subreddit.random_reddit()
            redirect_to("/" + c.site.path.strip('/') + request.path)
        elif c.site == RandomNSFW:
            c.site = Subreddit.random_reddit(over18=True)
            redirect_to("/" + c.site.path.strip('/') + request.path)

        # check that the site is available:
        if c.site._spam and not c.user_is_admin and not c.error_page:
            abort(404, "not found")

        # check if the user has access to this subreddit
        if not c.site.can_view(c.user) and not c.error_page:
            abort(403, "forbidden")

        #check over 18
        if (c.site.over_18 and not c.over18
                and request.path not in ("/frame", "/over18")
                and c.render_style == 'html'):
            return self.intermediate_redirect("/over18")

        #check whether to allow custom styles
        c.allow_styles = self.allow_stylesheets
        if g.css_killswitch:
            c.allow_styles = False
        #if the preference is set and we're not at a cname
        elif not c.user.pref_show_stylesheets and not c.cname:
            c.allow_styles = False
        #if the site has a cname, but we're not using it
        elif c.site.domain and c.site.css_on_cname and not c.cname:
            c.allow_styles = False
Ejemplo n.º 46
0
 def index(self):
     return redirect_to(controller='proposal', action="index", id=None)
Ejemplo n.º 47
0
    def GET_mobile_badge(self, meetup):
        if meetup.state not in BADGE_STATES:
            return redirect_to("/meetup/%s" % str(meetup._id))

        content = pages.MobileQrCodeBadge(meetup, c.user)
        return content.render()
Ejemplo n.º 48
0
    def pre(self):
        c.response_wrappers = []
        MinimalController.pre(self)

        set_cnameframe()

        # populate c.cookies unless we're on the unsafe media_domain
        if request.host != g.media_domain or g.media_domain == g.domain:
            try:
                for k, v in request.cookies.iteritems():
                    # minimalcontroller can still set cookies
                    if k not in c.cookies:
                        # we can unquote even if it's not quoted
                        c.cookies[k] = Cookie(value=unquote(v), dirty=False)
            except CookieError:
                #pylons or one of the associated retarded libraries
                #can't handle broken cookies
                request.environ['HTTP_COOKIE'] = ''

        c.firsttime = firsttime()

        # the user could have been logged in via one of the feeds
        maybe_admin = False

        # no logins for RSS feed unless valid_feed has already been called
        if not c.user:
            if c.extension != "rss":
                session_cookie = c.cookies.get(g.login_cookie)
                if session_cookie:
                    c.user = valid_cookie(session_cookie.value)
                    if c.user:
                        c.user_is_loggedin = True

                admin_cookie = c.cookies.get(g.admin_cookie)
                if c.user_is_loggedin and admin_cookie:
                    maybe_admin, first_login = valid_admin_cookie(
                        admin_cookie.value)

                    if maybe_admin:
                        self.enable_admin_mode(c.user, first_login=first_login)
                    else:
                        self.disable_admin_mode(c.user)

            if not c.user:
                c.user = UnloggedUser(get_browser_langs())
                # patch for fixing mangled language preferences
                if (not isinstance(c.user.pref_lang, basestring) or not all(
                        isinstance(x, basestring)
                        for x in c.user.pref_content_langs)):
                    c.user.pref_lang = g.lang
                    c.user.pref_content_langs = [g.lang]
                    c.user._commit()
        if c.user_is_loggedin:
            if not c.user._loaded:
                c.user._load()
            c.modhash = c.user.modhash()
            if request.method.upper() == 'GET':
                read_mod_cookie()
            if hasattr(c.user, 'msgtime') and c.user.msgtime:
                c.have_messages = c.user.msgtime
            c.show_mod_mail = Subreddit.reverse_moderator_ids(c.user)
            c.have_mod_messages = getattr(c.user, "modmsgtime", False)
            c.user_is_admin = maybe_admin and c.user.name in g.admins
            c.user_special_distinguish = c.user.special_distinguish()
            c.user_is_sponsor = c.user_is_admin or c.user.name in g.sponsors
            if request.path != '/validuser' and not g.disallow_db_writes:
                c.user.update_last_visit(c.start_time)

        c.over18 = over18()

        #set_browser_langs()
        set_host_lang()
        set_iface_lang()
        set_content_lang()
        set_recent_clicks()
        # used for HTML-lite templates
        set_colors()

        # set some environmental variables in case we hit an abort
        if not isinstance(c.site, FakeSubreddit):
            request.environ['REDDIT_NAME'] = c.site.name

        # random reddit trickery -- have to do this after the content lang is set
        if c.site == Random:
            c.site = Subreddit.random_reddit()
            redirect_to("/" + c.site.path.strip('/') + request.path)
        elif c.site == RandomNSFW:
            c.site = Subreddit.random_reddit(over18=True)
            redirect_to("/" + c.site.path.strip('/') + request.path)

        if not request.path.startswith("/api/login/"):
            # is the subreddit banned?
            if c.site.spammy() and not c.user_is_admin and not c.error_page:
                ban_info = getattr(c.site, "ban_info", {})
                if "message" in ban_info:
                    message = ban_info['message']
                else:
                    sitelink = url_escape(add_sr("/"))
                    subject = ("/r/%s has been incorrectly banned" %
                               c.site.name)
                    link = ("/r/redditrequest/submit?url=%s&title=%s" %
                            (sitelink, subject))
                    message = strings.banned_subreddit_message % dict(
                        link=link)
                errpage = pages.RedditError(strings.banned_subreddit_title,
                                            message,
                                            image="subreddit-banned.png")
                request.environ['usable_error_content'] = errpage.render()
                self.abort404()

            # check if the user has access to this subreddit
            if not c.site.can_view(c.user) and not c.error_page:
                errpage = pages.RedditError(strings.private_subreddit_title,
                                            strings.private_subreddit_message,
                                            image="subreddit-private.png")
                request.environ['usable_error_content'] = errpage.render()
                self.abort403()

            #check over 18
            if (c.site.over_18 and not c.over18
                    and request.path not in ("/frame", "/over18")
                    and c.render_style == 'html'):
                return self.intermediate_redirect("/over18")

        #check whether to allow custom styles
        c.allow_styles = self.allow_stylesheets
        if g.css_killswitch:
            c.allow_styles = False
        #if the preference is set and we're not at a cname
        elif not c.user.pref_show_stylesheets and not c.cname:
            c.allow_styles = False
        #if the site has a cname, but we're not using it
        elif c.site.domain and c.site.css_on_cname and not c.cname:
            c.allow_styles = False
Ejemplo n.º 49
0
    def GET_configure_badge(self, meetup):
        if meetup.state not in BADGE_STATES:
            return redirect_to("/meetup/%s" % str(meetup._id))

        content = pages.ConversationStarterSelector(meetup, c.user)
        return pages.MeatspacePage(content=content).render()