flask.url_for

Here are the examples of the python api flask.url_for taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pkgdb2
Source File: __init__.py
View license
@UI.route('/logout/')
def logout():
    """ Log out if the user is logged in other do nothing.
    Return to the index page at the end.
    """
    next_url = flask.url_for('ui_ns.index')
    if 'next' in flask.request.values:  # pragma: no cover
        next_url = flask.request.values['next']

    if next_url == flask.url_for('ui_ns.login'):  # pragma: no cover
        next_url = flask.url_for('ui_ns.index')
    if hasattr(flask.g, 'fas_user') and flask.g.fas_user is not None:
        FAS.logout()
        flask.flash("You are no longer logged-in")
    flask.session['_justloggedout'] = True
    return flask.redirect(next_url)

Example 2

Project: gae-init
Source File: auth.py
View license
@ndb.toplevel
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if flask_login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    return flask.redirect(util.get_next_url(auth_params['next']))
  flask.flash('Sorry, but you could not sign in.', category='danger')
  return flask.redirect(flask.url_for('signin'))

Example 3

Project: gae-init-babel
Source File: auth.py
View license
@ndb.toplevel
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if flask_login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    return util.set_locale(
      user_db.locale,
      flask.redirect(util.get_next_url(auth_params['next'])),
    )
  flask.flash(__('Sorry, but you could not sign in.'), category='danger')
  return flask.redirect(flask.url_for('signin'))

Example 4

Project: gae-init-debug
Source File: auth.py
View license
@ndb.toplevel
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if flask_login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    return flask.redirect(util.get_next_url(auth_params['next']))
  flask.flash('Sorry, but you could not sign in.', category='danger')
  return flask.redirect(flask.url_for('signin'))

Example 5

Project: gae-init-docs
Source File: auth.py
View license
@ndb.toplevel
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if flask_login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    return flask.redirect(util.get_next_url(auth_params['next']))
  flask.flash('Sorry, but you could not sign in.', category='danger')
  return flask.redirect(flask.url_for('signin'))

Example 6

Project: gae-init-upload
Source File: util.py
View license
def get_next_url(next_url=''):
  args = parser.parse({
    'next': wf.Str(missing=None), 'next_url': wf.Str(missing=None)
  })
  next_url = next_url or args['next'] or args['next_url']
  do_not_redirect_urls = [flask.url_for(u) for u in [
    'signin', 'signup', 'user_forgot', 'user_reset',
  ]]
  if next_url:
    if any(url in next_url for url in do_not_redirect_urls):
      return flask.url_for('welcome')
    return next_url
  referrer = flask.request.referrer
  if referrer and referrer.startswith(flask.request.host_url):
    return referrer
  return flask.url_for('welcome')

Example 7

Project: github-stats
Source File: auth.py
View license
@ndb.toplevel
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    if user_db.github:
      return flask.redirect(flask.url_for('gh_account', username=user_db.github))
    return flask.redirect(util.get_next_url(auth_params['next']))
  flask.flash('Sorry, but you could not sign in.', category='danger')
  return flask.redirect(flask.url_for('signin'))

Example 8

Project: fedocal
Source File: fedora_calendar.py
View license
    def formatmonthname(self, theyear, themonth, withyear=True):
        """
        Return a month name as a table row.
        """

        lcle = self.locale
        if self.locale in ['en', 'en_EN']:
            lcle = 'C'

        with TimeEncoding(lcle) as encoding:
            smonth = month_name[themonth]
            if encoding is not None:
                smonth = smonth.decode(encoding)

            if withyear:
                string = '%s %s' % (smonth, theyear)
            else:
                string = '%s' % smonth

        prev_month = self.month - 1
        prev_year = self.year
        if prev_month == 0:
            prev_month = 12
            prev_year = prev_year - 1

        prev_month_lnk = ''
        if self.calendar_name:
            prev_month_lnk = '<a class="button" href="%s"><</a>' % (
                flask.url_for(
                    'calendar',
                    calendar_name=self.calendar_name,
                    year=int(prev_year),
                    month=int(prev_month),
                    day=1))
        elif self.loc_name:
            prev_month_lnk = '<a class="button" href="%s"><</a>' % (
                flask.url_for(
                    'location',
                    loc_name=self.loc_name,
                    year=int(prev_year),
                    month=int(prev_month),
                    day=1))

        next_month = self.month
        next_year = self.year + next_month / 12
        next_month = next_month % 12 + 1

        next_month_lnk = ''
        if self.calendar_name:
            next_month_lnk = '<a class="button" href="%s">></a>' % (
                flask.url_for(
                    'calendar',
                    calendar_name=self.calendar_name,
                    year=int(next_year),
                    month=int(next_month),
                    day=1))
        elif self.loc_name:
            next_month_lnk = '<a class="button" href="%s">></a>' % (
                flask.url_for(
                    'location',
                    loc_name=self.loc_name,
                    year=int(next_year),
                    month=int(next_month),
                    day=1))

        return '<tr><th colspan="7" class="month">%s %s %s</th></tr>' % (
            prev_month_lnk, string, next_month_lnk)

Example 9

Project: pjuu
Source File: test_auth_frontend.py
View license
    def test_signin_signout(self):
        """
        These functions will test the signin and signout endpoints. We will use
        url_for so that we can change the URIs in the future.
        """
        # Test that we can GET the signin page
        resp = self.client.get(url_for('auth.signin'))
        # We should get a 200 with an error message if we were not successful
        self.assertEqual(resp.status_code, 200)

        # There is no user in the system check that we can't authenticate
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        })
        # We should get a 200 with an error message if we were not successful
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Invalid user name or password', resp.data)

        # Why we are here we will just check that logging in doesn't raise an
        # issue if not logged in
        resp = self.client.get(url_for('auth.signout'))
        # We should be 302 redirected to /signin
        self.assertEqual(resp.status_code, 302)
        # There is nothing we can really check as we do not flash() as message

        # Create a test user and try loggin in, should fail as the user isn't
        # activated
        user1 = create_account('user1', '[email protected]', 'Password')
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        })
        # We should get a 200 with an information message
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Please activate your account', resp.data)

        # Activate account
        self.assertTrue(activate(user1))

        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password',
            'keep_signed_in': True
        }, follow_redirects=True)
        # Check we are redirected
        self.assertEqual(resp.status_code, 200)
        self.assertIn("<title>Feed - Pjuu</title>", resp.data)

        # Log back out
        self.client.get(url_for('auth.signout'))

        # Test that the user has additional spaces striped from their names
        resp = self.client.post(url_for('auth.signin'), data={
            'username': ' user1 ',
            'password': 'Password',
            'keep_signed_in': True
        }, follow_redirects=True)
        # Check we are redirected
        self.assertEqual(resp.status_code, 200)
        self.assertIn("<title>Feed - Pjuu</title>", resp.data)

        # Log back out
        self.client.get(url_for('auth.signout'))

        # Test that the correct warning is shown if the user is banned
        self.assertTrue(ban(user1))
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        })
        # We should get a 200 with an information message
        self.assertEqual(resp.status_code, 200)
        self.assertIn('You\'re a very naughty boy!', resp.data)
        # Lets unban the user now so we can carry on
        self.assertTrue(ban(user1, False))

        # Now the user is active and not banned actualy log in
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('<h1>Feed</h1>', resp.data)

        # Attempt to try and get back to login when we are already logged in
        resp = self.client.get(url_for('auth.signin'))
        self.assertEqual(resp.status_code, 302)

        # Now we are logged in lets just ensure logout doesn't do anything daft
        # We should be redirected back to /
        resp = self.client.get(url_for('auth.signout'), follow_redirects=True)
        # We should have been 302 redirected to /signin
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Successfully signed out', resp.data)

        # Lets try and cheat the system
        # Attempt invalid Password
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password1'
        }, follow_redirects=True)
        # We should get a 200 with an error message if we were not successful
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Invalid user name or password', resp.data)

        # Attempt user does not exist
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'bob',
            'password': 'Password'
        })
        # We should get a 200 with an error message if we were not successful
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Invalid user name or password', resp.data)

        # Log the user in and ensure they are logged out if there account
        # is banned during using the site and not just at login
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('<h1>Feed</h1>', resp.data)
        # Lets go to another view, we will check out profile and look for our
        # username
        resp = self.client.get(url_for('users.settings_profile'))
        self.assertEqual(resp.status_code, 200)
        self.assertIn('[email protected]', resp.data)
        # Let's ban the user now
        self.assertTrue(ban(user1))
        # Attempt to get to the feed
        resp = self.client.get(url_for('users.feed'), follow_redirects=True)
        # We should be redirected to signin with the standard message
        self.assertEqual(resp.status_code, 200)
        self.assertIn('You\'re a very naughty boy!', resp.data)

        # Adding test from form.validate() == False in signup
        # Coverage
        resp = self.client.post(url_for('auth.signin'), data={
            'username': '',
            'password': ''
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Invalid user name or password', resp.data)

        # Log in with user1 and remove the session part way through
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)

Example 10

Project: pjuu
Source File: test_auth_frontend.py
View license
    def test_signup_activate(self):
        """Tests the signup and activate endpoint inside Pjuu.

        There are some limitations to this! We can not test e-mail sending as
        this will not be available on Travis.
        """
        # Test that we can GET the signup page
        resp = self.client.get(url_for('auth.signup'))
        # We should get a 200 with an error message if we were not successful
        self.assertEqual(resp.status_code, 200)

        # Lets attempt to create a new account. This should return a 302 to
        # /signin with a little message displayed to activate your account
        resp = self.client.post(url_for('auth.signup'), data={
            'username': 'user1',
            'email': '[email protected]',
            'password': 'Password',
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Yay! You\'ve signed up', resp.data)

        # We are in testing mode so we can get the auth token from the response
        # this is in the headers as X-Pjuu-Token
        token = resp.headers.get('X-Pjuu-Token')
        self.assertIsNotNone(token)
        # Try and actiavte our account
        resp = self.client.get(url_for('auth.activate', token=token),
                               follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Your account has now been activated', resp.data)

        # Try and activate the account again. We should get a 302 to /signin
        # and a flash message informing up that the account is already active
        resp = self.client.get(url_for('auth.activate', token=token),
                               follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Invalid token', resp.data)

        # Try and signup with the same user and ensure we get the correct resp
        # and error codes
        resp = self.client.post(url_for('auth.signup'), data={
            'username': 'user1',
            'email': '[email protected]',
            'password': 'Password',
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        # Ensure there is an overall form error
        self.assertIn('Oh no! There are errors in your form', resp.data)
        # Ensure the form elements actually throw there own errors
        self.assertIn('User name already in use', resp.data)
        self.assertIn('E-mail address already in use', resp.data)

        # Try a few scenarios with email addresses we are not happy about.
        resp = self.client.post(url_for('auth.signup'), data={
            'username': 'user1',
            'email': 'user1#[email protected]',
            'password': 'Password',
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        # Ensure there is an overall form error
        self.assertIn('Oh no! There are errors in your form', resp.data)
        self.assertIn('Invalid email address', resp.data)

        # Ensure that we CAN signup with a + in the name. This is a hate of
        # mine. Not being able to namespace my e-mail addresses
        resp = self.client.post(url_for('auth.signup'), data={
            'username': 'user2',
            'email': '[email protected]',
            'password': 'Password',
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Yay! You\'ve signed up', resp.data)

        # Log in to Pjuu so that we can make sure we can not get back to signup
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        }, follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        # We are now logged in lets try and go to signup and ensure we get
        # redirected back to feed
        resp = self.client.get(url_for('auth.signup'))
        self.assertEqual(resp.status_code, 302)
        # Why we are logged in lets ensure we can't get to activate
        resp = self.client.get(url_for('auth.activate', token=token))
        self.assertEqual(resp.status_code, 302)

        # Lets delete the account and then try and reactivate
        delete_account(get_uid_username('user1'))
        resp = self.client.get(url_for('auth.activate', token=token),
                               follow_redirects=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Invalid token', resp.data)

Example 11

Project: pjuu
Source File: test_users_frontend.py
View license
    def test_follow_unfollow(self):
        """
        Ensure users can follow and unfollow each other, also ensure that the
        followers and following pages show the correct value
        """
        # Create 2 users and have them follow each other
        user1 = create_account('user1', '[email protected]', 'Password')
        user2 = create_account('user2', 'use[email protected]', 'Password')
        activate(user1)
        activate(user2)

        # Let's try and access the endpoints feature when we are not logged in
        # We should not be able to see it
        resp = self.client.post(url_for('users.follow', username='user1'),
                                follow_redirects=True)
        self.assertIn('You need to be signed in to view that', resp.data)
        resp = self.client.post(url_for('users.unfollow', username='user1'),
                                follow_redirects=True)
        self.assertIn('You need to be signed in to view that', resp.data)
        resp = self.client.get(url_for('users.following', username='user1'),
                               follow_redirects=True)
        self.assertIn('You need to be signed in to view that', resp.data)
        resp = self.client.get(url_for('users.followers', username='user1'),
                               follow_redirects=True)
        self.assertIn('You need to be signed in to view that', resp.data)

        # Ensure that test1 can follow and unfollow test2
        # Signin
        resp = self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        }, follow_redirects=True)
        self.assertIn('<h1>Feed</h1>', resp.data)

        # Try and see a non-existant users followers and following page
        resp = self.client.get(url_for('users.followers', username='None'))
        self.assertEqual(resp.status_code, 404)
        resp = self.client.get(url_for('users.following', username='None'))
        self.assertEqual(resp.status_code, 404)
        # Try follow and unfollow a non-existant user
        resp = self.client.post(url_for('users.follow', username='None'))
        self.assertEqual(resp.status_code, 404)
        resp = self.client.post(url_for('users.unfollow', username='None'))
        self.assertEqual(resp.status_code, 404)

        # Try follow and unfollow yourself
        resp = self.client.post(url_for('users.follow', username='user1'),
                                follow_redirects=True)
        self.assertIn('You can\'t follow/unfollow yourself', resp.data)
        resp = self.client.post(url_for('users.unfollow', username='user1'),
                                follow_redirects=True)
        self.assertIn('You can\'t follow/unfollow yourself', resp.data)

        # Visit test2 and ensure followers count is 0
        resp = self.client.get(url_for('users.followers', username='user2'))
        self.assertIn('<!-- followers:0 -->', resp.data)

        # Follow test2
        # Ensure we pass a next variable to come back to test2's followers page
        resp = self.client.post(url_for('users.follow', username='user2',
                                next=url_for('users.followers',
                                             username='user2')),
                                follow_redirects=True)
        # Ensure the flash message has informed use we are following
        self.assertIn('You have started following user2', resp.data)
        # Ensure test2's followers count has been incremented
        self.assertIn('<!-- followers:1 -->', resp.data)
        # This should match inside a link (Test1 due to capitalization)
        # Not the best test but it works for now
        self.assertIn('<!-- list:user:%s -->' % user1, resp.data)

        # Attempt to follow test2 again
        resp = self.client.post(url_for('users.follow', username='user2',
                                next=url_for('users.followers',
                                             username='user2')),
                                follow_redirects=True)
        # Check we got no confirmation
        self.assertNotIn('You have started following test2', resp.data)
        # Check that the followers count has not incremented
        self.assertIn('<!-- followers:1 -->', resp.data)

        # Ensure test2 is in from YOUR (test1s) following page
        resp = self.client.get(url_for('users.following', username='user1'))
        self.assertNotIn('<!-- list:user:%s -->' % user1, resp.data)

        # Unfollow test2
        # Ensure that all the previous has been reversed
        resp = self.client.post(url_for('users.unfollow', username='user2',
                                next=url_for('users.followers',
                                             username='user2')),
                                follow_redirects=True)
        self.assertIn('You are no longer following user2', resp.data)
        self.assertIn('<!-- followers:0 -->', resp.data)
        # Check the list testing tag has gone
        self.assertNotIn('<!-- list:user:test1 -->', resp.data)

        # Attempt to unfollow the user again
        resp = self.client.post(url_for('users.unfollow', username='user2',
                                next=url_for('users.followers',
                                             username='user2')),
                                follow_redirects=True)
        self.assertNotIn('You are no longer following user2', resp.data)
        self.assertIn('<!-- followers:0 -->', resp.data)

        # Ensure test2 is missing from YOUR (test1s) following page
        resp = self.client.get(url_for('users.following', username='user1'))
        self.assertNotIn('<!-- list:user:%s -->' % user2, resp.data)

Example 12

Project: pjuu
Source File: test_users_frontend.py
View license
    def test_settings_profile(self):
        """Ensure users have the ability to see some information about there
        account and can change there about message and display options.
        """
        # Let's try and access the endpoint feature when we are not logged in
        # We should not be able to see it
        resp = self.client.get(url_for('users.settings_profile'),
                               follow_redirects=True)
        self.assertIn('You need to be signed in to view that', resp.data)

        # Create a test user
        user1 = create_account('user1', '[email protected]', 'Password')
        # Activate it
        activate(user1)

        # Signin
        self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        })

        # If the user profile hasn't been saved the sort order should
        user = m.db.users.find_one({'username': 'user1'})
        self.assertIsNone(user.get('reply_sort_order'))

        # Go to our settings page and ensure everything is there
        resp = self.client.get(url_for('users.settings_profile'))
        self.assertIn('<div class="content">user1</div>', resp.data)
        self.assertIn('<div class="content">[email protected]</div>', resp.data)
        # Post to the form and update our about. We should also be this on
        # this page
        resp = self.client.post(url_for('users.settings_profile'), data={
            'about': 'Otters love fish!'
        }, follow_redirects=True)
        self.assertIn('Otters love fish!', resp.data)

        # Try posting a MASSIVE about ('Otter' * 100)
        resp = self.client.post(url_for('users.settings_profile'), data={
            'about': 'Otters' * 100
        }, follow_redirects=True)
        # Check we get the form error
        self.assertIn('Oh no! There are errors in your form', resp.data)
        # Ensure the about did not change
        self.assertIn('Otters love fish!', resp.data)

        resp = self.client.post(url_for('users.settings_profile'), data={
            'about': 'Test display settings',
            'hide_feed_images': True,
        }, follow_redirects=True)
        self.assertIn('Test display settings', resp.data)

        # Not sure it's good to check for a checked checkbox so test the user
        # account
        user = get_user(user1)
        self.assertTrue(user.get('hide_feed_images'))

        # Ensure you can unset it
        resp = self.client.post(url_for('users.settings_profile'), data={
            'about': 'Test display settings',
        }, follow_redirects=True)

        # Get the user again. This should have been updated from the database
        user = get_user(user1)
        self.assertFalse(user.get('hide_feed_images'))

        # Test setting a homepage and location works as expected
        resp = self.client.post(url_for('users.settings_profile'), data={
            'about': 'Test display settings',
            'homepage': 'pjuu.com',
            'location': 'England'
        }, follow_redirects=True)

        user = get_user(user1)
        self.assertEqual(user.get('homepage'), 'http://pjuu.com')
        self.assertEqual(user.get('location'), 'England')

        # Ensure you can't set an invalid URL
        resp = self.client.post(url_for('users.settings_profile'), data={
            'about': 'Test display settings',
            'homepage': 'pjuu.cheese',
        }, follow_redirects=True)

        self.assertIn('Please ensure the home page is a valid URL or empty',
                      resp.data)

        # Test a URL that doesn't need to be prefixed
        resp = self.client.post(url_for('users.settings_profile'), data={
            'about': 'Test display settings',
            'homepage': 'https://pjuu.com',
        }, follow_redirects=True)

        user = get_user(user1)
        self.assertEqual(user.get('homepage'), 'https://pjuu.com')

        resp = self.client.post(url_for('users.settings_profile'), data={
            'homepage': 'https://pjuu.com',
            'location': 'England',
        }, follow_redirects=True)

        # Ensure the users profile reflects the changes
        resp = self.client.get(url_for('users.profile', username='user1'))
        self.assertIn('<i class="fa fa-map-marker fa-lg"></i> England',
                      resp.data)
        self.assertIn(
            '<a href="https://pjuu.com"><i class="fa fa-globe fa-lg"></i></a>',
            resp.data)

        # If the view before has been saved the default is -1 (unchecked)
        user = m.db.users.find_one({'username': 'user1'})
        self.assertEqual(user.get('reply_sort_order'), -1)

        resp = self.client.post(url_for('users.settings_profile'), data={
            'reply_sort_order': True,
        }, follow_redirects=True)
        user = m.db.users.find_one({'username': 'user1'})
        self.assertEqual(user.get('reply_sort_order'), 1)

        # You can not post the field as thats classed as a True value
        resp = self.client.post(url_for('users.settings_profile'),
                                data={'about': 'Test'},
                                follow_redirects=True)
        user = m.db.users.find_one({'username': 'user1'})
        self.assertEqual(user.get('reply_sort_order'), -1)

Example 13

Project: pjuu
Source File: test_users_frontend.py
View license
    def test_alerts(self):
        """Check that alerts are displayed properly in the frontend."""
        # Create two test users
        user1 = create_account('user1', '[email protected]', 'Password')
        user2 = create_account('user2', '[email protected]', 'Password')
        user3 = create_account('user3', '[email protected]', 'Password')
        # Activate
        activate(user1)
        activate(user2)
        activate(user3)

        # Try an visit i-has-alerts when not logged in
        resp = self.client.get(url_for('users.new_alerts'))
        self.assertEqual(resp.status_code, 403)

        # Login as user1
        self.client.post(url_for('auth.signin'), data={
            'username': 'user1',
            'password': 'Password'
        })

        # Get I has alerts and check that it is false
        resp = self.client.get(url_for('users.new_alerts'))
        # Check the JSON response
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.data).get('new_alerts'), 0)

        # Ensure that /alerts returns nothing
        resp = self.client.get(url_for('users.alerts'))
        self.assertNotIn('list:alert', resp.data)
        self.assertIn('Empty', resp.data)

        # Get user2 to follow user1
        follow_user(user2, user1)

        # Ensure that /i-has-alerts is correct
        resp = self.client.get(url_for('users.new_alerts'))
        # Check the JSON response
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.data).get('new_alerts'), 1)

        # Ensure the count goes up correctly
        follow_user(user3, user1)

        resp = self.client.get(url_for('users.new_alerts'))
        # Check the JSON response
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.data).get('new_alerts'), 2)

        resp = self.client.get(url_for('users.alerts'))
        # We don't know the alert ID but we can check that one is there by
        # looking for the comment in test mode
        self.assertIn('list:alert:', resp.data)
        self.assertNotIn('Empty', resp.data)
        # Check test2's name is there
        self.assertIn('user2', resp.data)
        # Check that the prettify message from FollowAlert is there
        self.assertIn('has started following you', resp.data)

        # We have now checked the alerts, ensure that i-has-alerts is False
        resp = self.client.get(url_for('users.new_alerts'))
        # Check the JSON response
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.data).get('new_alerts'), 0)

        # Check that we can delete the alert
        # Get the both alert ids from the backend function
        alert1 = get_alerts(user1).items[0].alert_id
        alert2 = get_alerts(user1).items[1].alert_id

        # Check that we don't get a message if there was no alert to delete
        resp = self.client.get(url_for('users.delete_alert',
                                       alert_id=k.NIL_VALUE),
                               follow_redirects=True)
        self.assertNotIn('Alert has been hidden', resp.data)

        # Delete both alerts
        resp = self.client.get(url_for('users.delete_alert', alert_id=alert1),
                               follow_redirects=True)
        self.assertIn('Alert has been hidden', resp.data)
        self.assertNotIn('<!-- list:alert:{} -->'.format(alert1),
                         resp.data)
        self.assertIn('<!-- list:alert:{} -->'.format(alert2),
                      resp.data)

        # Check when the last alert is deleted we get an empty list
        resp = self.client.get(url_for('users.delete_alert', alert_id=alert2),
                               follow_redirects=True)
        self.assertIn('Alert has been hidden', resp.data)
        # Check that there are also no alerts now
        self.assertIn('Empty', resp.data)

