예제 #1
0
파일: person.py 프로젝트: iseppi/zookeepr
    def validate_python(self, values, state):
        assertion = values['assertion']
        audience = h.url_for(qualified=True, controller='home').strip("/")

        page = urllib2.urlopen('https://verifier.login.persona.org/verify',
                               urllib.urlencode({ "assertion": assertion,
                                                  "audience": audience}))
        data = json.load(page)
        if data['status'] == 'okay':
            c.email = data['email']
            c.person = Person.find_by_email(c.email)

        if c.person is None:
            if not Config.get('account_creation'):
                error_message = "Your sign-in details are incorrect; try the 'Forgotten your password' link below."
                message = "Login failed"
                error_dict = {'email_address': error_message}
                raise Invalid(message, values, state, error_dict=error_dict)

            # Create a new account for this email address
            c.person = Person()
            c.person.email_address = data['email']
            c.person.activated = True
            meta.Session.add(c.person)
            meta.Session.commit()

        if not c.person.activated:
            # Persona returns verified emails only, so might as well confirm this one...
            c.person.activated = True
            meta.Session.commit()
예제 #2
0
    def test_create_duplicate_person(self):
        Dummy_smtplib.install()
        
        # create a fake user
        p = Person(email_address='*****@*****.**')
        p.activated = True
        self.dbsession.save(p)
        self.dbsession.flush()
        pid = p.id

        resp = self.app.get('/person/new')
        f = resp.form
        f['person.email_address'] = '*****@*****.**'
        f['person.firstname'] = 'Testguy'
        f['person.lastname'] = 'McTest'
        f['person.password'] = '******'
        f['person.password_confirm'] = 'test'
        f['person.phone'] = '1234'
        f['person.mobile'] = '1234'
        f['person.address1'] = 'Moo St'
        f['person.city'] = 'Tassie'
        f['person.country'] = 'Australia'
        f['person.postcode'] = '2000'
        resp = f.submit()

        resp.mustcontain('A person with this email already exists.')

        resp.click('recover your password')

        self.dbsession.delete(self.dbsession.query(Person).get(pid))
        self.dbsession.flush()
예제 #3
0
    def test_duplicate_password_reset(self):
        """Try to reset a password twice.
        """
        c = Person(email_address='*****@*****.**')
        self.dbsession.save(c)
        self.dbsession.flush()
        cid = c.id

        #
        email = '*****@*****.**'

        # trap smtp
        Dummy_smtplib.install()

        resp = self.app.get(url_for(controller='person',
                                    action='signin'))
        resp = resp.click('Forgotten your password?')
        f = resp.forms[0]
        f['email_address'] = email
        f.submit()

        crec = self.dbsession.query(PasswordResetConfirmation).filter_by(email_address=email).one()
        self.failIfEqual(None, crec)
        crecid = crec.id

        # submit a second time
        resp = f.submit()

        resp.mustcontain("password recovery process is already in progress")

        # clean up
        Dummy_smtplib.existing.reset()
        self.dbsession.delete(self.dbsession.query(PasswordResetConfirmation).get(crecid))
        self.dbsession.delete(self.dbsession.query(Person).get(cid))
        self.dbsession.flush()
예제 #4
0
def signed_in_person():
    email_address = request.environ.get("REMOTE_USER")
    if email_address is None:
        return None

    person = Person.find_by_email(email_address, True)
    return person
예제 #5
0
def signed_in_person():
    email_address = request.environ.get("REMOTE_USER")
    if email_address is None:
        return None

    person = Person.find_by_email(email_address, True)
    return person
예제 #6
0
파일: person.py 프로젝트: jhesketh/zookeepr
    def offer(self, id):
        # We need to recheck auth in here so we can pass in the id
        if not h.auth.authorized(
                h.auth.Or(h.auth.is_same_zkpylons_user(id),
                          h.auth.has_reviewer_role,
                          h.auth.has_organiser_role)):
            # Raise a no_auth error
            h.auth.no_role()
        c.person = Person.find_by_id(id)
        c.offers = c.person.proposal_offers
        c.travel_assistance = reduce(
            lambda a, b: a or
            ('Travel' in b.status.name), c.offers, False) or False
        c.accommodation_assistance = reduce(
            lambda a, b: a or
            ('Accommodation' in b.status.name), c.offers, False) or False

        # Set initial form defaults
        defaults = {
            'status': 'accept',
        }
        if c.person.travel:
            defaults.update(h.object_to_defaults(c.person.travel, 'travel'))

        form = render('person/offer.mako')
        return htmlfill.render(form, defaults)