Example 14

Project: guides-cms
Source File: api.py
View license
@app.route('/api/save/', methods=['POST'])
@login_required
def api_save():
    """
    Api: POST /api/save
    {path:'', title: '', sha:'', original_stack: '', content: '', stacks: []}
    """

    # Used to show link to slack for authors to get feedback
    g.slack_url = SLACK_URL

    user = models.find_user()
    if user is None:
        redirect_to = url_for('index')
        data = {'error': 'Cannot save unless logged in', 'redirect': redirect_to}
        return Response(response=json.dumps(data), status=401, mimetype='application/json')

    if user.email is None:
        flash('Unable to read email address from Github API to properly attribute your commit to your account. Please make sure you have authorized the application to access your email.', category='warning')
        # FIXME: stop using flash

    content = request.form['content']

    path = request.form['path']
    title = request.form['title']
    sha = request.form['sha']
    orig_stack = request.form['original_stack']
    first_commit = request.form['first_commit']

    if not content.strip() or not title.strip():
        data = {'error': 'Must enter title and body of guide'}
        return Response(response=json.dumps(data), status=400, mimetype='application/json')

    # Form only accepts 1 stack right now but we can handle multiple on the
    # back-end.
    if not request.form['stacks']:
        stacks = None
    else:
        stacks = request.form.getlist('stacks')

        # FIXME: This is not the best solution. We're making this task
        # synchronous but it's just a few git commands so hoping it will be
        # quick. Also it only happens in the rare case where a stack is
        # changed.  We need to wait for the file move so we can maintain the
        # history of the article through the move.
        if path and orig_stack and stacks[0] != orig_stack:
            new_path = models.change_article_stack(path, orig_stack, stacks[0],
                                                   title, user.login,
                                                   user.email)

            if new_path is None:
                flash('Failed changing guide stack', category='error')
                # FIXME? return an error?
            else:
                path = new_path

    new_article = False
    if path:
        message = 'Updates to "%s"' % (title)
    else:
        new_article = True
        message = 'New guide, "%s"' % (title)

        # Go ahead and make sure we don't have an article with the same stack
        # and title.  This would lead to duplicate URLs and we want to
        # prevent users from ever creating a clash instead of detecting this
        # change
        article = models.search_for_article(title, stacks=stacks)
        if article is not None:
            if stacks is None:
                msg = u'Please try choosing a stack. The title "%s" is already used by a guide.' % (title)
            else:
                msg = u'Please try choosing a different stack/title combination. The title "%s" is already used by a guide with the stack "%s".' % (title, ','.join(stacks))
            data = {'error': msg}
            return Response(response=json.dumps(data), status=422, mimetype='application/json')

    # Hidden option for admin to save articles to our other repo that's not
    # editable
    # TODO: move this to another endpoint
    repo_path = None
    if request.form.get('secondary_repo', None) is not None:
        repo_path = '%s/%s' % (app.config['SECONDARY_REPO_OWNER'],
                               app.config['SECONDARY_REPO_NAME'])

    article = models.branch_or_save_article(title, path, message, content,
                                            user.login, user.email, sha,
                                            user.avatar_url,
                                            stacks=stacks,
                                            repo_path=repo_path,
                                            author_real_name=user.name,
                                            first_commit=first_commit)

    if not article:
        # Was this a new guide or update?
        if path:
            redirect_to = request.referrer or url_for('index')
        else:
            redirect_to = url_for('write')

        data = {'error': 'Failed creating guide on github. Please try again.',
                'redirect': redirect_to}

        return Response(response=json.dumps(data), status=500, mimetype='application/json')

    # TODO: move this to another endpoint
    if repo_path is not None:
        redirect_to = url_for('partner', article_path=article.path, branch=article.branch)
        data = {'msg': 'Saved into admin repository', 'redirect': redirect_to}
        if new_article:
            return Response(response=json.dumps(data), status=201, mimetype='application/json')
        else:
            return Response(response=json.dumps(data), status=200, mimetype='application/json')

    # We only have to worry about this on the master branch because we never
    # actually use file listings on other branches.
    if article.branch == u'master':
        # Use these filter wrappers so we get absolute URL instead of relative
        # URL to this specific site.
        url = filters.url_for_article(article, base_url=app.config['DOMAIN'])
        author_url = filters.url_for_user(article.author_name,
                                          base_url=app.config['DOMAIN'])

        tasks.update_listing.delay(url,
                                   article.title,
                                   author_url,
                                   article.author_real_name,
                                   user.login,
                                   user.email,
                                   author_img_url=article.image_url,
                                   thumbnail_url=article.thumbnail_url,
                                   stacks=article.stacks,
                                   branch=article.branch,
                                   status=article.publish_status)

    redirect_to = filters.url_for_article(article, branch=article.branch, saved=1)
    data = {'redirect': redirect_to}
    status = 200

    if new_article:
        status = 201

    return Response(response=json.dumps(data), status=status,
                    mimetype='application/json')

Example 15

Project: guides-cms
Source File: views.py
View license
def render_article_view(request_obj, article, only_visible_by_user=None):
    """
    Render article view

    :param request_obj: Request object
    :param article: Article object to render view for
    :param branch: Branch of article to read
    :param only_visible_by_user: Name of user that is allowed to view article
                                 or None to allow anyone to read it
    """

    g.review_active = True
    login = session.get('login', None)
    collaborator = session.get('collaborator', False)

    recently_saved = request.args.get('saved', 0)
    status = request.args.get('status', PUBLISHED)

    publish_statuses = ()

    if login == article.branch or article.author_name == login:
        allow_delete = True

        # Regular users cannot directly publish
        publish_statuses = (IN_REVIEW, DRAFT)
    else:
        allow_delete = False

    # Collaborators aka editors can use all statuses
    if collaborator:
        publish_statuses = STATUSES

    # Use http as canonical protocol for url to avoid having two separate
    # comment threads for an article. Disqus uses this variable to save
    # comments.
    canonical_url = request_obj.base_url.replace('https://', 'http://')

    article_identifier = article.first_commit
    redirect_url = None
    if article_identifier is None:
        # Backwards compatability for disqus comments. We didn't track the
        # first commit before version .2 and all disqus comments used the
        # slugified title for the unique id.  Disqus doesn't allow for changing
        # this so we're stuck with it if we want to maintain the comments
        # before version .2.
        article_identifier = utils.slugify(article.title)

        # Hack to save our old social shares. The po.st service doesn't handle
        # 301 redirects so need to share with the old url to keep the counts.
        redirect_url = u'%s/review/%s' % (app.config['DOMAIN'],
                                          article_identifier)
    else:
        # Use full domain for redirect_url b/c this controls the po.st social
        # sharing numbers.  We want these numbers to stick with the domain
        # we're running on so counts go with us.
        redirect_url = filters.url_for_article(article,
                                               base_url=app.config['DOMAIN'])

    # Filter out the current branch from the list of branches
    branches = [b for b in article.branches if b != article.branch]

    # Always include a link to original article if this is a branched version
    if article.branch != u'master':
        branches.append([article.author_name, u'master'])

    g.header_white = True

    user = models.find_user(article.author_name)
    if only_visible_by_user is not None and only_visible_by_user != user.login:
        return redirect(url_for('index'))

    # Don't allow comments when we're testing b/c disqus will create a
    # 'discussion' for every article and there's no way to delete them!
    allow_comments = not app.debug

    allow_set_featured = collaborator and (
                         models.allow_set_featured_article()) and (
                         article.published)

    hearted = False
    if login is not None:
        hearted = models.has_hearted(article.stacks[0], article.title, login)

    return render_template('article.html',
                           article=article,
                           hearted=hearted,
                           allow_delete=allow_delete,
                           canonical_url=canonical_url,
                           article_identifier=article_identifier,
                           branches=branches,
                           allow_set_featured=allow_set_featured,
                           user=user,
                           publish_statuses=publish_statuses,
                           redirect_url=redirect_url,
                           allow_comments=allow_comments,
                           recently_saved=recently_saved,
                           status=status)

Example 16

Project: guides-cms
Source File: views.py
View license
@app.route('/publish', methods=['POST'])
@login_required
def change_publish_status():
    """Publish or unpublish article via POST"""

    user = models.find_user()
    if user is None:
        flash('Cannot change publish status unless logged in', category='error')
        return render_published_articles(status_code=401)

    path = request.form['path']
    branch = request.form['branch']

    publish_status = request.form['publish_status']
    if publish_status not in STATUSES:
        flash('Invalid publish status, must be one of "%s"' % (STATUSES),
              category='error')
        return render_template('index.html')

    if branch != u'master':
        flash('Cannot change publish status on guides from branches other than master', category='error')
        return redirect(url_for('index'))

    article = models.read_article(path, rendered_text=False, branch=branch)
    if article is None:
        flash('Cannot find guide to change publish status', category='error')
        return redirect(url_for('index'))

    if article.publish_status == publish_status:
        flash('Guide already in %s publish status' % (publish_status),
              category='warning')
        return redirect(filters.url_for_article(article))

    if not user.is_collaborator:
        if article.author_name != user.login:
            flash('Only collaborators can change publish status on guides they do not start',
                  category='error')
            return redirect(url_for('index'))

        if publish_status == PUBLISHED:
            flash('Only collaborators can publish guides')
            return redirect(url_for('index'))

    curr_path = article.path

    app.logger.info(u'Requesting publish change for "%s" from "%s" to "%s"',
                    article.title, article.publish_status, publish_status)

    article.publish_status = publish_status

    author_url = filters.url_for_user(article.author_name,
                                      base_url=app.config['DOMAIN'])

    # Create this link AFTER changing the status b/c the URL will have the
    # status in it if the article is not published yet.
    article_url = filters.url_for_article(article,
                                          base_url=app.config['DOMAIN'])

    tasks.update_listing.delay(article_url,
                               article.title,
                               author_url,
                               article.author_real_name,
                               user.login,
                               user.email,
                               author_img_url=article.image_url,
                               thumbnail_url=article.thumbnail_url,
                               stacks=article.stacks,
                               branch=article.branch,
                               status=article.publish_status)

    tasks.move_article.delay(curr_path, article.path, article.title,
                             user.login, user.email,
                             new_publish_status=article.publish_status)

    return redirect(filters.url_for_article(article, saved=1))

Example 17

Project: pygotham
Source File: talks.py
View license
@route(
    blueprint,
    '/new/',
    defaults={'pk': None},
    endpoint='submit',
    methods=('GET', 'POST'),
    navbar_kwargs={
        'path': ('Speaking', 'Submit a Talk'),
        'when': lambda: g.current_event.is_call_for_proposals_active,
    })
@route(blueprint, '/<int:pk>/edit/', endpoint='edit', methods=('GET', 'POST',))
@login_required
def proposal(pk=None):
    """Return the talk proposal form."""
    from pygotham.forms import TalkSubmissionForm

    if not (current_user.name and current_user.bio):
        message = 'Please fill out your speaker profile before continuing.'
        flash(message, 'warning')
        return redirect(url_for('profile.settings'))

    event = g.current_event

    if pk:
        talk = Talk.query.filter(
            Talk.id == pk, Talk.event == event).first_or_404()
        if talk.user != current_user:
            abort(403)
    else:
        if not event.is_call_for_proposals_active:
            # If the current event's CFP is closed, don't allow users to
            # submit new proposals.
            message = 'The Call for Proposals is closed at this time.'
            flash(message, 'warning')
            return redirect(url_for('home.index'))
        talk = Talk(
            user_id=current_user.id,
            event_id=event.id,
            recording_release=True,
            type='talk',
        )

    form = TalkSubmissionForm(obj=talk)
    if form.validate_on_submit():
        form.populate_obj(talk)

        db.session.add(talk)
        db.session.commit()

        flash('Your proposal has been submitted.', 'success')

        return redirect(url_for('profile.dashboard'))

    return render_template('talks/proposal.html', form=form)

Example 18

Project: quokka
Source File: views.py
View license
    def get(self, long_slug):
        # !!! filter available_until
        now = datetime.now()
        path = long_slug.split('/')
        mpath = ",".join(path)
        mpath = ",{0},".format(mpath)

        channel = Channel.objects.get_or_404(mpath=mpath, published=True)

        if not is_accessible(roles_accepted=channel.roles):
            raise abort(403, "User has no role to view this channel content")

        if channel.is_homepage and request.path != channel.get_absolute_url():
            return redirect(channel.get_absolute_url())

        published_channels = Channel.objects(published=True).values_list('id')

        if channel.redirect_url:
            url_protos = ('http://', 'mailto:', '/', 'ftp://')
            if channel.redirect_url.startswith(url_protos):
                return redirect(channel.redirect_url)
            else:
                return redirect(url_for(channel.redirect_url))

        if channel.render_content:
            return ContentDetail().get(
                channel.render_content.content.long_slug, True)

        self.channel = channel

        base_filters = {}

        filters = {
            'published': True,
            'available_at__lte': now,
            'show_on_channel': True,
            'channel__in': published_channels
        }

        if not channel.is_homepage:
            base_filters['__raw__'] = {
                '$or': [
                    {'mpath': {'$regex': "^{0}".format(mpath)}},
                    {'related_mpath': {'$regex': "^{0}".format(mpath)}}
                ]
            }
        else:
            # list only allowed items in homepage
            user_roles = [role.name for role in get_current_user().roles]
            if 'admin' not in user_roles:
                base_filters['__raw__'] = {
                    "$or": [
                        {"channel_roles": {"$in": user_roles}},
                        {"channel_roles": {"$size": 0}},
                        # the following filters are for backwards compatibility
                        {"channel_roles": None},
                        {"channel_roles": {"$exists": False}}
                    ]
                }

        filters.update(channel.get_content_filters())
        contents = Content.objects(**base_filters).filter(**filters)

        sort = request.args.get('sort')
        if sort:
            contents = contents.order_by(sort)
        elif channel.sort_by:
            contents = contents.order_by(*channel.sort_by)

        disabled_pagination = False
        if not current_app.config.get("PAGINATION_ENABLED", True):
            disabled_pagination = contents.count()

        pagination_arg = current_app.config.get("PAGINATION_ARG", "page")
        page = request.args.get(pagination_arg, 1)
        per_page = (
            disabled_pagination or
            request.args.get('per_page') or
            channel.per_page or
            current_app.config.get("PAGINATION_PER_PAGE", 10)
        )
        contents = contents.paginate(page=int(page),
                                     per_page=int(per_page))

        themes = channel.get_themes()
        return render_template(self.get_template_names(),
                               theme=themes,
                               contents=contents,
                               channel=channel)

Example 19

Project: quokka
Source File: aliases.py
View license
def dispatch_aliases():
    """
    When ALIASES_ENABLED == True

    This method handle 3 QuokkaCMS features:
    1. Fixed aliases
      Alias is defined in ALIASES_MAP setting as a dictionary
    2. Managed Redirects
      Alias defined in database
    3. Channel and Content aliases
      Alias defined in specific channel or content

    ALIASES_MAP
    keys are long_slug
        keys should always start with /
        & end with / or extension.
    {
        "/team/": {
            "alias_type": "endpoint|long_slug|url|string|template",
            "action": "redirect|render",
            "to": "authors|/articles/science.html|http://t.co|'<b>Hello</b>'",
            "published": True,
            "available_at": "",
            "available_until: "",
        }
    }

    - 'endpoint' and 'long_slug' by default are rendered
    - 'url' is always redirect
    - 'string' and 'template' are always rendered
    """

    app = current_app
    aliases_map = app.config.get('ALIASES_MAP')
    if aliases_map and request.path in aliases_map:
        alias = aliases_map[request.path]
        status = alias.get('status', 200)
        if alias['alias_type'] == 'endpoint':
            endpoint = alias['to']
            if alias.get('action') == 'redirect':
                return redirect(url_for(endpoint, **request.args))
            else:  # render
                return app.process_response(
                    app.make_response(
                        app.view_functions[endpoint]()
                    )
                )
        elif alias['alias_type'] == 'long_slug':
            long_slug = alias['to']
            if alias.get('action') == 'redirect':
                return redirect(long_slug)  # pass request.args ?
            else:  # render
                endpoint = route_from(long_slug)[0]
                return app.process_response(
                    app.make_response(
                        app.view_functions[endpoint]()
                    )
                )
        elif alias['alias_type'] == 'url':
            return redirect(alias['to'])
        elif alias['alias_type'] == 'string':
            return render_template_string(alias['to']), status
        elif alias['alias_type'] == 'template':
            return render_template(alias['to']), status

Example 20

Project: flask-funnel
Source File: main.py
View license
    def init_app(self, app):
        self.app = app

        app.config.setdefault('CSS_MEDIA_DEFAULT', 'screen,projection,tv')
        app.config.setdefault('BUNDLES_DIR', 'bundles')
        app.config.setdefault('FUNNEL_USE_S3', False)

        app.config.setdefault('LESS_BIN', 'lessc')
        app.config.setdefault('LESS_PREPROCESS', False)

        app.config.setdefault('SCSS_BIN', 'scss')
        app.config.setdefault('SCSS_PREPROCESS', False)

        app.config.setdefault('STYLUS_BIN', 'stylus')
        app.config.setdefault('STYLUS_PREPROCESS', False)

        app.config.setdefault('COFFEE_BIN', 'coffee')
        app.config.setdefault('COFFEE_PREPROCESS', False)

        app.config.setdefault('AUTOPREFIXER_BIN', 'autoprefixer')
        app.config.setdefault('AUTOPREFIXER_ENABLED', False)
        app.config.setdefault('AUTOPREFIXER_BROWSERS', 'last 2 versions')

        app.config.setdefault('CSS_BUNDLES', {})
        app.config.setdefault('JS_BUNDLES', {})

        def get_path(item):
            return os.path.join(app.static_folder, item)

        @app.context_processor
        def context_processor():
            def get_url(item):
                if app.config.get('FUNNEL_USE_S3'):
                    try:
                        from flask.ext.s3 import url_for
                    except ImportError:
                        from flask import url_for
                else:
                    from flask import url_for

                if item.startswith(('//', 'http://', 'https://')):
                    return item
                item = item.split('?', 1)
                url = url_for('static', filename=item[0])
                if item[1]:
                    url += '?' + item[1]
                return url

            def get_mtime(item):
                if item.startswith(('//', 'http://', 'https://')):
                    return int(time.time())

                try:
                    return int(os.path.getmtime(get_path(item)))
                except OSError:
                    return int(time.time())

            def build_html(items, wrapper):
                return Markup('\n'.join((wrapper % (get_url(item))
                              for item in items)))

            def _build(bundle_tp, bundle):
                items = []
                for item in app.config.get(bundle_tp)[bundle]:
                    items.append(preprocess(item))

                # Add timestamp to avoid caching.
                items = ['%s?build=%s' % (item, get_mtime(item))
                         for item in items]

                return items

            def js(bundle, defer=False, async=False, debug=app.debug):
                if debug:
                    items = _build('JS_BUNDLES', bundle)
                else:
                    bundle_file = os.path.join(app.config.get('BUNDLES_DIR'),
                                               'js', '%s-min.js' % bundle)
                    items = ('%s?build=%s' % (bundle_file,
                                              get_mtime(bundle_file)),)

                attrs = ['src="%s"']

                if defer:
                    attrs.append('defer')

                if async:
                    attrs.append('async')

                string = '<script %s></script>' % ' '.join(attrs)
                return build_html(items, string)

            def css(bundle, media=None, debug=app.debug):
                if media is None:
                    media = app.config.get('CSS_MEDIA_DEFAULT')

                if debug:
                    items = _build('CSS_BUNDLES', bundle)
                else:
                    bundle_file = os.path.join(app.config.get('BUNDLES_DIR'),
                                               'css', '%s-min.css' % bundle)
                    items = ('%s?build=%s' % (bundle_file,
                                              get_mtime(bundle_file),),)

                ss_html = '<link rel="stylesheet" media="%s" href="%%s" />'
                return build_html(items, ss_html % media)

            return dict(js=js, css=css)

Example 21

View license
@examples_alerts.route('/modal')
def modal():
    """Push flash message to stack, then redirect back to index()."""
    message_size = request.args.get('message_size')
    flash_count = request.args.get('flash_count')
    flash_type = request.args.get('flash_type')

    # First check if requested type/count are valid.
    available_types = [k for k, v in flash.__dict__.items() if callable(v)]
    if flash_type not in available_types:
        abort(400)
    if not str(flash_count).isdigit() or not (1 <= int(flash_count) <= 10):
        abort(400)

    # Build message.
    if message_size == 'large':
        message = dedent("""\
        Traceback (most recent call last):
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/tornado/web.py", line 1309, in _execute
            result = self.prepare()
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/tornado/web.py", line 2498, in prepare
            self.fallback(self.request)
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/tornado/wsgi.py", line 280, in __call__
            WSGIContainer.environ(request), start_response)
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
            return self.wsgi_app(environ, start_response)
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
            response = self.make_response(self.handle_exception(e))
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/flask/app.py", line 1410, in handle_exception
            return handler(e)
          File "/Users/robpol86/workspace/Flask-Large-Application-Example/pypi_portal/middleware.py", line 56, in error_handler
            send_exception('{} exception in {}'.format(exception_name, view_module))
          File "/Users/robpol86/workspace/Flask-Large-Application-Example/pypi_portal/core/email.py", line 77, in send_exception
            mail.send(msg)
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/flask_mail.py", line 415, in send
            with self.connect() as connection:
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/flask_mail.py", line 123, in __enter__
            self.host = self.configure_host()
          File "/Users/robpol86/virtualenvs/Flask-Large-App/lib/python2.7/site-packages/flask_mail.py", line 137, in configure_host
            host = smtplib.SMTP(self.mail.server, self.mail.port)
          File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 251, in __init__
            (code, msg) = self.connect(host, port)
          File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 311, in connect
            self.sock = self._get_socket(host, port, self.timeout)
          File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 286, in _get_socket
            return socket.create_connection((host, port), timeout)
          File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 553, in create_connection
            for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        gaierror: [Errno 8] nodename nor servname provided, or not known\
        """)
    elif message_size == 'medium':
        message = ("Built-in functions, exceptions, and other objects.\n\nNoteworthy: "
                   "None is the `nil' object;&nbsp;<script>Ellipsis represents `...' in slices.")
    else:
        message = 'This is a sample message.'

    # Push to flash stack, then redirect.
    func = getattr(flash, flash_type)
    for i in range(int(flash_count)):
        func(message)
    return redirect(url_for('.index'))

Example 22