예제 #7
0
파일: person.py 프로젝트: iseppi/zookeepr
    def _new(self):
        # Do we allow account creation?
        if Config.get('account_creation'):
            """Create a new person submit.
            """

            # Remove fields not in class
            results = self.form_result['person']
            del results['password_confirm']
            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 Config.get('confirm_email_address', category='rego') == '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')
                return self.finish_login(c.person.email_address)
        else:
            return render('/not_allowed.mako')
예제 #8
0
파일: auth.py 프로젝트: tmfox/zookeepr
    def check(self, app, environ, start_response):

        if not environ.get('REMOTE_USER'):
            raise NotAuthenticatedError('Not Authenticated')

        person = Person.find_by_email(environ['REMOTE_USER'])
        if person is None:
            environ['auth_failure'] = 'NO_USER'
            raise NotAuthorizedError(
                'You are not one of the users allowed to access this resource.'
            )

        funding = Funding.find_by_id(self.funding_id)
        if funding is None:
            raise NotAuthorizedError(
                "Funding Request doesn't exist"
            )

        if person != funding.person:
            set_role("User doesn't have any of the specified roles")
            raise NotAuthorizedError(
                "User doesn't have any of the specified roles"
            )

        return app(environ, start_response)
예제 #9
0
파일: auth.py 프로젝트: tmfox/zookeepr
    def check(self, app, environ, start_response):

        if not environ.get('REMOTE_USER'):
            set_redirect()
            raise NotAuthenticatedError('Not Authenticated')

        person = Person.find_by_email(environ['REMOTE_USER'])
        if person is None:
            environ['auth_failure'] = 'NO_USER'
            raise NotAuthorizedError(
                'You are not one of the users allowed to access this resource.'
            )

        proposal = Proposal.find_by_id(self.proposal_id)
        if proposal is None:
            raise NotAuthorizedError(
                "Proposal doesn't exist"
            )

        if person not in proposal.people:
            set_role("User doesn't have any of the specified roles")
            raise NotAuthorizedError(
                "User doesn't have any of the specified roles"
            )

        return app(environ, start_response)
예제 #10
0
파일: auth.py 프로젝트: tmfox/zookeepr
    def check(self, app, environ, start_response):

        if not environ.get('REMOTE_USER'):
            set_redirect()
            raise NotAuthenticatedError('Not Authenticated')

        person = Person.find_by_email(environ['REMOTE_USER'])
        if person is None:
            environ['auth_failure'] = 'NO_USER'
            raise NotAuthorizedError(
                'You are not one of the users allowed to access this resource.'
            )

        registration = Registration.find_by_id(self.registration_id)
        if registration is None:
            raise NotAuthorizedError(
                "Registration doesn't exist"
            )

        if person.id <> registration.person_id:
            set_role("Registration is not for this user");
            raise NotAuthorizedError(
                "Registration is not for this user"
            )

        return app(environ, start_response)
예제 #11
0
파일: person.py 프로젝트: iseppi/zookeepr
    def _forgotten_password(self):
        """Action to let the user request a password change.

        GET returns a form for emailing them the password change
        confirmation.

        POST checks the form and then creates a confirmation record:
        date, email_address, and a url_hash that is a hash of a
        combination of date, email_address, and a random nonce.

        The email address must exist in the person database.

        The second half of the password change operation happens in
        the ``confirm`` action.
        """
        c.email = self.form_result['email_address']
        c.person = Person.find_by_email(c.email)

        if c.person is not None:
            # Check if there is already a password recovery in progress
            reset = PasswordResetConfirmation.find_by_email(c.email)
            if reset is not None:
                return render('person/in_progress.mako')

            # Ok kick one off
            c.conf_rec = PasswordResetConfirmation(email_address=c.email)
            meta.Session.add(c.conf_rec)
            meta.Session.commit()

        email(c.email, render('person/confirmation_email.mako'))

        return render('person/password_confirmation_sent.mako')
예제 #12
0
파일: person.py 프로젝트: iseppi/zookeepr
 def _new_incomplete(self):
     results = self.form_result['person']
     c.person = Person(**results)
     c.person.email_address = c.person.email_address.lower()
     meta.Session.add(c.person)
     meta.Session.commit()
     redirect_to(controller='person', action='index')
예제 #13
0
    def test_registration_confirmation(self):
        # insert registration model object
        timestamp = datetime.datetime.now()
        email_address = '*****@*****.**'
        password = '******'
	handle = 'testguy'
        r = Person(creation_timestamp=timestamp,
                   email_address=email_address,
                   password=password,
		   handle=handle,
                   activated=False)
        url_hash = r.url_hash
        print url_hash
        self.dbsession.save(r)
        self.dbsession.flush()
        rid = r.id
        print r
        # clear so that we reload the object later
        self.dbsession.clear()
        
        # visit the link
        response = self.app.get('/person/confirm/' + url_hash)
        response.mustcontain('Thanks for confirming your account')
        
        # test that it's activated
        r = self.dbsession.get(Person,rid)
        self.assertEqual(True, r.activated, "registration was not activated")

        # clean up
        self.dbsession.delete(self.dbsession.query(Person).get(rid))
        self.dbsession.flush()
예제 #14
0
 def validate_python(self, values, state):
     person = Person.find_by_email(values['email_address'])
     if person is not None:
         msg = "A person with this email already exists. Please try signing in first."
         raise Invalid(msg,
                       values,
                       state,
                       error_dict={'email_address': msg})
예제 #15
0
    def index(self):
        c.DAYS_OPEN = DAYS_OPEN
        c.open_date = lca_info.lca_info['date']
        days_open = (datetime.date.today() - c.open_date.date()).days
        photo_db = PhotoCompEntry.read_db()
        photos = [
            photo for days in photo_db.values() for entries in days
            for photo in entries if photo is not None and photo.day < days_open
        ]
        c.no_photos = not photos
        day_filter = request.GET.get('day', 'All')
        if day_filter and day_filter != 'All':
            photos = [p for p in photos if str(p.day) == day_filter]
        person_filter = request.GET.get('person', 'All')
        if person_filter and person_filter != 'All':
            photos = [p for p in photos if str(p.person_id) == person_filter]
        submitted = request.GET.get('s', None)
        randomise = not submitted or 'randomise' in request.GET
        if randomise:
            random.shuffle(photos)
        else:
            photos.sort(key=lambda p: (p.day, p.person_id, p.entry_id))
        person_map = {}
        for photo in photos:
            photo.write_scaled()
            person_map[photo.person_id] = None
        c.all_person = []
        for person_id in person_map:
            person = Person.find_by_id(person_id)
            person_map[person_id] = person
            c.all_person.append(person)
        c.all_person.sort(key=lambda person:
                          (person.firstname + " " + person.lastname).lower())
        c.photos = photos

        def photo_title(photo):
            return "%s %s, %s entry %s, %s" % (
                person_map[photo.person_id].firstname,
                person_map[photo.person_id].lastname,
                (c.open_date + datetime.timedelta(photo.day)).strftime('%A'),
                ENTRY_NAMES[photo.entry_id],
                photo.image_name,
            )

        c.photo_title = photo_title
        field_values = {
            'day': day_filter,
            'person': person_filter,
        }
        if randomise:
            field_values['randomise'] = '1'
        if submitted == 'Full Screen' and photos:
            html = render('/photocomp/index-fullscreen.mako')
        else:
            html = render('/photocomp/index.mako')
        return htmlfill.render(html, field_values)
예제 #16
0
파일: person.py 프로젝트: iseppi/zookeepr
    def view(self, id):
        # We need to recheck auth in here so we can pass in the id
        if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_user(id), h.auth.has_reviewer_role, h.auth.has_organiser_role)):
            # Raise a no_auth error
            h.auth.no_role()

        c.registration_status = h.config['app_conf'].get('registration_status')
        c.person = Person.find_by_id(id)

        return render('person/view.mako')
예제 #17
0
파일: auth.py 프로젝트: tmfox/zookeepr
    def user_exists(self, username):
        """
        Returns ``True`` if the user exists, ``False`` otherwise. Users are
        case insensitive.
        """

        person = Person.find_by_email(username)

        if person is not None:
            return True
        return False