Project: runbook
Source File: views.py
View license
@monitor_blueprint.route('/dashboard/monitors/<cname>', methods=['GET', 'POST'])
def addcheck_page(cname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/monitors/' + cname
        tmpl = 'monitors/create.html'
        data['js_bottom'] = ['monitors/monitorlist.js', 'monitors/base.js',]
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Get list of reactions and validate that there are some
            data['reactions'] = user.getReactions(g.rdb_conn)
            # Proces the form
            cform = __import__(
                "monitorforms." + cname, globals(), locals(), ['CheckForm'], -1)
            form = cform.CheckForm(request.form)
            if form.__contains__("timer"):
                form.timer.choices = data['choices']
            reactchoices = []
            for key in data['reactions'].keys():
                reactchoices.append(
                    (data['reactions'][key]['id'],
                        data['reactions'][key]['name']))
            form.reactions.choices = reactchoices
            if request.method == 'POST':
                if form.validate():
                    monitor = Monitor()
                    monitor.config = app.config
                    monitor.name = form.name.data
                    monitor.ctype = cname
                    monitor.uid = user.uid
                    monitor.status = "queued"
                    monitor.url = None
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    monitor.data = tmpdata

                    # Check if the user already exceeds their limit
                    if monitor.count(user.uid, g.rdb_conn) < data['limit']:
                        # Create the monitor if all checks out
                        results = monitor.createMonitor(g.rdb_conn)
                    else:
                        if data['upgraded']:
                            payment = __import__("payments." + user.payments, globals(),
                                                 locals(), ['Payments'], -1)
                            subscription = payment.Payments(user=user, config=app.config, rdb=g.rdb_conn)
                            quantity = user.subplans + 1
                            results = subscription.adjust(quantity=quantity)
                            if results:
                                results = monitor.createMonitor(g.rdb_conn)
                        else:
                            results = "toomany"

                    if results == "exists":
                        print("/dashboard/monitors/{0} - \
                              Monitor already exists".format(cname))
                        flash('{0} seems to already exist. \
                              Try using a different name.'.format(
                              monitor.name), 'danger')
                    elif results is False:
                        print("/dashboard/monitors/{0} - \
                            Monitor creation failed".format(cname))
                        flash('Could not create monitor.', 'danger')
                    elif results == 'toomany':
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Too many health checks',
                            1)
                        flash('You have too many monitors. \
                              Please upgrade your plan or clean \
                              up old ones.', 'danger')
                        print("/dashboard/monitors/{0} - \
                              Monitor creation failed: toomany".format(cname))
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Monitor Added', 1)
                        print("/dashboard/monitors/%s - \
                              Monitor creation successful") % cname
                        flash('Monitor "{0}" successfully added.'.format(
                            monitor.name), 'success')
                        newmonitor = Monitor()
                        newmonitor.config = app.config
                        newmonitor.get(results, g.rdb_conn)
                        if newmonitor.uid == user.uid:
                            data['monitor'] = {
                                'cid': newmonitor.cid,
                                'name': newmonitor.name,
                                'uid': newmonitor.uid,
                                'ctype': newmonitor.ctype,
                                'url': newmonitor.url,
                                'data': newmonitor.data
                            }
                else:
                    print("/dashboard/monitors/{0} - \
                          Monitor creation failed: Form invalid".format(cname))
                    flash('Form is not valid.', 'danger')
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))

Example 23

Project: runbook
Source File: views.py
View license
@monitor_blueprint.route(
    '/dashboard/edit-monitors/<cname>/<cid>', methods=['GET', 'POST'])
def editcheck_page(cname, cid):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-monitors/' + cname + "/" + cid
        tmpl = 'monitors/create.html'
        data['edit'] = True
        data['js_bottom'] = ['monitors/base.js',]
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Get list of reactions and validate that there are some
            data['reactions'] = user.getReactions(g.rdb_conn)
            # Proces the form
            cform = __import__(
                "monitorforms." + cname, globals(), locals(), ['CheckForm'], -1)
            form = cform.CheckForm(request.form)
            oldmonitor = Monitor()
            oldmonitor.config = app.config
            oldmonitor.get(cid, g.rdb_conn)
            if oldmonitor.uid == user.uid:
                data['monitor'] = {
                    'cid': oldmonitor.cid,
                    'name': oldmonitor.name,
                    'uid': oldmonitor.uid,
                    'ctype': oldmonitor.ctype,
                    'url': oldmonitor.url,
                    'data': oldmonitor.data
                }
            # Check if the form contains the timer SelectField
            if form.__contains__("timer"):
                form.timer.choices = data['choices']
            reactchoices = []
            reactdefaults = []
            for key in data['reactions'].keys():
                reactchoices.append(
                    (data['reactions'][key]['id'],
                        data['reactions'][key]['name']))
                if data['reactions'][key]['id'] in \
                        data['monitor']['data']['reactions']:
                    reactdefaults.append(data['reactions'][key]['id'])
            form.reactions.choices = reactchoices
            for item in form.__iter__():
                if item.type == "SelectField" or\
                        item.type == "SelectMultipleField":
                    item.default = data['monitor']['data'][item.name]

            if request.method == 'POST':
                if form.validate():
                    monitor = Monitor()
                    monitor.config = app.config
                    monitor.cid = cid
                    monitor.name = form.name.data
                    monitor.ctype = cname
                    monitor.uid = user.uid
                    monitor.status = "queued"
                    monitor.url = oldmonitor.url
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    monitor.data = tmpdata
                    data['monitor'] = {
                        'cid': monitor.cid,
                        'name': monitor.name,
                        'uid': monitor.uid,
                        'ctype': monitor.ctype,
                        'url': monitor.url,
                        'data': monitor.data
                    }
                    reactdefaults = data['monitor']['data']['reactions']
                    # Check if the user already exceeds their limit
                    if oldmonitor.uid == user.uid:
                        # Create the monitor if all checks out
                        results = monitor.editMonitor(g.rdb_conn)
                    else:
                        results = "NotYours"
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: not users".format(cname))
                        flash("This Monitor doesn't appear to be yours.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: exists".format(cname))
                        flash('This monitor seems to already exist. \
                               Try using a different name.', 'danger')
                    elif results is False:
                        print("/dashboard/edit-monitors/{0} - Monitor \
                              edit failed: unknown reason".format(cname))
                        flash('Could not edit monitor.', 'danger')
                    elif results == 'toomany':
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Too many health checks',
                            1)
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: too many".format(cname))
                        flash('You have too many monitors. \
                              Please upgrade your plan or clean \
                              up old ones.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Monitor Added',
                            1
                        )
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit successful").format(cname)
                        flash('Monitor "{0}" successfully edited'.format(
                            monitor.name), 'success')
                else:
                    print("/dashboard/edit-monitors/{0} - \
                          Monitor edit failed: Form invalid".format(cname))
                    flash('Form is not valid.', 'danger')
            # Process form to display defaults
            if form.__contains__("timer"):
                form.timer.default = data['monitor']['data']['timer']
            form.reactions.default = reactdefaults
            form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))

Example 24

Project: runbook
Source File: views.py
View license
@reaction_blueprint.route(
    '/dashboard/reactions/<rname>', methods=['GET', 'POST'])
def addreaction_page(rname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.config = app.config
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                            Reaction creation failed: exists".format(rname))
                        flash('{0} seems to already exist. Try using a \
                              different name.'.format(reaction.name), 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - Reaction \
                              edit failed: doesn't exist".format(rname))
                        flash('{0} cannot be edited as it does not \
                              exist.'.format(reaction.name), 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited: {0}.'.format(
                            reaction.name), 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited: {0}.'.format(
                            reaction.name), 'danger')
                    elif results == "toomany":
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: too many".format(rname))
                        flash('Could not create reaction: \
                              Too many reactions already created.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction creation successful".format(rname))
                        flash('Reaction "{0}" successfully added.'.format(
                            reaction.name), 'success')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction creation failed: form invalid".format(rname))
                    flash('Form is not valid.', 'success')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))

Example 25

Project: runbook
Source File: views.py
View license
@reaction_blueprint.route(
    '/dashboard/edit-reactions/<rname>/<rid>', methods=['GET', 'POST'])