예제 #18
0
파일: person.py 프로젝트: iseppi/zookeepr
    def _edit(self, id):
        """UPDATE PERSON"""
        # We need to recheck auth in here so we can pass in the id
        if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_user(id), h.auth.has_organiser_role)):
            # Raise a no_auth error
            h.auth.no_role()

        c.person = Person.find_by_id(id)
        self.finish_edit(c.person)

        redirect_to(action='view', id=id)
예제 #19
0
파일: person.py 프로젝트: iseppi/zookeepr
 def validate_python(self, values, state):
     c.email = values['email_address']
     c.person = Person.find_by_email(c.email)
     error_message = None
     if c.person is None or not c.person.check_password(values['password']):
         error_message = ("Your sign-in details are incorrect; try the"
                          " 'Forgotten your password' link below or sign up"
                          " for a new person.")
         message = "Login failed"
         error_dict = {'email_address': error_message}
         raise Invalid(message, values, state, error_dict=error_dict)
예제 #20
0
    def index(self):
        c.DAYS_OPEN = DAYS_OPEN
        c.open_date =  lca_info.lca_info['date']
        days_open = (datetime.date.today() - c.open_date.date()).days
        photo_db = PhotoCompEntry.read_db()
        photos = [
            photo
            for days in photo_db.values()
            for entries in days
            for photo in entries
            if photo is not None and photo.day < days_open]
        c.no_photos = not photos
        day_filter = request.GET.get('day', 'All')
        if day_filter and day_filter != 'All':
            photos = [p for p in photos if str(p.day) == day_filter]
        person_filter = request.GET.get('person', 'All')
        if person_filter and person_filter != 'All':
            photos = [p for p in photos if str(p.person_id) == person_filter]
        submitted = request.GET.get('s', None)
        randomise = not submitted or 'randomise' in request.GET
        if randomise:
            random.shuffle(photos)
        else:
            photos.sort(key=lambda p: (p.day, p.person_id, p.entry_id))
        person_map = {}
        for photo in photos:
            photo.write_scaled()
            person_map[photo.person_id] = None
        c.all_person = []
        for person_id in person_map:
            person = Person.find_by_id(person_id)
            person_map[person_id] = person
            c.all_person.append(person)
        c.all_person.sort(key=lambda person: (person.firstname + " " + person.lastname).lower())
        c.photos = photos
        def photo_title(photo):
            return "%s %s, %s entry %s, %s" % (
                person_map[photo.person_id].firstname,
                person_map[photo.person_id].lastname,
                (c.open_date + datetime.timedelta(photo.day)).strftime('%A'),
                ENTRY_NAMES[photo.entry_id],
                photo.image_name,)
        c.photo_title = photo_title
        field_values = {
            'day':      day_filter,
            'person':   person_filter,
        }
        if randomise:
            field_values['randomise'] = '1'
	if submitted == 'Full Screen' and photos:
            html = render('/photocomp/index-fullscreen.mako')
        else:
            html = render('/photocomp/index.mako')
        return htmlfill.render(html, field_values)
예제 #21
0
파일: person.py 프로젝트: iseppi/zookeepr
    def roles(self, id):

        c.person = Person.find_by_id(id)
        c.roles = Role.find_all()
        if not c.person.activated:
            h.flash(
                "NOTICE: This user hasn't confirmed their email address yet."
                " Please get them to visit"
                " %s" % h.full_url_for('person/activate'),
                category='warning')
        return render('person/roles.mako')