def editreact_page(rname, rid):
    ''' This is a generic edit page for reactions '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-reactions/' + rname + '/' + rid
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js', ]
        data['edit'] = True
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            reaction = Reaction()
            reaction.config = app.config
            # If Edit get information
            reaction.get("rid", rid, g.rdb_conn)
            if reaction.uid == user.uid:
                data['reaction'] = {
                    'rid': reaction.rid,
                    'name': reaction.name,
                    'trigger': reaction.trigger,
                    'frequency': reaction.frequency,
                    'uid': reaction.uid,
                    'rtype': reaction.rtype,
                    'data': reaction.data
                }
            data['selects'] = []
            for item in form.__iter__():
                if item.type == "SelectField" or \
                        item.type == "SelectMultipleField":
                    item.default = data['reaction']['data'][item.name]
            tmpl = 'reactions/create.html'
            if request.method == 'POST':
                if form.validate():
                    reaction2 = Reaction()
                    reaction2.config = app.config
                    reaction2.rid = reaction.rid
                    reaction2.name = form.name.data
                    reaction2.trigger = form.trigger.data
                    reaction2.frequency = form.frequency.data
                    reaction2.lastrun = reaction.lastrun
                    reaction2.uid = user.uid
                    reaction2.rtype = reaction.rtype
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    reaction2.data = tmpdata

                    data['reaction'] = {
                        'rid': reaction2.rid,
                        'name': reaction2.name,
                        'trigger': reaction2.trigger,
                        'frequency': reaction2.frequency,
                        'uid': reaction2.uid,
                        'rtype': reaction2.rtype,
                        'data': reaction2.data
                    }
                    if reaction.uid == user.uid:
                        results = reaction2.editReaction(g.rdb_conn)
                    else:
                        results = False
                        print("/dashboard/reactions/{0} - \
                            Reaction edit failed: not owner".format(rname))
                        flash("It doesn't appear that you own this reaction.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction seems to already exist. \
                              Try using a different name.', 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction can not be edited \
                              as it does not exist.', 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited.', 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction edit success".format(rname))
                        flash('Reaction "{0}" successfully \
                              added.'.format(reaction2.name), 'danger')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction edit failed: form invalid".format(rname))
                    flash('Form is not valid.', 'danger')
        form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))

Example 26

Project: sagenb
Source File: authentication.py
View license
@authentication.route('/register', methods = ['GET','POST'])
@with_lock
def register():
    if not g.notebook.user_manager().get_accounts():
        return redirect(url_for('base.index'))
    from sagenb.notebook.misc import is_valid_username, is_valid_password, \
    is_valid_email, do_passwords_match
    from sagenb.notebook.challenge import challenge

    # VALIDATORS: is_valid_username, is_valid_password,
    # do_passwords_match, is_valid_email,
    # challenge.is_valid_response
    # INPUT NAMES: username, password, retype_password, email +
    # challenge fields

    # TEMPLATE VARIABLES: error, username, username_missing,
    # username_taken, username_invalid, password_missing,
    # password_invalid, passwords_dont_match,
    # retype_password_missing, email, email_missing,
    # email_invalid, email_address, challenge, challenge_html,
    # challenge_missing, challenge_invalid

    # PRE-VALIDATION setup and hooks.
    required = set(['username', 'password'])
    empty = set()
    validated = set()

    # Template variables.  We use empty_form_dict for empty forms.
    empty_form_dict = {}
    template_dict = {}

    if g.notebook.conf()['email']:
        required.add('email')
        empty_form_dict['email'] = True

    if g.notebook.conf()['challenge']:
        required.add('challenge')
        empty_form_dict['challenge'] = True
        chal = challenge(g.notebook.conf(),
                         is_secure = g.notebook.secure,
                         remote_ip = request.environ['REMOTE_ADDR'])
        empty_form_dict['challenge_html'] = chal.html()

    template_dict.update(empty_form_dict)

    # VALIDATE FIELDS.

    # Username.  Later, we check if a user with this username
    # already exists.
    username = request.values.get('username', None)
    if username:
        if not is_valid_username(username):
            template_dict['username_invalid'] = True
        elif g.notebook.user_manager().user_exists(username):
            template_dict['username_taken'] = True
        else:
            template_dict['username'] = username
            validated.add('username')
    else:
        template_dict['username_missing'] = True
        empty.add('username')

    # Password.
    password = request.values.get('password', None)
    retype_password = request.values.get('retype_password', None)
    if password:
        if not is_valid_password(password, username):
            template_dict['password_invalid'] = True
        elif not do_passwords_match(password, retype_password):
            template_dict['passwords_dont_match'] = True
        else:
            validated.add('password')
    else:
        template_dict['password_missing'] = True
        empty.add('password')

    # Email address.
    email_address = ''
    if g.notebook.conf()['email']:
        email_address = request.values.get('email', None)
        if email_address:
            if not is_valid_email(email_address):
                template_dict['email_invalid'] = True
            else:
                template_dict['email_address'] = email_address
                validated.add('email')
        else:
            template_dict['email_missing'] = True
            empty.add('email')

    # Challenge (e.g., reCAPTCHA).
    if g.notebook.conf()['challenge']:
        status = chal.is_valid_response(req_args = request.values)
        if status.is_valid is True:
            validated.add('challenge')
        elif status.is_valid is False:
            err_code = status.error_code
            if err_code:
                template_dict['challenge_html'] = chal.html(error_code = err_code)
            else:
                template_dict['challenge_invalid'] = True
        else:
            template_dict['challenge_missing'] = True
            empty.add('challenge')

    # VALIDATE OVERALL.
    if empty == required:
        # All required fields are empty.  Not really an error.
        return render_template(os.path.join('html', 'accounts', 'registration.html'),
                               **empty_form_dict)
    elif validated != required:
        # Error(s)!
        errors = len(required) - len(validated)
        template_dict['error'] = 'E ' if errors == 1 else 'Es '
        return render_template(os.path.join('html', 'accounts', 'registration.html'),
                        **template_dict)

    # Create an account, if username is unique.
    try:
        g.notebook.user_manager().add_user(username, password, email_address)
    except ValueError:
        template_dict['username_taken'] = True
        template_dict['error'] = 'E '

        form = render_template(os.path.join('html', 'accounts', 'registration.html'),
                        **template_dict)
        return HTMLResponse(stream = form)

    #XXX: Add logging support
    #log.msg("Created new user '%s'"%username)

    # POST-VALIDATION hooks.  All required fields should be valid.
    if g.notebook.conf()['email']:
        from sagenb.notebook.smtpsend import send_mail
        from sagenb.notebook.register import make_key, build_msg

        # TODO: make this come from the server settings
        key = make_key()
        listenaddr = g.notebook.interface
        port = g.notebook.port
        fromaddr = '[email protected]%s' % listenaddr
        body = build_msg(key, username, listenaddr, port, g.notebook.secure)

        # Send a confirmation message to the user.
        try:
            send_mail(fromaddr, email_address,
                      _("Sage Notebook Registration"), body)
            waiting[key] = username
        except ValueError:
            pass

    # Go to the login page.
    from sagenb.misc.misc import SAGE_VERSION
    template_dict = {'accounts': g.notebook.user_manager().get_accounts(),
                     'welcome_user': username,
                     'recovery': g.notebook.conf()['email'],
                     'sage_version': SAGE_VERSION}

    return render_template(os.path.join('html', 'login.html'), **template_dict)

Example 27

Project: sagenb
Source File: base.py
View license
@base.route('/openid_profiles', methods=['POST','GET'])
def set_profiles():
    if not g.notebook.conf()['openid']:
        return redirect(url_for('base.index'))

    from sagenb.notebook.challenge import challenge


    show_challenge=g.notebook.conf()['challenge']
    if show_challenge:
        chal = challenge(g.notebook.conf(),
                         is_secure = g.notebook.secure,
                         remote_ip = request.environ['REMOTE_ADDR'])

    if request.method == 'GET':
        if 'openid_response' in session:
            from sagenb.notebook.misc import valid_username_chars
            re_invalid_username_chars = re.compile('[^(%s)]' % valid_username_chars)
            openid_resp = session['openid_response']
            if openid_resp.fullname is not None:
                openid_resp.fullname = re.sub(re_invalid_username_chars, '_', openid_resp.fullname)
            template_dict={}
            if show_challenge:
                template_dict['challenge_html'] = chal.html()

            return render_template('html/accounts/openid_profile.html', resp=openid_resp,
                                   challenge=show_challenge, **template_dict)
        else:
            return redirect(url_for('base.index'))


    if request.method == 'POST':
        if 'openid_response' in session:
            parse_dict = {'resp':session['openid_response']}
        else:
            return redirect(url_for('base.index'))

        try:
            resp = session['openid_response']
            username = request.form.get('username')
            from sagenb.notebook.user import User
            from sagenb.notebook.misc import is_valid_username, is_valid_email

            if show_challenge:
                parse_dict['challenge'] = True
                status = chal.is_valid_response(req_args = request.values)
                if status.is_valid is True:
                    pass
                elif status.is_valid is False:
                    err_code = status.error_code
                    if err_code:
                        parse_dict['challenge_html'] = chal.html(error_code = err_code)
                    else:
                        parse_dict['challenge_invalid'] = True
                    raise ValueError("Invalid challenge")
                else:
                    parse_dict['challenge_missing'] = True
                    raise ValueError("Missing challenge")

            if not is_valid_username(username):
                parse_dict['username_invalid'] = True
                raise ValueError("Invalid username")
            if g.notebook.user_manager().user_exists(username):
                parse_dict['username_taken'] = True
                raise ValueError("Pre-existing username")
            if not is_valid_email(request.form.get('email')):
                parse_dict['email_invalid'] = True
                raise ValueError("Invalid email")
            try:
                new_user = User(username, '', email = resp.email, account_type='user')
                g.notebook.user_manager().add_user_object(new_user)
            except ValueError as msg:
                parse_dict['creation_error'] = True
                raise ValueError("Error in creating user\n%s"%msg)
            g.notebook.user_manager().create_new_openid(resp.identity_url, username)
            session['username'] = g.username = username
            session.modified = True
        except ValueError:
            return render_template('html/accounts/openid_profile.html', **parse_dict)
        return redirect(url_for('base.index'))

Example 28

Project: sagenb
Source File: settings.py
View license
@settings.route('/settings', methods = ['GET','POST'])
@login_required
@with_lock
def settings_page():
    from sagenb.notebook.misc import is_valid_password, is_valid_email
    from sagenb.misc.misc import SAGE_VERSION
    error = None
    redirect_to_home = None
    redirect_to_logout = None
    nu = g.notebook.user_manager().user(g.username)

    autosave = int(request.values.get('autosave', 0))*60
    if autosave:
        nu['autosave_interval'] = autosave
        redirect_to_home = True

    old = request.values.get('old-pass', None)
    new = request.values.get('new-pass', None)
    two = request.values.get('retype-pass', None)

    if new or two:
        if not old:
            error = _('Old password not given')
        elif not g.notebook.user_manager().check_password(g.username, old):
            error = _('Incorrect password given')
        elif not new:
            error = _('New password not given')
        elif not is_valid_password(new, g.username):
            error = _('Password not acceptable. Must be 4 to 32 characters and not contain spaces or username.')
        elif not two:
            error = _('Please type in new password again.')
        elif new != two:
            error = _('The passwords you entered do not match.')

        if not error:
            # The browser may auto-fill in "old password," even
            # though the user may not want to change her password.
            g.notebook.user_manager().set_password(g.username, new)
            redirect_to_logout = True

    if g.notebook.conf()['email']:
        newemail = request.values.get('new-email', None)
        if newemail:
            if is_valid_email(newemail):
                nu.set_email(newemail)
                ##nu.set_email_confirmation(False)
                redirect_to_home = True
            else:
                error = _('Invalid e-mail address.')

    if error:
        return current_app.message(error, url_for('settings_page'), username=g.username)

    if redirect_to_logout:
        return redirect(url_for('authentication.logout'))

    if redirect_to_home:
        return redirect(url_for('worksheet_listing.home', username=g.username))

    td = {}
    td['sage_version'] = SAGE_VERSION
    td['username'] = g.username

    td['autosave_intervals'] = ((i, ' selected') if nu['autosave_interval']/60 == i else (i, '') for i in range(1, 10, 2))

    td['email'] = g.notebook.conf()['email']
    if td['email']:
        td['email_address'] = nu.get_email() or 'None'
        if nu.is_email_confirmed():
            td['email_confirmed'] = _('Confirmed')
        else:
            td['email_confirmed'] = _('Not confirmed')

    td['admin'] = nu.is_admin()

    return render_template(os.path.join('html', 'settings', 'account_settings.html'), **td)

Example 29

Project: sagenb
Source File: worksheet_listing.py
View license
@worksheet_listing.route('/upload_worksheet', methods=['GET', 'POST'])
@login_required
def upload_worksheet():
    from sage.misc.all import tmp_filename, tmp_dir
    from werkzeug.utils import secure_filename
    import zipfile

    if g.notebook.readonly_user(g.username):
        return current_app.message(_("Account is in read-only mode"), cont=url_for('home', username=g.username), username=g.username)

    backlinks = _("""Return to <a href="/upload" title="Upload a worksheet"><strong>Upload File</strong></a>.""")

    url = request.values['url'].strip()
    dir = ''
    if url != '':
        #Downloading a file from the internet
        # The file will be downloaded from the internet and saved
        # to a temporary file with the same extension
        path = urlparse.urlparse(url).path
        extension = os.path.splitext(path)[1].lower()
        if extension not in ["", ".txt", ".sws", ".zip", ".html", ".rst"]:
            # Or shall we try to import the document as an sws when in doubt?
            return current_app.message(_("Unknown worksheet extension: %(ext)s. %(links)s", ext=extension, links=backlinks), username=g.username)
        filename = tmp_filename()+extension
        try:
            import re
            matches = re.match("file://(?:localhost)?(/.+)", url)
            if matches:
                if g.notebook.interface != 'localhost':
                    return current_app.message(_("Unable to load file URL's when not running on localhost.\n%(backlinks)s",backlinks=backlinks), username=g.username)

                import shutil
                shutil.copy(matches.group(1),filename)
            else:
                my_urlretrieve(url, filename, backlinks=backlinks)

        except RetrieveError as err:
            return current_app.message(str(err), username=g.username)

    else:
        #Uploading a file from the user's computer
        dir = tmp_dir()
        file = request.files['file']
        if file.filename is None:
            return current_app.message(_("Please specify a worksheet to load.\n%(backlinks)s",backlinks=backlinks), username=g.username)

        filename = secure_filename(file.filename)
        if len(filename)==0:
            return current_app.message(_("Invalid filename.\n%(backlinks)s",backlinks=backlinks), username=g.username)

        filename = os.path.join(dir, filename)
        file.save(filename)

    new_name = request.values.get('name', None)

    try:
        try:
            if filename.endswith('.zip'):
                # Extract all the .sws files from a zip file.
                zip_file = zipfile.ZipFile(filename)
                for subfilename in zip_file.namelist():
                    prefix, extension = os.path.splitext(subfilename)
                    # Mac zip files contain files like __MACOSX/._worksheet.sws
                    # which are metadata files, so we skip those as
                    # well as any other files we won't understand
                    if extension in ['.sws', '.html', '.txt', '.rst'] and not prefix.startswith('__MACOSX/'):
                        tmpfilename = os.path.join(dir, "tmp" + extension)
                        try:
                            tmpfilename = zip_file.extract(subfilename, tmpfilename)
                        except AttributeError:
                            open(tmpfilename, 'w').write(zip_file.read(subfilename))
                        W = g.notebook.import_worksheet(tmpfilename, g.username)
                        if new_name:
                            W.set_name("%s - %s" % (new_name, W.name()))
                    else:
                        print("Unknown extension, file %s is ignored" % subfilename)
                return redirect(url_for('home', username=g.username))

            else:
                if url and extension in ['', '.html']:
                    linked_sws = parse_link_rel(url, filename)
                    if linked_sws:
                        # just grab 1st URL; perhaps later add interface for
                        # downloading multiple linked .sws
                        try:
                            filename = my_urlretrieve(linked_sws[0]['url'], backlinks=backlinks)[0]
                            print('Importing {0}, linked to from {1}'.format(linked_sws[0]['url'], url))
                        except RetrieveError as err:
                            return current_app.message(str(err), username=g.username)
                W = g.notebook.import_worksheet(filename, g.username)
        except Exception as msg:
            print('error uploading worksheet {}'.format(msg))
            s = _('There was an error uploading the worksheet.  It could be an old unsupported format or worse.  If you desperately need its contents contact the <a href="http://groups.google.com/group/sage-support">sage-support group</a> and post a link to your worksheet.  Alternatively, an sws file is just a bzip2 tarball; take a look inside!\n%(backlinks)s', backlinks=backlinks)
            return current_app.message(s, url_for('home', username=g.username), username=g.username)
        finally:
            # Clean up the temporarily uploaded filename.
            os.unlink(filename)
            # if a temp directory was created, we delete it now.
            if dir:
                import shutil
                shutil.rmtree(dir)

    except ValueError as msg:
        s = _("Error uploading worksheet '%(msg)s'.%(backlinks)s", msg=msg, backlinks=backlinks)
        return current_app.message(s, url_for('home', username=g.username), username=g.username)

    if new_name:
        W.set_name(new_name)

    from .worksheet import url_for_worksheet
    return redirect(url_for_worksheet(W))

Example 30

Project: rentmybikes
Source File: list.py
View license
@route('/list', 'listing.create', methods=['POST'])
@validate(ListingForm, prefix='listing')
@validate(GuestListingForm, prefix='guest')
@validate(BankAccountForm)
def create(**kwargs):
    manager = ListingManager(request)

    forms = kwargs.pop('forms')
    listing_form = find_form(forms, ListingForm)
    guest_listing_form = find_form(forms, GuestListingForm)
    bank_account_form = find_form(forms, BankAccountForm)

    if request.user.is_authenticated:
        form = listing_form
    else:
        form = guest_listing_form
        session['email'] = form.email.data

    if not form.validate():
        return index(**kwargs)

    try:
        listing_id = manager.create(form, bank_account_form)
    except balanced.exc.HTTPError as ex:
        if ex.status_code == 300:
            # we've created the user locally, persist this information
            Session.commit()

            return redirect(url_for('redirect.show',
                listing=form.listing_id.data,
                redirect_uri=ex.response.headers['location'],
                email=session.get('email')))
        elif ex.status_code == 400:
            if 'merchant.postal_code' in ex.description:
                form['postal_code'].errors.append(ex.description)
                return index(**kwargs)
            elif 'merchant.phone' in ex.description:
                form['phone'].errors.append(ex.description)
                return index(**kwargs)
        raise
    except Exception as ex:
        if ex.message == 'Password mismatch':
            flash('Sorry, this email address is already assigned to an '
                'account and your password does not match, please try '
                'again.', 'error')
            return self.index(**kwargs)
        raise

    Session.commit()

    return redirect(url_for('listing.complete', listing=listing_id))

Example 31

Project: pybossa
Source File: account.py
View license
@blueprint.route('/<name>/update', methods=['GET', 'POST'])
@login_required
def update_profile(name):
    """
    Update user's profile.

    Returns Jinja2 template.

    """
    user = user_repo.get_by_name(name)
    if not user:
        return abort(404)
    ensure_authorized_to('update', user)
    show_passwd_form = True
    if user.twitter_user_id or user.google_user_id or user.facebook_user_id:
        show_passwd_form = False
    usr = cached_users.get_user_summary(name)
    # Extend the values
    user.rank = usr.get('rank')
    user.score = usr.get('score')
    if request.form.get('btn') != 'Profile':
        update_form = UpdateProfileForm(formdata=None, obj=user)
    else:
        update_form = UpdateProfileForm(obj=user)
    update_form.set_locales(current_app.config['LOCALES'])
    avatar_form = AvatarUploadForm()
    password_form = ChangePasswordForm()

    title_msg = "Update your profile: %s" % user.fullname

    if request.method == 'POST':
        # Update user avatar
        succeed = False
        if request.form.get('btn') == 'Upload':
            succeed = _handle_avatar_update(user, avatar_form)
        # Update user profile
        elif request.form.get('btn') == 'Profile':
            succeed = _handle_profile_update(user, update_form)
        # Update user password
        elif request.form.get('btn') == 'Password':
            succeed = _handle_password_update(user, password_form)
        # Update user external services
        elif request.form.get('btn') == 'External':
            succeed = _handle_external_services_update(user, update_form)
        # Otherwise return 415
        else:
            return abort(415)
        if succeed:
            return redirect(url_for('.update_profile', name=user.name))
        else:
            return render_template('/account/update.html',
                                   form=update_form,
                                   upload_form=avatar_form,
                                   password_form=password_form,
                                   title=title_msg,
                                   show_passwd_form=show_passwd_form)

    return render_template('/account/update.html',
                           form=update_form,
                           upload_form=avatar_form,
                           password_form=password_form,
                           title=title_msg,
                           show_passwd_form=show_passwd_form)

Example 32

Project: ldapass
Source File: ldapass.py
View license
@app.route('/reset/<link_id>', methods=['GET', 'POST'])
def reset(link_id):
    error = None
    form = PasswordForm(request.form)

    db_conn = sqlite3.connect(conf.get('app', 'database'))
    db_curs = db_conn.cursor()
    db_curs.execute("SELECT * FROM mails WHERE link_id='{link_id}'".format(
        link_id=link_id))
    db_data = db_curs.fetchall()

    if len(db_data) == 1:
        if request.method == 'GET':
            flash(
                'You are changing password for the account of {mail}'.format(
                    mail=db_data[0][1]))
            return render_template(
                'reset.html',
                error=error,
                form=form,
                link_id=link_id)

        if request.method == 'POST':
            if form.validate():
                ldap_uri = 'ldap://{addr}:{port}'.format(
                    addr=conf.get('ldap', 'addr'),
                    port=conf.get('ldap', 'port')
                )
                try:
                    ldap.set_option(
                        ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
                    l = ldap.initialize(
                        ldap_uri, trace_level=conf.get('app', 'ldap_debug'))
                    l.start_tls_s()
                except ldap.LDAPError as error:
                    return render_template('error.html', error=error)
                try:
                    search_filter = 'mail={mail}'.format(mail=db_data[0][1])
                    ldap_result_id = l.search(
                        conf.get('ldap', 'basedn'),
                        ldap.SCOPE_SUBTREE,
                        search_filter,
                        None)
                    result_type, result_data = l.result(ldap_result_id, 0)
                    l.simple_bind_s(
                        conf.get('ldap', 'user'), conf.get('ldap', 'pass'))
                    l.passwd_s(
                        'uid={uid},{basedn}'.format(
                            uid=result_data[0][1]['uid'][0],
                            basedn=conf.get('ldap', 'basedn')),
                        None,
                        '{passwd}'.format(passwd=form.passwd.data))
                except ldap.LDAPError as error:
                    error = 'LDAP error: {error}, please get in touch with \
                        LDAP administration.'.format(error=error)
                    return render_template(
                        'reset.html',
                        error=error,
                        form=form
                    )
                flash('Password for account {mail} has been changed.'.format(
                    mail=db_data[0][1]))
                db_curs.execute(
                    "DELETE FROM mails WHERE link_id='{link_id}'".format(
                        link_id=link_id))
                db_conn.commit()
                db_conn.close()
                return redirect(url_for('index'))
            else:
                error = 'The form is invalid, please try again.'
                return render_template('reset.html', error=error, form=form)
    else:
        db_conn.close()
        error = 'There is no such password reset id {link_id}'.format(
            link_id=link_id)
        return render_template('error.html', error=error)

Example 33

Project: flask-caching
Source File: __init__.py
View license
    def cached(self, timeout=None, key_prefix='view/%s', unless=None,
               forced_update=None):
        """Decorator. Use this to cache a function. By default the cache key
        is `view/request.path`. You are able to use this decorator with any
        function by changing the `key_prefix`. If the token `%s` is located
        within the `key_prefix` then it will replace that with `request.path`

        Example::

            # An example view function
            @cache.cached(timeout=50)
            def big_foo():
                return big_bar_calc()

            # An example misc function to cache.
            @cache.cached(key_prefix='MyCachedList')
            def get_list():
                return [random.randrange(0, 1) for i in range(50000)]

            my_list = get_list()

        .. note::

            You MUST have a request context to actually called any functions
            that are cached.

        .. versionadded:: 0.4
            The returned decorated function now has three function attributes
            assigned to it. These attributes are readable/writable.

                **uncached**
                    The original undecorated function

                **cache_timeout**
                    The cache timeout value for this function. For a
                    custom value to take affect, this must be set before the
                    function is called.

                **make_cache_key**
                    A function used in generating the cache_key used.

        :param timeout: Default None. If set to an integer, will cache for that
                        amount of time. Unit of time is in seconds.

        :param key_prefix: Default 'view/%(request.path)s'. Beginning key to .
                           use for the cache key. `request.path` will be the
                           actual request path, or in cases where the
                           `make_cache_key`-function is called from other
                           views it will be the expected URL for the view
                           as generated by Flask's `url_for()`.

                           .. versionadded:: 0.3.4
                               Can optionally be a callable which takes
                               no arguments but returns a string that will
                               be used as the cache_key.

        :param unless: Default None. Cache will *always* execute the caching
                       facilities unless this callable is true.
                       This will bypass the caching entirely.

        :param forced_update: Default None. If this callable is true,
                              cache value will be updated regardless cache
                              is expired or not. Useful for background
                              renewal of cached functions.
        """

        def decorator(f):
            @functools.wraps(f)
            def decorated_function(*args, **kwargs):
                #: Bypass the cache entirely.
                if self._bypass_cache(unless, f, *args, **kwargs):
                    return f(*args, **kwargs)

                try:
                    cache_key = _make_cache_key(args, kwargs, use_request=True)

                    if callable(forced_update) and forced_update() is True:
                        rv = None
                    else:
                        rv = self.cache.get(cache_key)
                except Exception:
                    if current_app.debug:
                        raise
                    logger.exception("Exception possibly due to "
                                     "cache backend.")
                    return f(*args, **kwargs)

                if rv is None:
                    rv = f(*args, **kwargs)
                    try:
                        self.cache.set(
                            cache_key, rv,
                            timeout=decorated_function.cache_timeout
                        )
                    except Exception:
                        if current_app.debug:
                            raise
                        logger.exception("Exception possibly due to "
                                         "cache backend.")
                return rv

            def make_cache_key(*args, **kwargs):
                # Convert non-keyword arguments (which is the way
                # `make_cache_key` expects them) to keyword arguments
                # (the way `url_for` expects them)
                argspec = inspect.getargspec(f)
                for arg_name, arg in zip(argspec.args, args):
                    kwargs[arg_name] = arg

                return _make_cache_key(args, kwargs, use_request=False)

            def _make_cache_key(args, kwargs, use_request):
                if callable(key_prefix):
                    cache_key = key_prefix()
                elif '%s' in key_prefix:
                    if use_request:
                        cache_key = key_prefix % request.path
                    else:
                        cache_key = key_prefix % url_for(f.__name__, **kwargs)
                else:
                    cache_key = key_prefix

                return cache_key

            decorated_function.uncached = f
            decorated_function.cache_timeout = timeout
            decorated_function.make_cache_key = make_cache_key

            return decorated_function
        return decorator

Example 34

Project: flaskbb
Source File: views.py
View license
@forum.route("/forum/<int:forum_id>/edit", methods=["POST", "GET"])
@forum.route("/forum/<int:forum_id>-<slug>/edit", methods=["POST", "GET"])
@login_required
def manage_forum(forum_id, slug=None):
    page = request.args.get('page', 1, type=int)

    forum_instance, forumsread = Forum.get_forum(forum_id=forum_id,
                                                 user=current_user)

    # remove the current forum from the select field (move).
    available_forums = Forum.query.order_by(Forum.position).all()
    available_forums.remove(forum_instance)

    if not Permission(IsAtleastModeratorInForum(forum=forum_instance)):
        flash(_("You do not have the permissions to moderate this forum."),
              "danger")
        return redirect(forum_instance.url)

    if forum_instance.external:
        return redirect(forum_instance.external)

    topics = Forum.get_topics(
        forum_id=forum_instance.id, user=current_user, page=page,
        per_page=flaskbb_config["TOPICS_PER_PAGE"]
    )

    mod_forum_url = url_for("forum.manage_forum", forum_id=forum_instance.id,
                            slug=forum_instance.slug)

    # the code is kind of the same here but it somehow still looks cleaner than
    # doin some magic
    if request.method == "POST":
        ids = request.form.getlist("rowid")
        tmp_topics = Topic.query.filter(Topic.id.in_(ids)).all()

        if not len(tmp_topics) > 0:
            flash(_("In order to perform this action you have to select at "
                    "least one topic."), "danger")
            return redirect(mod_forum_url)

        # locking/unlocking
        if "lock" in request.form:
            changed = do_topic_action(topics=tmp_topics, user=current_user,
                                      action="locked", reverse=False)

            flash(_("%(count)s topics locked.", count=changed), "success")
            return redirect(mod_forum_url)

        elif "unlock" in request.form:
            changed = do_topic_action(topics=tmp_topics, user=current_user,
                                      action="locked", reverse=True)
            flash(_("%(count)s topics unlocked.", count=changed), "success")
            return redirect(mod_forum_url)

        # highlighting/trivializing
        elif "highlight" in request.form:
            changed = do_topic_action(topics=tmp_topics, user=current_user,
                                      action="important", reverse=False)
            flash(_("%(count)s topics highlighted.", count=changed), "success")
            return redirect(mod_forum_url)

        elif "trivialize" in request.form:
            changed = do_topic_action(topics=tmp_topics, user=current_user,
                                      action="important", reverse=True)
            flash(_("%(count)s topics trivialized.", count=changed), "success")
            return redirect(mod_forum_url)

        # deleting
        elif "delete" in request.form:
            changed = do_topic_action(topics=tmp_topics, user=current_user,
                                      action="delete", reverse=False)
            flash(_("%(count)s topics deleted.", count=changed), "success")
            return redirect(mod_forum_url)

        # moving
        elif "move" in request.form:
            new_forum_id = request.form.get("forum")

            if not new_forum_id:
                flash(_("Please choose a new forum for the topics."), "info")
                return redirect(mod_forum_url)

            new_forum = Forum.query.filter_by(id=new_forum_id).first_or_404()
            # check the permission in the current forum and in the new forum

            if not Permission(
                And(
                    IsAtleastModeratorInForum(forum_id=new_forum_id),
                    IsAtleastModeratorInForum(forum=forum_instance)
                )
            ):
                flash(_("You do not have the permissions to move this topic."),
                      "danger")
                return redirect(mod_forum_url)

            new_forum.move_topics_to(tmp_topics)
            return redirect(mod_forum_url)

    return render_template(
        "forum/edit_forum.html", forum=forum_instance, topics=topics,
        available_forums=available_forums, forumsread=forumsread,
    )

Example 35

Project: flaskbb
Source File: views.py
View license
@message.route("/<int:conversation_id>/view", methods=["GET", "POST"])
def view_conversation(conversation_id):
    conversation = Conversation.query.filter_by(
        id=conversation_id,
        user_id=current_user.id
    ).first_or_404()

    if conversation.unread:
        conversation.unread = False
        current_user.invalidate_cache(permissions=False)
        conversation.save()

    form = MessageForm()
    if form.validate_on_submit():

        message_count = Conversation.query.\
            filter(Conversation.user_id == current_user.id).\
            count()

        if message_count >= flaskbb_config["MESSAGE_QUOTA"]:
            flash(_("You cannot send any messages anymore because you have "
                    "reached your message limit."), "danger")
            return redirect(url_for("message.view_conversation",
                                    conversation_id=conversation.id))

        to_user_id = None
        # If the current_user is the user who recieved the message
        # then we have to change the id's a bit.
        if current_user.id == conversation.to_user_id:
            to_user_id = conversation.from_user_id
        else:
            to_user_id = conversation.to_user_id

        form.save(conversation=conversation, user_id=current_user.id)

        # save the message in the recievers conversation
        old_conv = conversation
        conversation = Conversation.query.\
            filter(
                Conversation.user_id == to_user_id,
                Conversation.shared_id == conversation.shared_id
            ).first()

        # user deleted the conversation, start a new conversation with just
        # the recieving message
        if conversation is None:
            conversation = Conversation(
                subject=old_conv.subject,
                from_user_id=current_user.id,
                to_user=to_user_id,
                user_id=to_user_id,
                shared_id=old_conv.shared_id
            )
            conversation.save()

        form.save(conversation=conversation, user_id=current_user.id,
                  unread=True)
        conversation.to_user.invalidate_cache(permissions=False)

        return redirect(url_for("message.view_conversation",
                                conversation_id=old_conv.id))

    return render_template("message/conversation.html",
                           conversation=conversation, form=form)

Example 36

Project: flask-dance
Source File: oauth2.py
View license
    def authorized(self):
        if "next" in request.args:
            next_url = request.args["next"]
        elif self.redirect_url:
            next_url = self.redirect_url
        elif self.redirect_to:
            next_url = url_for(self.redirect_to)
        else:
            next_url = "/"
        log.debug("next_url = %s", next_url)

        # check for error in request args
        error = request.args.get("error")
        if error:
            error_desc = request.args.get("error_description")
            error_uri = request.args.get("error_uri")
            log.warning(
                "OAuth 2 authorization error: %s description: %s uri: %s",
                error, error_desc, error_uri,
            )
            oauth_error.send(self,
                error=error, error_description=error_desc, error_uri=error_uri,
            )
            return redirect(next_url)

        state_key = "{bp.name}_oauth_state".format(bp=self)
        if state_key not in flask.session:
            # can't validate state, so redirect back to login view
            log.info("state not found, redirecting user to login")
            return redirect(url_for(".login"))

        state = flask.session[state_key]
        log.debug("state = %s", state)
        self.session._state = state
        del flask.session[state_key]

        self.session.redirect_uri = url_for(
            ".authorized", next=request.args.get('next'), _external=True,
        )

        log.debug("client_id = %s", self.client_id)
        log.debug("client_secret = %s", self.client_secret)
        try:
            token = self.session.fetch_token(
                self.token_url,
                authorization_response=request.url,
                client_secret=self.client_secret,
                **self.token_url_params
            )
        except MissingCodeError as e:
            e.args = (
                e.args[0],
                "The redirect request did not contain the expected parameters. Instead I got: {}".format(
                    json.dumps(request.args)
                )
            )
            raise

        results = oauth_authorized.send(self, token=token) or []
        set_token = True
        for func, ret in results:
            if isinstance(ret, (Response, current_app.response_class)):
                return ret
            if ret == False:
                set_token = False

        if set_token:
            self.token = token
        return redirect(next_url)

Example 37

Project: sopython-site
Source File: __init__.py
View license
def create_app(info=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object('sopy.config')
    app.config.from_pyfile('config.py', True)

    app.cli.add_command(alembic_cli, 'db')

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    alembic.init_app(app)
    babel.init_app(app)
    db.init_app(app)

    from sopy.ext import views

    views.init_app(app)

    from sopy import auth, tags, se_data, canon, salad, wiki, pages, admin, transcript, spoiler

    app.register_blueprint(auth.bp, url_prefix='/auth')
    app.register_blueprint(tags.bp, url_prefix='/tags')
    app.register_blueprint(se_data.bp, url_prefix='/se_data')
    app.register_blueprint(canon.bp, url_prefix='/canon')
    app.register_blueprint(salad.bp, url_prefix='/salad')
    app.register_blueprint(wiki.bp, url_prefix='/wiki')
    app.register_blueprint(pages.bp, url_prefix='/pages')
    app.register_blueprint(admin.bp, url_prefix='/admin')
    app.register_blueprint(transcript.bp, url_prefix='/transcript')
    app.register_blueprint(spoiler.bp, url_prefix='/spoiler')

    @app.route('/')
    def index():
        return render_template('index.html')

    app.add_url_rule('/favicon.ico', None, app.send_static_file, defaults={'filename': 'favicon.ico'})
    app.add_url_rule('/robots.txt', None, app.send_static_file, defaults={'filename': 'robots.txt'})

    @app.errorhandler(403)
    def forbidden(e):
        return render_template('errors/403.html'), 403

    @app.errorhandler(404)
    def not_found(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('errors/500.html'), 500

    @app.route('/pycon2016')
    def pycon2016():
        return redirect(url_for('wiki.detail', title='PyCon US 2016'))

    if not app.debug:
        handler = logging.StreamHandler(sys.stderr)
        handler.setLevel(logging.ERROR)
        app.logger.addHandler(handler)

    return app

Example 38

Project: get5-web
Source File: team_test.py
View license
    def test_team_create(self):
        with self.app as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1

            # Make sure we can render the team creation page
            response = c.get('/team/create')
            self.assertEqual(response.status_code, 200)

            # Fill in its form
            response = c.post('/team/create',
                              follow_redirects=False,
                              data={
                                  'name': 'NiP',
                                  'country_flag': 'se',
                                  'auth1': 'STEAM_0:1:52245092',
                              })
            self.assertEqual(response.status_code, 302)
            self.assertEqual(response.location, url_for(
                'team.teams_user', userid=1, _external=True))

        # Make sure the team was actually created
        team = Team.query.filter_by(name='NiP').first()
        self.assertEqual(team.id, 3)  # already 2 test data teams
        self.assertEqual(team.user_id, 1)
        self.assertEqual(team.name, 'NiP')
        self.assertEqual(team.flag, 'se')
        self.assertEqual(team.auths[0], '76561198064755913')
        self.assertTrue(team in User.query.get(1).teams)

        # Should be able to render the teams page
        self.assertEqual(self.app.get('/teams/1').status_code, 200)

        # Edit the team
        with self.app as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1

            # Make sure we can render the team edit page
            response = c.get('/team/3/edit')
            self.assertEqual(response.status_code, 200)

            # Fill in its data
            response = c.post('/team/3/edit',
                              follow_redirects=False,
                              data={
                                  'name': 'NiP2',
                                  'country_flag': 'ru',
                                  'auth1': 'STEAM_0:1:52245092',
                              })
            self.assertEqual(response.status_code, 302)
            self.assertEqual(response.location, url_for(
                'team.teams_user', userid=1, _external=True))

        team = Team.query.get(3)
        self.assertEqual(team.name, 'NiP2')
        self.assertEqual(team.flag, 'ru')

        # Now delete the team
        with self.app as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1

            response = c.get('/team/3/delete')
            self.assertEqual(response.status_code, 302)
        team = Team.query.get(3)
        self.assertIsNone(team)

Example 39

Project: DockCI
Source File: job.py
View license
    def post(self, project_slug, job_slug):
        """ Create a new stream queue for a job """
        job = get_validate_job(project_slug, job_slug)
        routing_key = 'dockci.{project_slug}.{job_slug}.*.*'.format(
            project_slug=project_slug,
            job_slug=job_slug,
        )

        with redis_pool() as redis_pool_:
            with pika_conn() as pika_conn_:
                channel = pika_conn_.channel()
                queue_result = channel.queue_declare(
                    queue='dockci.job.%s' % uuid.uuid4().hex,
                    arguments={
                        'x-expires': CONFIG.live_log_session_timeout,
                        'x-message-ttl': CONFIG.live_log_message_timeout,
                    },
                    durable=False,
                )

                redis_conn = redis.Redis(connection_pool=redis_pool_)
                with redis_lock.Lock(
                    redis_conn,
                    redis_lock_name(job),
                    expire=5,
                ):
                    channel.queue_bind(
                        exchange='dockci.job',
                        queue=queue_result.method.queue,
                        routing_key=routing_key,
                    )

                    try:
                        stage = job.job_stages[-1]

                    except IndexError:
                        stage = None
                        bytes_read = 0

                    else:
                        bytes_read = redis_conn.get(
                            redis_len_key(stage)
                        )

                        # Sometimes Redis gives us bytes :\
                        try:
                            bytes_read = bytes_read.decode()
                        except AttributeError:
                            pass

        return {
            'init_stage': None if stage is None else stage.slug,
            'init_log': None if stage is None else (
                "{url}?count={count}".format(
                    url=url_for(
                        'job_log_init_view',
                        project_slug=project_slug,
                        job_slug=job_slug,
                        stage=stage.slug
                    ),
                    count=bytes_read,
                )
            ),
            'live_queue': queue_result.method.queue,
        }

Example 40

Project: utter-va
Source File: configurehandlers.py
View license
@mod.route('/configure/twitter', methods=['GET', 'POST'])
@login_required
def configure_twitter():
	# check configuration
	settings = Status().check_settings()

	# get the forms for the page
	form = TwitterForm(request.form)
	mrof = BotForm(request.form)

	# blow the flavors into a list
	flavor_list = []
	flavors = Flavors.get_all()
	for flavor in flavors:
		flavor_list.append((flavor.id, flavor.description))
	
	mrof.flavor.choices = flavor_list

	# twitter bot credentials
	bot = TwitterBot.get()

	# initialize the bot if it's not
	if not bot:
		bot = oauth_initialize()
	else:
		if bot.complete == 0:
			bot = oauth_initialize()

		if bot.complete == 1 and request.method == 'GET':
			# ensure we don't use stale creds
			bot = oauth_initialize()

		elif bot.complete == 1 and request.method == 'POST':
			if form.validate_on_submit():
				pin = request.form['pin']
				bot = oauth_complete(pin)
				if bot:
					flash("Authentication with Twitter complete.", "success")
				else:
					flash("Authentication with Twitter failed.", "error")
					bot = TwitterBot.get()
					bot.delete(bot)
					return redirect(url_for(".configure_twitter"))	
			else:
				# form was not valid, so show errors	
				flash("There were form errors. Please check your entries and try again.", "error")
				
		elif request.method == 'POST':
			if mrof.validate_on_submit():
				bot.flavor_id = mrof.flavor.data
				bot.announce = mrof.announce.data
				bot.max_instances = mrof.max_instances.data
				bot.updated = int(time.time())
				bot.update()

				if bot.announce > 0:
					# announce (requires 'settings' in comment to reload stream bot)
					tweet_status("Appliance settings updated. Now serving up to (%s) %s instances via '@%s !status'" % (
							bot.max_instances,
							bot.flavor.name,
							bot.screen_name
						)
					)
				flash("Bot settings updated.", "success")
			else:
				# form was not valid, so show errors	
				flash("There were form errors. Please check your entries and try again.", "error")	

	# no bot not hot
	if not bot:
		flash("Twitterbot failed to contact Twitter or get credentials.", "error")
		bot = None

	else:
		# set default form values
		mrof.flavor.data = bot.flavor_id
		mrof.announce.data = bot.announce

	return render_template(
		'configure/twitter.html',
		bot=bot,
		settings=settings,
		form=form,
		mrof=mrof
	)

Example 41

Project: translator
Source File: __init__.py
View license
@main_module.route('/')
@main_module.route('/tr/<translation_id>')
def index(translation_id=None):
    """The main page."""

    if request.host == 'translator.suminb.com':
        return redirect('http://better-translator.com')

    # NOTE: Do not use HTTP GET parameters 'sl', 'tl', 'm' and 't'. These are
    # reserved for special purposes.

    # FIXME: The following values must exist in other pages as well
    user_agent = request.headers.get('User-Agent', [])
    is_android = 'Android' in user_agent
    is_iphone = 'iPhone' in user_agent
    is_msie = 'MSIE' in user_agent

    context = dict(
        version=__version__,
        locale=get_locale(),
        is_android=is_android,
        is_iphone=is_iphone,
        is_mobile=is_android or is_iphone,
        is_msie=is_msie,
        language_options=language_options_html(),
        debug=os.environ.get('DEBUG', None),
    )

    tresponse = None

    translation_id = translation_id or request.args.get('tr', None)

    #if translation_id != None:
    #    tresponse = TranslationResponse.fetch(id_b62=translation_id)

    if translation_id is not None and tresponse is None:
        return redirect(url_for('main.index'))

    if tresponse is not None:
        translation = tresponse.serialize()
        translation['original_text'] = tresponse.request.original_text
        #translation['translated_text_dictlink'] = link_dictionary(
        #translation['translated_text'], translation['source'], translation['target'])

        context['og_description'] = tresponse.request.original_text
        context['translation'] = json.dumps(translation)
    else:
        context['og_description'] = _('app-description-text')

    return render_template('index.html', **context)

Example 42

Project: flask-optimize
Source File: __init__.py
View license
    def optimize(self, type='html', htmlmin=None, izip=None, cache=None, limit=False, redirect_host=True, exceed_msg=True):
        ''' Flask optimize respond using minify html, zip content and mem cache.
        Elastic optimization and create Cross-site HTTP requests if respond is json
        Args:
            type: respond return type
                -html
                -text
                -json
            htmlmin: minify html
                None is using global config, True is enable minify html
            izip: send content in zip format
                None is using global config, True is enable zip respond
            cache: cache content in RAM
                None is using global config, False or 0 to disable cache,
                integer value to set time cache (seconds),
                or string format: 'METHOD-seconds' to select METHOD cache, eg: 'GET-3600'
            limit: limit requests for each windows and set time temporary ban
                True if you want using default value,
                using this format [requests, window, ban expire] to set value,
                False is disable it
            redirect_host: you have 2 or more domains and want redirect all to one
                True if you want using default value,
                using this format [['host1', 'host2], 'host_redirect'] to set value,
                False is disable it
            exceed_msg: return temporary ban content
                True if you want using default value,
        Examples:
            @optimize(type='html', htmlmin=True, zip=True, cache='GET-84600')
        '''

        def _decorating_wrapper(func):

            def _optimize_wrapper(*args, **kwargs):
                try:
                    load_config = self.config[type]

                    htmlmin_arg = load_config['htmlmin'] if (htmlmin is None) else htmlmin
                    izip_arg = load_config['izip'] if (izip is None) else izip
                    cache_arg = load_config['cache'] if (cache is None) else cache

                    if isinstance(cache_arg, str) and request.method in cache_arg:
                        cache_arg = int(cache_arg.split('-')[1])
                    elif not isinstance(cache_arg, int):
                        cache_arg = 0

                    limit_arg = self.config['limit'] if (limit is True) else limit
                    redirect_host_arg = self.config['redirect_host'] if (redirect_host is True) else redirect_host
                    exceed_msg_arg = self.config['exceed_msg'] if (exceed_msg is True) else exceed_msg
                except:
                    raise Exception('Wrong input format')

                # limit by ip
                if limit_arg and self.redis:
                    limit_key = 'limitip-{}'.format(request.remote_addr)
                    ban_key = 'banip-{}'.format(request.remote_addr)

                    times_requested = int(self.redis.get(limit_key) or '0')
                    if times_requested >= limit_arg[0] or self.redis.get(ban_key):
                        if times_requested >= limit_arg[0]:
                            self.redis.delete(limit_key)
                            self.redis.set(ban_key, 1)
                            self.redis.expire(ban_key, limit_arg[2])

                        if self.config['exceed_msg']:
                            return redirect(url_for(exceed_msg_arg))
                        else:
                            return self.crossdomain({'status_code': 429})
                    else:
                        self.redis.incr(limit_key, 1)
                        self.redis.expire(limit_key, limit_arg[1])

                # redirect new host
                if redirect_host_arg:
                    for host in redirect_host_arg[0]:
                        if host in request.url_root:
                            redirect_url = request.url
                            redirect_url = redirect_url.replace(host, redirect_host_arg[1])
                            return redirect(redirect_url)

                # find cached value
                if cache_arg:
                    now = time.time()
                    key_cache = request.url

                    if self._timestamp.get(key_cache, now) > now:
                        return self._cache[key_cache]

                resp = func(*args, **kwargs)

                if not isinstance(resp, wrappers.Response):
                    # crossdomain
                    if type == 'json':
                        resp = self.crossdomain(resp)

                    # min html
                    if htmlmin_arg:
                        resp = self.validate(minify, resp)

                    # gzip
                    if izip_arg:
                        resp = self.validate(self.zipper, resp)

                # cache
                if cache_arg:
                    self._cache[key_cache] = resp
                    self._timestamp[key_cache] = now + cache_arg

                return resp

            return update_wrapper(_optimize_wrapper, func)

        return _decorating_wrapper

Example 43

View license
@application.route("/", methods=['GET', 'POST'])
def main():
    if request.method == 'GET':                         # Main Page
        return render_template("main.html")
    elif request.method == 'POST':                      # Perform Test
        # Sanity checks of request values
        ok = True
        host = request.form['host']
        if not reHost.match(host):
            flash("Wrong host name!")
            ok = False
        if host == "localhost" or host.find("127.") == 0:
            flash("I was already pentested ;)")
            ok = False

        try:
            port = int(request.form['port'])
            if not (port >= 0 and port <= 65535):
                flash("Wrong port number!")
                ok = False
        except:
            flash("Port number must be numeric")
            ok = False

        if 'starttls' in request.form and request.form['starttls'] == "yes":
            starttls = True
        else:
            starttls = False

        protocol = request.form['protocol']
        if starttls and protocol not in protocols:
            flash("Wrong protocol!")
            ok = False

        if not ('confirm' in request.form and request.form['confirm'] == "yes"):
            flash("You must confirm that you are authorized to scan the given system!")
            ok = False

        # Perform preflight request to prevent that testssl.sh runs into long timeout
        if ok and preflightRequest:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(preflightTimeout)
                s.connect((host, port))
                s.close()
            except:
                flash("Connection failed!")
                ok = False

        if not ok:
            return redirect(url_for('main'))

        # Build command line
        args = [checkCmd]
        args += checkArgs
        if starttls:
            args.append("-t")
            args.append(protocol)
        args.append(host + ":" + str(port))

        # Perform test
        output = b""
        try:
            check = Popen(args, stdout=PIPE, stderr=PIPE)
            output, err = check.communicate(timeout=checkTimeout)
            if check.returncode != 0:
                output = err
                flash("SSL Scan failed with error code " + str(check.returncode) + " - see below for details")
        except TimeoutExpired as e:
            flash("SSL Scan timed out")
            check.terminate()

        html = "<pre>" + str(output, 'utf-8') + "</pre>"
        try:
            renderer = Popen([rendererCmd], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            html, err = renderer.communicate(input=output, timeout=rendererTimeout)
            if renderer.returncode != 0:
                html = "<pre>" + str(err, 'utf-8') + "</pre>"
                flash("HTML formatting failed with error code " + str(renderer.returncode) + " - see raw output below")
        except TimeoutExpired as e:
            flash("HTML formatting failed - see raw output below")
            renderer.terminate()

        ts = datetime.now()
        try:
            resultfile = open(resultDirHTML + "/" + ts.strftime("%Y%m%d-%H%M%S.%f") + "-" + host + "_" + str(port) + ".html", mode='w')
            resultfile.write(str(html, 'utf-8'))
            resultfile.close()
        except:
            pass
        return render_template("result.html", result=str(html, 'utf-8'))

Example 44

Project: WAPT
Source File: blueprints.py
View license
    def test_templates_and_static(self):
        from blueprintapp import app
        c = app.test_client()

        rv = c.get('/')
        self.assert_equal(rv.data, b'Hello from the Frontend')
        rv = c.get('/admin/')
        self.assert_equal(rv.data, b'Hello from the Admin')
        rv = c.get('/admin/index2')
        self.assert_equal(rv.data, b'Hello from the Admin')
        rv = c.get('/admin/static/test.txt')
        self.assert_equal(rv.data.strip(), b'Admin File')
        rv.close()
        rv = c.get('/admin/static/css/test.css')
        self.assert_equal(rv.data.strip(), b'/* nested file */')
        rv.close()

        # try/finally, in case other tests use this app for Blueprint tests.
        max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
        try:
            expected_max_age = 3600
            if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:
                expected_max_age = 7200
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age
            rv = c.get('/admin/static/css/test.css')
            cc = parse_cache_control_header(rv.headers['Cache-Control'])
            self.assert_equal(cc.max_age, expected_max_age)
            rv.close()
        finally:
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default

        with app.test_request_context():
            self.assert_equal(flask.url_for('admin.static', filename='test.txt'),
                              '/admin/static/test.txt')

        with app.test_request_context():
            try:
                flask.render_template('missing.html')
            except TemplateNotFound as e:
                self.assert_equal(e.name, 'missing.html')
            else:
                self.assert_true(0, 'expected exception')

        with flask.Flask(__name__).test_request_context():
            self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')

Example 45

Project: bepasty-server
Source File: rest.py
View license
    def post(self):
        """
        Upload file via REST-API. Chunked Upload is supported.

        HTTP Headers that need to be given:
        * Content-Type: The type of the file that is being uploaded.
            If this is not given filetype will be 'application/octet-stream'
        * Content-Length: The total size of the file to be uploaded.
        * Content-Filename: The filename of the file. This will be used when downloading.
        * Content-Range: The Content-Range of the Chunk that is currently being uploaded.
            Follows the HTTP-Header Specifications.
        * Transaction-Id: The Transaction-Id for Chunked Uploads.
            Needs to be delivered when uploading in chunks (after the first chunk).

        To start an upload, the HTTP Headers need to be delivered.
        The body of the request needs to be the base64 encoded file contents.
        Content-Length is the original file size before base64 encoding.
        Content-Range follows the same logic.
        After the first chunk is uploaded, bepasty will return the Transaction-Id to continue the upload.
        Deliver the Transaction-Id and the correct Content-Range to continue upload.
        After the file is completely uploaded, the file will be marked as complete and
        a 201 HTTP Status will be returned.
        The Content-Location Header will contain the api url to the uploaded Item.

        If the file size exceeds the permitted size, the upload will be aborted. This will be checked twice.
        The first check is the provided Content-Length. The second is the actual file size on the server.
        """
        if not may(CREATE):
            return 'Missing Permissions', 403

        # Collect all expected data from the Request
        file_type = request.headers.get("Content-Type")
        file_size = request.headers.get("Content-Length")
        file_name = request.headers.get("Content-Filename")

        # Check the file size from Request
        Upload.filter_size(file_size)

        # Check if Transaction-ID is available for continued upload
        if not request.headers.get("Transaction-Id"):
            # Create ItemName and empty file in Storage
            name = ItemName.create(current_app.storage)
            item = current_app.storage.create(name, 0)

            # set max lifetime
            maxlife_unit = request.headers.get('maxlife-unit', 'FOREVER')
            maxlife_value = int(request.headers.get('maxlife-value', 1))
            maxtime = time_unit_to_sec(maxlife_value, maxlife_unit.upper())
            maxlife_timestamp = int(time.time()) + maxtime if maxtime > 0 else maxtime
            # Fill meta with data from Request
            Upload.meta_new(item, 0, file_name, file_type,
                            'application/octet-stream',
                            name, maxlife_stamp=maxlife_timestamp)
        else:
            # Get file name from Transaction-ID and open from Storage
            name = base64.b64decode(request.headers.get("Transaction-Id"))
            item = current_app.storage.openwrite(name)

        # Check the actual size of the file on the server against limit
        # Either 0 if new file or n bytes of already uploaded file
        Upload.filter_size(item.data.size)

        # Check Content-Range. Needs to be specified, even if only one chunk
        if not request.headers.get("Content-Range"):
            return 'Content-Range not specified', 400

        # Get Content-Range and check if Range is consistent with server state
        file_range = ContentRange.from_request()
        if not item.data.size == file_range.begin:
            return ('Content-Range inconsistent. Last byte on Server: %d' % item.data.size), 409

        # Decode Base64 encoded request data
        raw_data = base64.b64decode(request.data)
        file_data = BytesIO(raw_data)

        # Write data chunk to item
        Upload.data(item, file_data, len(raw_data), file_range.begin)

        # Make a Response and create Transaction-ID from ItemName
        response = make_response()
        response.headers["transaction-id"] = base64.b64encode(name)
        response.status = '200'

        # Check if file is completely uploaded and set meta
        if file_range.is_complete:
            Upload.meta_complete(item, '')
            item.meta['size'] = item.data.size
            item.close()

            background_compute_hash(current_app.storage, name)
            # Set status 'successful' and return the new URL for the uploaded file
            response.status = '201'
            response.headers["Content-Location"] = url_for('bepasty_apis.items_detail', name=name)
            response.headers["Transaction-ID"] = base64.b64encode(name)
        else:
            item.close()

        return response

Example 46

Project: bepasty-server
Source File: display.py
View license
    def get(self, name):
        if not may(READ):
            raise Forbidden()
        try:
            item = current_app.storage.openwrite(name)
        except (OSError, IOError) as e:
            if e.errno == errno.ENOENT:
                raise NotFound()
            raise

        with item as item:
            complete = item.meta['complete']
            if not complete and not may(ADMIN):
                error = 'Upload incomplete. Try again later.'
                return render_template('error.html', heading=item.meta['filename'], body=error), 409

            if item.meta['locked'] and not may(ADMIN):
                raise Forbidden()

            if delete_if_lifetime_over(item, name):
                raise NotFound()

            def read_data(item):
                # reading the item for rendering is registered like a download
                data = item.data.read(item.data.size, 0)
                item.meta['timestamp-download'] = int(time.time())
                return data

            size = item.meta['size']
            ct = item.meta['type']
            try:
                get_lexer_for_mimetype(ct)
                use_pygments = True
                ct_pygments = ct
            except NoPygmentsLexer:
                if ct.startswith('text/'):
                    # seems like we found a text type not supported by pygments
                    # use text/plain so we get a display with line numbers
                    use_pygments = True
                    ct_pygments = 'text/plain'
                else:
                    use_pygments = False

            if rendering_allowed(ct, size, use_pygments, complete):
                if ct.startswith('text/x-bepasty-'):
                    # special bepasty items - must be first, don't feed to pygments
                    if ct == 'text/x-bepasty-list':
                        names = read_data(item).decode('utf-8').splitlines()
                        files = sorted(file_infos(names), key=lambda f: f['filename'])
                        rendered_content = Markup(render_template('filelist_tableonly.html', files=files))
                    else:
                        rendered_content = u"Can't render this content type."
                elif ct.startswith('image/'):
                    src = url_for('bepasty.download', name=name)
                    rendered_content = Markup(u'<img src="%s" alt="the image" width="800">' % src)
                elif ct.startswith('audio/'):
                    src = url_for('bepasty.download', name=name)
                    alt_msg = u'html5 audio element not supported by your browser.'
                    rendered_content = Markup(u'<audio controls src="%s">%s</audio>' % (src, alt_msg))
                elif ct.startswith('video/'):
                    src = url_for('bepasty.download', name=name)
                    alt_msg = u'html5 video element not supported by your browser.'
                    rendered_content = Markup(u'<video controls src="%s">%s</video>' % (src, alt_msg))
                elif ct in ['application/pdf', 'application/x-pdf', ]:
                    src = url_for('bepasty.inline', name=name)
                    link_txt = u'Click to see PDF'
                    rendered_content = Markup(u'<a href="%s">%s</a>' % (src, link_txt))
                elif use_pygments:
                    text = read_data(item)
                    # TODO we don't have the coding in metadata
                    try:
                        text = text.decode('utf-8')
                    except UnicodeDecodeError:
                        # well, it is not utf-8 or ascii, so we can only guess...
                        text = text.decode('iso-8859-1')
                    lexer = get_lexer_for_mimetype(ct_pygments)
                    formatter = CustomHtmlFormatter(linenos='table', lineanchors="L",
                                                    lineparagraphs="L", anchorlinenos=True)
                    rendered_content = Markup(highlight(text, lexer, formatter))
                else:
                    rendered_content = u"Can't render this content type."
            else:
                if not complete:
                    rendered_content = u"Rendering not allowed (not complete). Is it still being uploaded?"
                else:
                    rendered_content = u"Rendering not allowed (too big?). Try download"

            return render_template('display.html', name=name, item=item,
                                   rendered_content=rendered_content)

Example 47

Project: galah
Source File: _resubmit.py
View license
@app.route("/assignments/<assignment_id>/resubmit/<submission_id>")
@account_type_required(("student", "teacher", "teaching_assistant"))
def resubmit_submission(assignment_id, submission_id):
    # Figure out which assignment the submission belongs to.
    try:
        assignment_id = ObjectId(assignment_id)
        assignment = Assignment.objects.get(id = assignment_id)
    except (InvalidId, Assignment.DoesNotExist) as e:
        logger.info("Could not retrieve assignment: %s", str(e))

        abort(404)

    # Figure out where we should redirect the user to once we're done.
    redirect_to = request.args.get("next") or request.referrer

    if not is_url_on_site(app, redirect_to):
        # Default going back to the assignment screen
        redirect_to = url_for(
            "view_assignment",
            assignment_id = assignment_id
        )

    # Recheck if the assignment's cutoff date has passed.
    today = datetime.datetime.today()
    deadline = current_user.personal_deadline
    if assignment.due_cutoff and \
            assignment.due_cutoff < today and \
            (str(assignment_id) not in deadline or
             deadline[str(assignment_id)] < datetime.datetime.today):
        logger.info("Submission rejected, cutoff date has already passed.")

        return craft_response(
            error = "The cutoff date has already passed, your submission was "
                    "not accepted."
        )

    try:
        submission_id = ObjectId(submission_id)
        submission = Submission.objects.get(id = submission_id)
    except (InvalidId, Submission.DoesNotExist) as e:
        logger.info("Could not retrieve submission: %s", str(e))

        abort(404)

    # Recheck that this assignment has a test harness before signaling shepherd.
    if (assignment.test_harness):
        submission.test_request_timestamp = datetime.datetime.now()
        send_test_request(config["PUBLIC_SOCKET"], submission.id)
        logger.info("Resending test request to shepherd for %s" \
                        % str(submission.id))

        # If the test result failed, remove it from submissions and database
        if submission.test_results:
            result = TestResult.objects.get(id = submission.test_results)
            if result.failed:
                result.delete()
                submission.test_results = None

        # Save new reqeust timestamp in submission.
        submission.save()

        flash("Successfully resubmitted files.", category = "message")

    return redirect(redirect_to)

Example 48

Project: galah
Source File: _upload_submission.py
View license
@app.route("/assignments/<assignment_id>/upload", methods = ["POST"])
@account_type_required(("student", "teacher", "teaching_assistant"))
def upload_submission(assignment_id):
    # Figure out which assignment the user asked for.
    try:
        id = ObjectId(assignment_id)
        assignment = Assignment.objects.get(id = id)
    except (InvalidId, Assignment.DoesNotExist) as e:
        logger.info("Could not retrieve assignment: %s", str(e))

        abort(404)

    # Figure out where we should redirect the user to once we're done.
    redirect_to = request.args.get("next") or request.referrer

    if not is_url_on_site(app, redirect_to):
        # Default going back to the assignment screen
        redirect_to = url_for(
            "view_assignment",
            assignment_id = assignment_id
        )

    assignment.apply_personal_deadlines(current_user)

    # Check if the assignment's cutoff date has passed
    if assignment.due_cutoff and \
            assignment.due_cutoff < datetime.datetime.today():
        logger.info("Submission rejected, cutoff date has already passed.")

        flash(
            "The cutoff date has already passed, your submission was not "
            "accepted.", category = "error"
        )

        return redirect(redirect_to)

    form = SimpleArchiveForm()
    if not form.validate_on_submit():
        logger.info(
            "Submission rejected due to internal validation problem."
        )

        flash(
            "Submission rejected due to internal validation problem. Try "
            "again.", category = "error"
        )

        return redirect(redirect_to)

    if not [i for i in form.archive.entries if i.data.filename]:
        logger.info("Submission rejected. User did not submit any files.")

        flash("You did not submit any files.", category = "error")

        return redirect(redirect_to)

    new_submission = Submission(
        assignment = id,
        user = current_user.id,
        timestamp = datetime.datetime.now(),
        test_type = "final" if form.marked_as_final.data else "public",
        most_recent = True
    )
    new_submission.id = ObjectId()

    logger.info(str(new_submission.to_dict()))

    # Craft a unique directory path where we will store the new submission. We
    # are guarenteed an ObjectId is unique. However we are not guarenteed that
    # we will have the proper permissions and that we will be able to make the
    # directory thus this could error because of that.
    new_submission.testables = new_submission.getFilePath()
    os.makedirs(new_submission.testables)

    # Save each file the user uploaded into the submissions directory
    for i in form.archive.entries:
        if not i.data.filename:
            continue

        #  Figure out where we want to save the user's file
        file_path = os.path.join(
            new_submission.testables, secure_filename(i.data.filename)
        )

        # Do the actual saving
        i.data.save(file_path)

    new_submission.uploaded_filenames.extend(
        secure_filename(i.data.filename) for i in form.archive.entries
            if i.data.filename
    )

    logger.info(
        "Succesfully uploaded a new submission (id = %s) with files %s.",
        str(new_submission.id),
        str(new_submission.uploaded_filenames)
    )

    # The old "most_recent" submission is no longer the most recent.
    Submission.objects(
        user = current_user.email,
        assignment = id,
        most_recent = True
    ).update(
        multi = False,
        unset__most_recent = 1
    )

    if assignment.test_harness:
        new_submission.test_request_timestamp = datetime.datetime.now()
        logger.info("Sent test request to shepherd for %s" % \
                        str(new_submission.id))

    new_submission.save()

    # Tell shepherd to start running tests if there is a test_harness.
    if assignment.test_harness:
        send_test_request(config["PUBLIC_SOCKET"], new_submission.id)

    # Communicate to the next page what submission was just added.
    flash(str(new_submission.id), category = "new_submission")

    flash(
        "Successfully uploaded %s %s." %
            (
                plural_if("file", len(new_submission.uploaded_filenames)),
                pretty_list(new_submission.uploaded_filenames)
            ),
        category = "message"
    )

    # Everything seems to have gone well
    return redirect(redirect_to)

Example 49

Project: plenario
Source File: __init__.py
View license
def create_app():
    # API depends on the tables in the database to exist.
    # Don't import until we really need it to create the app
    # Since otherwise it may be called before init_db.py runs.
    from plenario.api import api, cache

    # These other imports might eventually use API as well.
    # plenario.views does now. So we'll put them here like
    # API and not import them until they're really needed.
    from plenario.apiary import apiary, apiary_bp
    from plenario.database import session as db_session
    from plenario.models import bcrypt
    from plenario.auth import auth, login_manager
    from plenario.views import views
    from plenario.utils.helpers import slugify as slug

    app = Flask(__name__)
    app.config.from_object('plenario.settings')
    app.url_map.strict_slashes = False
    login_manager.init_app(app)
    login_manager.login_view = "auth.login"
    bcrypt.init_app(app)

    if sentry:
        sentry.init_app(app)
    app.register_blueprint(api)
    app.register_blueprint(views)
    app.register_blueprint(auth)
    cache.init_app(app)

    apiary.init_app(app)
    app.register_blueprint(apiary_bp)

    @app.before_request
    def check_maintenance_mode():
        """
        If maintenance mode is turned on in settings.py,
        Disable the API and the interactive pages in the explorer.
        """
        maint = app.config.get('MAINTENANCE')
        maint_pages = ['/v1/api', '/explore', '/admin']

        maint_on = False
        for m in maint_pages:
            if m in request.path:
                maint_on = True

        if maint and maint_on and request.path != url_for('views.maintenance'):
            return redirect(url_for('views.maintenance'))

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def page_not_found(e):
        return render_template('error.html'), 500

    @app.template_filter('slugify')
    def slugify(s):
        return slug(s)

    @app.template_filter('format_number')
    def reverse_filter(s):
        return '{:,}'.format(s)

    @app.template_filter('format_date_sort')
    def reverse_filter(s):
        if s:
            return s.strftime('%Y%m%d%H%M')
        else:
            return '0'

    @app.template_filter('has_description')
    def has_description(list_of_cols):
        try:
            # Any description attribute filled?
            return any([col['description'] for col in list_of_cols])
        except KeyError:
            # Is there even a description attribute?
            return False

    return app

Example 50

Project: flask-mwoauth
Source File: __init__.py
View license
    def __init__(self,
                 base_url='https://www.mediawiki.org/w',
                 clean_url='https://www.mediawiki.org/wiki',
                 default_return_to='index',
                 consumer_key=None, consumer_secret=None, name='mw.org'):
        if not consumer_key or not consumer_secret:
            raise Exception('MWOAuthBlueprintFactory needs consumer key and secret')
        self.base_url = base_url

        self.default_return_to = default_return_to

        self.oauth = OAuth()
        request_url_params = {'title': 'Special:OAuth/initiate',
                              'oauth_callback': 'oob'}
        access_token_params = {'title': 'Special:OAuth/token'}
        self.mwoauth = self.oauth.remote_app(
            name,
            base_url=base_url + "/index.php",
            request_token_url=base_url + "/index.php?" +
                              urlencode(request_url_params),
            request_token_params=None,
            access_token_url=base_url + "/index.php?" +
                             urlencode(access_token_params),
            authorize_url=clean_url + '/Special:OAuth/authorize',
            consumer_key=consumer_key,
            consumer_secret=consumer_secret,
        )

        @self.mwoauth.tokengetter
        def get_mwo_token(token=None):
            return session.get('mwo_token')

        self.bp = Blueprint('mwoauth', __name__)

        @self.bp.route('/logout')
        def logout():
            session['mwo_token'] = None
            session['username'] = None
            if 'next' in request.args:
                return redirect(request.args['next'])
            return "Logged out!"

        @self.bp.route('/login')
        def login():
            uri_params = {'oauth_consumer_key': self.mwoauth.consumer_key}
            redirector = self.mwoauth.authorize(**uri_params)

            if 'next' in request.args:
                oauth_token = session[self.mwoauth.name + '_oauthtok'][0]
                session[oauth_token + '_target'] = request.args['next']

            return redirector

        @self.bp.route('/oauth-callback')
        def oauth_authorized():
            resp = self.mwoauth.authorized_response()
            next_url_key = request.args['oauth_token'] + '_target'
            default_url = url_for(self.default_return_to)

            next_url = session.pop(next_url_key, default_url)

            if resp is None:
                flash(u'You denied the request to sign in.')
                return redirect(next_url)
            session['mwo_token'] = (
                resp['oauth_token'],
                resp['oauth_token_secret']
            )

            username = self.get_current_user(False)
            flash('You were signed in, %s!' % username)

            return redirect(next_url)