예제 #22
0
파일: person.py 프로젝트: jhesketh/zookeepr
    def _offer(self, id):
        # We need to recheck auth in here so we can pass in the id
        if not h.auth.authorized(
                h.auth.Or(h.auth.is_same_zkpylons_user(id),
                          h.auth.has_reviewer_role,
                          h.auth.has_organiser_role)):
            # Raise a no_auth error
            h.auth.no_role()
        c.person = Person.find_by_id(id)
        c.offers = c.person.proposal_offers
        c.travel_assistance = reduce(
            lambda a, b: a or
            ('Travel' in b.status.name), c.offers, False) or False
        c.accommodation_assistance = reduce(
            lambda a, b: a or
            ('Accommodation' in b.status.name), c.offers, False) or False

        # What status are we moving all proposals to?
        if self.form_result['status'] == 'accept':
            c.status = ProposalStatus.find_by_name('Accepted')
        elif self.form_result['status'] == 'withdraw':
            c.status = ProposalStatus.find_by_name('Withdrawn')
        elif self.form_result['status'] == 'contact':
            c.status = ProposalStatus.find_by_name('Contact')
        else:
            c.status = None

        emails = [c.person.email_address]
        for offer in c.offers:
            offer.status = c.status
            if offer.type.notify_email and offer.type.notify_email not in emails:
                emails.append(offer.type.notify_email)

        if c.travel_assistance:
            if not c.person.travel:
                self.form_result['travel']['flight_details'] = ''
                travel = Travel(**self.form_result['travel'])
                meta.Session.add(travel)
                c.person.travel = travel
            else:
                for key in self.form_result['travel']:
                    setattr(c.person.travel, key,
                            self.form_result['travel'][key])

        if c.status.name == 'Accepted':
            email(c.person.email_address, render('/person/offer_email.mako'))
        else:
            email(emails, render('/person/offer_email.mako'))

        # update the objects with the validated form data
        meta.Session.commit()
        return render('person/offer.mako')
예제 #23
0
    def check(self, app, environ, start_response):
        """
        Should return True if the user has the role or
        False if the user doesn't exist or doesn't have the role.

        In this implementation role names are case insensitive.
        """

        if not environ.get('REMOTE_USER'):
            if self.error:
                raise self.error
            set_redirect()
            raise NotAuthenticatedError('Not authenticated')

        for role in self.roles:
           if not self.role_exists(role):
               raise NotAuthorizedError("No such role %r exists"%role)

        person = Person.find_by_email(environ['REMOTE_USER'])
        if person is None:
            raise users.AuthKitNoSuchUserError(
                "No such user %r" % environ['REMOTE_USER'])

        if not person.activated:
            #set_role('User account must be activated')
            raise NotAuthorizedError(
                    "User account must be activated"
                )

        if self.all:
            for role in self.roles:
                if not self.user_has_role(person, role):
                    if self.error:
                        raise self.error
                    else:
                        set_role("User doesn't have the role %s"%role.lower())
                        raise NotAuthorizedError(
                            "User doesn't have the role %s"%role.lower()
                        )
            return app(environ, start_response)
        else:
            for role in self.roles:
                if self.user_has_role(person, role):
                    return app(environ, start_response)
            if self.error:
                raise self.error
            else:
                set_role("User doesn't have any of the specified roles")
                raise NotAuthorizedError(
                    "User doesn't have any of the specified roles"
                )
예제 #24
0
파일: person.py 프로젝트: biancaG/zookeepr
 def validate_python(self, values, state):
     c.email = values['email_address']
     c.person = Person.find_by_email(c.email)
     error_message = None
     if c.person is None:
         error_message = "Your sign-in details are incorrect; try the 'Forgotten your password' link below or sign up for a new person."
     elif not c.person.activated:
         error_message = "You haven't yet confirmed your registration, please refer to your email for instructions on how to do so."
     elif not c.person.check_password(values['password']):
         error_message = "Your sign-in details are incorrect; try the 'Forgotten your password' link below or sign up for a new person."
     if error_message:
         message = "Login failed"
         error_dict = {'email_address': error_message}
         raise Invalid(message, values, state, error_dict=error_dict)
예제 #25
0
파일: person.py 프로젝트: tmfox/zookeepr
 def validate_python(self, values, state):
     c.email = values['email_address']
     c.person = Person.find_by_email(c.email)
     error_message = None
     if c.person is None:
         error_message = "Your sign-in details are incorrect; try the 'Forgotten your password' link below or sign up for a new person."
     elif not c.person.activated:
         error_message = "You haven't yet confirmed your registration, please refer to your email for instructions on how to do so."
     elif not c.person.check_password(values['password']):
         error_message = "Your sign-in details are incorrect; try the 'Forgotten your password' link below or sign up for a new person."
     if error_message:
         message = "Login failed"
         error_dict = {'email_address': error_message}
         raise Invalid(message, values, state, error_dict=error_dict)
예제 #26
0
파일: auth.py 프로젝트: Ivoz/zookeepr
    def check(self, app, environ, start_response):

        if not environ.get('REMOTE_USER'):
            set_redirect()
            raise NotAuthenticatedError('Not Authenticated')

        person = Person.find_by_email(environ['REMOTE_USER'])
        if Person is None:
            environ['auth_failure'] = 'NO_USER'
            raise NotAuthorizedError(
                'You are not one of the users allowed to access this resource.'
            )

        return app(environ, start_response)
예제 #27
0
파일: auth.py 프로젝트: noisymime/zookeepr
    def check(self, app, environ, start_response):

        if not environ.get('REMOTE_USER'):
            set_redirect()
            raise NotAuthenticatedError('Not Authenticated')

        person = Person.find_by_email(environ['REMOTE_USER'])
        if Person is None:
            environ['auth_failure'] = 'NO_USER'
            raise NotAuthorizedError(
                'You are not one of the users allowed to access this resource.'
            )

        return app(environ, start_response)
예제 #28
0
파일: person.py 프로젝트: iseppi/zookeepr
    def _reset_password(self, url_hash):
        """Confirm a password change request, and let the user change
        their password.

        `url_hash` is a hash of the email address, with which we can
        look up the confuirmation record in the database.

        If `url_hash` doesn't exist, 404.

        If `url_hash` exists and the date is older than 24 hours,
        warn the user, offer to send a new confirmation, and delete the
        confirmation record.

        GET returns a form for setting their password, with their email
        address already shown.

        POST checks that the email address (in the session, not in the
        form) is part of a valid person record (again).  If the record
        exists, then update the password, hashed.  Report success to the
        user.  Delete the confirmation record.

        If the record doesn't exist, throw an error, delete the
        confirmation record.
        """
        c.conf_rec = PasswordResetConfirmation.find_by_url_hash(url_hash)

        now = datetime.datetime.now(c.conf_rec.timestamp.tzinfo)
        delta = now - c.conf_rec.timestamp
        if delta > datetime.timedelta(hours=24):
            # this confirmation record has expired
            meta.Session.delete(c.conf_rec)
            meta.Session.commit()
            return render('person/expired.mako')

        c.person = Person.find_by_email(c.conf_rec.email_address)
        if c.person is None:
            raise RuntimeError, "Person doesn't exist %s" % c.conf_rec.email_address

        # set the password
        c.person.password = self.form_result['password']
        # also make sure the person is activated
        c.person.activated = True

        # delete the conf rec
        meta.Session.delete(c.conf_rec)
        meta.Session.commit()

        h.flash('Your password has been updated!')
        self.finish_login(c.person.email_address)
예제 #29
0
파일: auth.py 프로젝트: noisymime/zookeepr
    def check(self, app, environ, start_response):
        """
        Should return True if the user has the role or
        False if the user doesn't exist or doesn't have the role.

        In this implementation role names are case insensitive.
        """

        if not environ.get('REMOTE_USER'):
            if self.error:
                raise self.error
            set_redirect()
            raise NotAuthenticatedError('Not authenticated')

        for role in self.roles:
            if not self.role_exists(role):
                raise Exception("No such role %r exists" % role)

        person = Person.find_by_email(environ['REMOTE_USER'])
        if person is None:
            raise users.AuthKitNoSuchUserError("No such user %r" %
                                               environ['REMOTE_USER'])

        if not person.activated:
            #set_role('User account must be activated')
            raise NotAuthorizedError("User account must be activated")

        if self.all:
            for role in self.roles:
                if not self.user_has_role(person, role):
                    if self.error:
                        raise self.error
                    else:
                        set_role("User doesn't have the role %s" %
                                 role.lower())
                        raise NotAuthorizedError(
                            "User doesn't have the role %s" % role.lower())
            return app(environ, start_response)
        else:
            for role in self.roles:
                if self.user_has_role(person, role):
                    return app(environ, start_response)
            if self.error:
                raise self.error
            else:
                set_role("User doesn't have any of the specified roles")
                raise NotAuthorizedError(
                    "User doesn't have any of the specified roles")
예제 #30
0
파일: person.py 프로젝트: iseppi/zookeepr
    def edit(self, id):
        # We need to recheck auth in here so we can pass in the id
        if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_user(id), h.auth.has_organiser_role)):
            # Raise a no_auth error
            h.auth.no_role()
        c.form = 'edit'
        c.person = Person.find_by_id(id)
        c.social_networks = SocialNetwork.find_all()
        c.person.fetch_social_networks()

        defaults = h.object_to_defaults(c.person, 'person')
        if not defaults['person.country']:
            defaults['person.country'] = 'AUSTRALIA'

        form = render('/person/edit.mako')
        return htmlfill.render(form, defaults)
예제 #31
0
파일: person.py 프로젝트: iseppi/zookeepr
    def confirm(self, confirm_hash):
        """Confirm a registration with the given ID.

        `confirm_hash` is a md5 hash of the email address of the registrant, the time
        they regsitered, and a nonce.

        """
        person = Person.find_by_url_hash(confirm_hash)

        if person.activated:
            return render('person/already_confirmed.mako')

        person.activated = True

        meta.Session.commit()

        return render('person/confirmed.mako')
예제 #32
0
파일: auth.py 프로젝트: tmfox/zookeepr
    def user_has_role(self, username, role):
        """
        Returns ``True`` if the user has the role specified, ``False``
        otherwise. Raises an exception if the user doesn't exist.
        """
        if not self.user_exists(username.lower()):
            raise users.AuthKitNoSuchUserError("No such user %r"%username.lower())
        if not self.role_exists(role.lower()):
            raise users.AuthKitNoSuchRoleError("No such role %r"%role.lower())
        person = Person.find_by_email(username)
        if person is None:
            return False

        for role_ in person.roles:
            if role_.name == role.lower():
                return True
        return False
예제 #33
0
파일: person.py 프로젝트: iseppi/zookeepr
    def _offer(self,id):
        # We need to recheck auth in here so we can pass in the id
        if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_user(id), h.auth.has_reviewer_role, h.auth.has_organiser_role)):
            # Raise a no_auth error
            h.auth.no_role()
        c.person = Person.find_by_id(id)
        c.offers = c.person.proposal_offers
        c.travel_assistance = reduce(lambda a, b: a or ('Travel' in b.status.name), c.offers, False) or False
        c.accommodation_assistance = reduce(lambda a, b: a or ('Accommodation' in b.status.name), c.offers, False) or False

        # What status are we moving all proposals to?
        if self.form_result['status'] == 'accept':
            c.status = ProposalStatus.find_by_name('Accepted')
        elif self.form_result['status'] == 'withdraw':
            c.status = ProposalStatus.find_by_name('Withdrawn')
        elif self.form_result['status'] == 'contact':
            c.status = ProposalStatus.find_by_name('Contact')
        else:
            c.status = None

        emails = [c.person.email_address]
        for offer in c.offers:
            offer.status = c.status
            if offer.type.notify_email and offer.type.notify_email not in emails:
                emails.append(offer.type.notify_email)

        if c.travel_assistance:
            if not c.person.travel:
                self.form_result['travel']['flight_details'] = ''
                travel = Travel(**self.form_result['travel'])
                meta.Session.add(travel)
                c.person.travel = travel
            else:
                for key in self.form_result['travel']:
                    setattr(c.person.travel, key, self.form_result['travel'][key])

        if c.status.name == 'Accepted':
            email(c.person.email_address, render('/person/offer_email.mako'))
        else:
            email(emails, render('/person/offer_email.mako'))

        # update the objects with the validated form data
        meta.Session.commit()
        return render('person/offer.mako')
예제 #34
0
    def test_confirm(self):
        """Test confirmation of a password reset that should succeed"""

        # create a confirmation record
        email = '*****@*****.**'
        p = Person(email_address=email)
        self.dbsession.save(p)
        c = PasswordResetConfirmation(email_address=email)
        # set the timestamp to just under 24 hours ago
        c.timestamp = datetime.datetime.now() - datetime.timedelta(23, 59, 59)
        self.dbsession.save(c)
        self.dbsession.flush()
        pid = p.id
        cid = c.id

        resp = self.app.get(url_for(controller='person',
            action='reset_password',
            url_hash=c.url_hash))

        # showing the email on the page
        resp.mustcontain(email)

        f = resp.form
        f['password'] = '******'
        f['password_confirm'] = 'test'
        resp = f.submit()

        # check for success
        resp.mustcontain("Your password has been updated")

        self.dbsession.clear()

        # conf rec should be gone
        c = self.dbsession.get(PasswordResetConfirmation, cid)
        self.assertEqual(None, c)

        # password should be set to 'test'
        p_hash = md5.new('test').hexdigest()
        p = self.dbsession.get(Person, pid)
        self.assertEqual(p_hash, p.password_hash)

        self.dbsession.delete(p)
        self.dbsession.flush()
예제 #35
0
파일: person.py 프로젝트: iseppi/zookeepr
    def offer(self, id):
        # We need to recheck auth in here so we can pass in the id
        if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_user(id), h.auth.has_reviewer_role, h.auth.has_organiser_role)):
            # Raise a no_auth error
            h.auth.no_role()
        c.person = Person.find_by_id(id)
        c.offers = c.person.proposal_offers
        c.travel_assistance = reduce(lambda a, b: a or ('Travel' in b.status.name), c.offers, False) or False
        c.accommodation_assistance = reduce(lambda a, b: a or ('Accommodation' in b.status.name), c.offers, False) or False

        # Set initial form defaults
        defaults = {
            'status': 'accept',
            }
        if c.person.travel:
            defaults.update(h.object_to_defaults(c.person.travel, 'travel'))

        form = render('person/offer.mako')
        return htmlfill.render(form, defaults)
예제 #36
0
파일: auth.py 프로젝트: noisymime/zookeepr
    def check(self, app, environ, start_response):
        if not environ.get('REMOTE_USER'):
            set_redirect()
            raise NotAuthenticatedError('Not Authenticated')

        person = Person.find_by_email(environ['REMOTE_USER'])
        if person is None:
            set_redirect()
            environ['auth_failure'] = 'NO_USER'
            raise NotAuthorizedError(
                'You are not one of the users allowed to access this resource.'
            )

        if not person.activated:
            set_redirect()
            if 'is_active' in dir(meta.Session):
                meta.Session.flush()
                meta.Session.close()

            redirect(url(controller="person", action="activate"))

        return app(environ, start_response)
예제 #37
0
    def check(self, app, environ, start_response):
        if not environ.get('REMOTE_USER'):
            set_redirect()
            raise NotAuthenticatedError('Not Authenticated')

        person = Person.find_by_email(environ['REMOTE_USER'])
        if person is None:
            set_redirect()
            environ['auth_failure'] = 'NO_USER'
            raise NotAuthorizedError(
                'You are not one of the users allowed to access this resource.'
            )

        if not person.activated:
            set_redirect()
            if 'is_active' in dir(meta.Session):
                meta.Session.flush()
                meta.Session.close()

            redirect(url(controller="person", action="activate"))

        return app(environ, start_response)
예제 #38
0
파일: person.py 프로젝트: iseppi/zookeepr
    def _roles(self, id):
        """ Lists and changes the person's roles. """

        c.person = Person.find_by_id(id)
        c.roles = Role.find_all()

        role = self.form_result['role']
        action = self.form_result['action']

        role = Role.find_by_name(name=role)

        if action == 'Revoke' and role in c.person.roles:
            c.person.roles.remove(role)
            h.flash('Role ' + role.name + ' Revoked')
        elif action == 'Grant' and role not in c.person.roles:
            c.person.roles.append(role)
            h.flash('Role ' + role.name + ' Granted')
        else:
            h.flash("Nothing to do")

        meta.Session.commit()

        return render('person/roles.mako')
예제 #39
0
 def validate_python(self, values, state):
     person = Person.find_by_email(values['email_address'])
     if person is not None:
         msg = "A person with this email already exists. Please try signing in first."
         raise Invalid(msg, values, state, error_dict={'email_address': msg})
예제 #40
0
 def _to_python(self, value, state):
     person = Person.find_by_id(int(value), abort_404=False)
     if person is None:
         raise Invalid("Unknown person ID.", value, state)
     else:
         return person
예제 #41
0
 def validate_python(self, value, state):
     person = Person.find_by_email(value)
     if person is None:
         msg = 'Your supplied e-mail does not exist in our database. Please try again or if you continue to have problems, contact %s.' % klf_info['contact_email']
         raise Invalid(msg, value, state, error_dict={'email_address': msg})
예제 #42
0
 def person(self, id):
     c.person = Person.find_by_id(id)
     return render('/fulfilment/person.mako')
예제 #43
0
 def _to_python(self, value, state):
     return Person.find_by_id(int(value))
예제 #44
0
파일: review.py 프로젝트: Secko/zookeepr
 def summary(self):
     c.summary = Person.find_review_summary().all()
     return render('review/summary.mako')