Esempio n. 1
0
    def test_new_wrong_user(self):
        # First we add a Dataset with user 'test_new'
        user = Account.by_name('test_new')
        assert user.api_key == 'd0610659-627b-4403-8b7f-6e2820ebc95d'

        u = url(controller='api/version2', action='create')
        params = {
            'metadata':
            'https://dl.dropbox.com/u/3250791/sample-openspending-model.json',
            'csv_file':
            'http://mk.ucant.org/info/data/sample-openspending-dataset.csv'
        }
        apikey_header = 'apikey {0}'.format(user.api_key)
        response = self.app.post(u, params, {'Authorization': apikey_header})

        assert "200" in response.status
        assert Dataset.by_name('openspending-example') is not None

        # After that we try to update the Dataset with user 'test_new2'
        user = Account.by_name('test_new2')
        assert user.api_key == 'c011c340-8dad-419c-8138-1c6ded86ead5'

        u = url(controller='api/version2', action='create')
        params = {
            'metadata':
            'https://dl.dropbox.com/u/3250791/sample-openspending-model.json',
            'csv_file':
            'http://mk.ucant.org/info/data/sample-openspending-dataset.csv'
        }
        apikey_header = 'apikey {0}'.format(user.api_key)
        response = self.app.post(u, params, {'Authorization': apikey_header},
                                 expect_errors=True)
        assert '403' in response.status
Esempio n. 2
0
def shell_account():
    account = Account.by_name(SHELL_USER)
    if account is not None:
        return account
    account = Account()
    account.name = SHELL_USER
    db.session.add(account)
    return account
Esempio n. 3
0
def shell_account():
    account = Account.by_name(SHELL_USER)
    if account is not None:
        return account
    account = Account()
    account.name = SHELL_USER
    db.session.add(account)
    return account
Esempio n. 4
0
def verify():


    if request.method == 'GET':
        loginhash = request.args.get('login')
        if not loginhash:
            message = "Invalid URL.  Please contact system administrator."
            return render_template('account/message.jade', message=message)


        account = Account.by_login_hash(loginhash)

        if not account:
            message = "This URL is no longer valid.  If you have an account, you can reset your password at the " + \
                        " <a href='" + url_for('account.trigger_reset') + "'>password reset page</a>. Or you can register at \
                        <a href='" + url_for('account.login') + "'>login page</a>"
            return render_template('account/message.jade', message=message)

    
        #request.form.loginhash = {"data":loginhash}
        values = {'loginhash': loginhash, "csrf_token": generate_csrf_token()}
        return render_template('account/verify.jade', account=account, form_fill=values)

    else:

        loginhash = request.form.get('loginhash')
        if not loginhash:
            message = "We cannot find your unique URL"
            return render_template('account/message.jade', message=message)

        account = Account.by_login_hash(loginhash)

        if not account:
            message = "We could not find your account"
            return render_template('account/message.jade', message=message)

        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        # Check if passwords match, return error if not
        if password1 != password2:
            error = "Your passwords do not match"
            return render_template('account/verify.jade', loginhash=loginhash, account=account, error=error)

        account.password = generate_password_hash(password1)
        #reset that hash but don't send it.
        account.reset_loginhash()
        account.verified = True
        db.session.commit()


        flash_success("Password saved and you are now verified.  Thank you.")
        login_user(account, remember=True)



        return redirect(url_for('home.index'))
Esempio n. 5
0
 def test_settings(self, model_mock, update_mock):
     account = Account()
     account.name = 'mockaccount'
     db.session.add(account)
     db.session.commit()
     model_mock.return_value = account
     update_mock.return_value = True
     self.app.get(url(controller='account', action='settings'),
                  extra_environ={'REMOTE_USER': '******'})
Esempio n. 6
0
 def test_settings(self, model_mock, update_mock):
     account = Account()
     account.name = 'mockaccount'
     db.session.add(account)
     db.session.commit()
     model_mock.return_value = account
     update_mock.return_value = True
     self.app.get(url(controller='account', action='settings'),
                  extra_environ={'REMOTE_USER': '******'})
Esempio n. 7
0
def verify():

    if request.method == 'GET':
        loginhash = request.args.get('login')
        if not loginhash:
            message = "Invalid URL.  Please contact system administrator."
            return render_template('account/message.jade', message=message)

        account = Account.by_login_hash(loginhash)

        if not account:
            message = "This URL is no longer valid.  If you have an account, you can reset your password at the " + \
                        " <a href='" + url_for('account.trigger_reset') + "'>password reset page</a>. Or you can register at \
                        <a href='"                                   + url_for('account.login') + "'>login page</a>"
            return render_template('account/message.jade', message=message)

        #request.form.loginhash = {"data":loginhash}
        values = {'loginhash': loginhash, "csrf_token": generate_csrf_token()}
        return render_template('account/verify.jade',
                               account=account,
                               form_fill=values)

    else:

        loginhash = request.form.get('loginhash')
        if not loginhash:
            message = "We cannot find your unique URL"
            return render_template('account/message.jade', message=message)

        account = Account.by_login_hash(loginhash)

        if not account:
            message = "We could not find your account"
            return render_template('account/message.jade', message=message)

        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        # Check if passwords match, return error if not
        if password1 != password2:
            error = "Your passwords do not match"
            return render_template('account/verify.jade',
                                   loginhash=loginhash,
                                   account=account,
                                   error=error)

        account.password = generate_password_hash(password1)
        #reset that hash but don't send it.
        account.reset_loginhash()
        account.verified = True
        db.session.commit()

        flash_success("Password saved and you are now verified.  Thank you.")
        login_user(account, remember=True)

        return redirect(url_for('home.index'))
Esempio n. 8
0
def load_user_from_request(request):
    api_key = request.args.get('api_key')
    if api_key and len(api_key):
        account = Account.by_api_key(api_key)
        if account:
            return account

    api_key = request.headers.get('Authorization')
    if api_key and len(api_key) and ' ' in api_key:
        method, api_key = api_key.split(' ', 1)
        if method.lower() == 'apikey':
            account = Account.by_api_key(api_key)
            if account:
                return account
    return None
Esempio n. 9
0
def load_user_from_request(request):
    api_key = request.args.get('api_key')
    if api_key and len(api_key):
        account = Account.by_api_key(api_key)
        if account:
            return account

    api_key = request.headers.get('Authorization')
    if api_key and len(api_key) and ' ' in api_key:
        method, api_key = api_key.split(' ', 1)
        if method.lower() == 'apikey':
            account = Account.by_api_key(api_key)
            if account:
                return account
    return None
Esempio n. 10
0
    def setup(self):

        super(TestRunController, self).setup()
        self.source = csvimport_fixture('import_errors')
        self.source.dataset.managers.append(Account.by_name('test'))
        self.importer = CSVImporter(self.source)
        self.importer.run()
Esempio n. 11
0
    def setup(self):

        super(TestRunController, self).setup()
        self.source = csvimport_fixture('import_errors')
        self.source.dataset.managers.append(Account.by_name('test'))
        self.importer = CSVImporter(self.source)
        self.importer.run()
Esempio n. 12
0
def email_message():
    """
    Redirect user to this to tell them to go check their email
    """

    user_id = request.args.get('id')
    useraccount = Account.by_id(user_id)

    if not useraccount:
        message = "There is no user with this account"
        return render_template('account/email_message.jade', message=message)

    if useraccount.admin:
        message = "This operation is not possible for this user type"
        return render_template('account/email_message.jade', message=message)

    emailsplit = useraccount.email.split("@")
    email = emailsplit[0][:3] + "*****@" + emailsplit[1]

    flash_success("Your account is being set up.  Please see note below.")

    message = """Thank you for your request.  An email has been sent to %s with 
                further instructions.  If you have not recieved an email in next few minutes
                 please try <a style='color:#337ab7' href='%s'>resetting your
                 password</a>.""" % (email, url_for('account.trigger_reset'))

    # message_dict = sendhash(useraccount, gettext=True)
    # message = str(message_dict) + "<br/><br/><a href='" + message_dict['verifylink'] + "'><h3>Click to Verify</h3></a>"

    return render_template('account/email_message.jade', message=message)
Esempio n. 13
0
    def profile(self, name=None):
        """
        Generate a profile page for a user (from the provided name)
        """

        # Get the account, if it's none we return a 404
        account = Account.by_name(name)
        if account is None:
            response.status = 404
            return None

        # Set the account we got as the context variable 'profile'
        # Note this is not the same as the context variable 'account'
        # which is the account for a logged in user
        c.profile = account

        # Set a context boo if email/twitter should be shown, it is only shown
        # to administrators and to owner (account is same as context account)
        show_info = (c.account and c.account.admin) or (c.account == account)

        # ..or if the user has chosen to make it public
        c.show_email = show_info or account.public_email
        c.show_twitter = show_info or account.public_twitter

        # Collect and sort the account's datasets and views
        c.account_datasets = sorted(account.datasets, key=lambda d: d.label)
        c.account_views = sorted(account.views, key=lambda d: d.label)

        # Render the profile
        return templating.render('account/profile.html')
Esempio n. 14
0
def profile(account_id=None):
    """ Render the user page. """
    if not is_authenticated(current_user):
        flash_error("This is only for registered users")
        abort(403)

    if account_id:
        account = Account.by_id(account_id)
    else:
        account = current_user

    if not account:
        flash_error("Cannot find the user account")
        abort(404)

    dataview_list = Dataview.query.filter_by(account_id=account.id).all()

    topics_tracked = current_user.tracked_topics.count()

    # page = request.args.get("forumpage", 1, type=int)
    # topics = current_user.tracked_topics.\
    #     outerjoin(TopicsRead,
    #               db.and_(TopicsRead.topic_id == Topic.id,
    #                       TopicsRead.user_id == current_user.id)).\
    #     add_entity(TopicsRead).\
    #     order_by(Topic.last_updated.desc()).\
    #     paginate(page, flaskbb_config['TOPICS_PER_PAGE'], True)

    # return render_template("forum/forum/topictracker.html", topics=topics)

    return render_template('user/user.jade',
                           account=account,
                           dataviews=dataview_list,
                           topics_tracked=topics_tracked)
Esempio n. 15
0
def create_view(dataset, view_config):
    """
    Create view for a provided dataset from a view provided as dict
    """

    # Check if it exists (if not we create it)
    existing = View.by_name(dataset, view_config['name'])
    if existing is None:
        # Create the view
        view = View()

        # Set saved configurations
        view.widget = view_config['widget']
        view.state = view_config['state']
        view.name = view_config['name']
        view.label = view_config['label']
        view.description = view_config['description']
        view.public = view_config['public']

        # Set the dataset as the current dataset
        view.dataset = dataset

        # Try and set the account provided but if it doesn't exist
        # revert to shell account
        view.account = Account.by_name(view_config['account'])
        if view.account is None:
            view.account = shell_account()

        # Commit view to database
        db.session.add(view)
        db.session.commit()
Esempio n. 16
0
def trigger_reset():
    """
    Allow user to trigger a reset of the password in case they forget it
    """

    values = {"csrf_token": generate_csrf_token()}

    # If it's a simple GET method we return the form
    if request.method == 'GET':
        return render_template('account/trigger_reset.html', form_fill=values)

    # Get the email
    email = request.form.get('email')

    # Simple check to see if the email was provided. Flash error if not
    if email is None or not len(email):
        flash_error("Please enter an email address!")
        return render_template('account/trigger_reset.html', form_fill=values)

    # Get the account for this email
    account = Account.by_email(email)

    # If no account is found we let the user know that it's not registered
    if account is None:
        flash_error("No user is registered under this address!")
        return render_template('account/trigger_reset.html', form_fill=values)

    account.reset_loginhash()
    db.session.commit()

    # Send the reset link to the email of this account
    sendhash(account)

    # Redirect to the login page
    return redirect(url_for('account.email_message', id=account.id))
Esempio n. 17
0
    def test_delete_source(self):
        """
        Test source removal with a source that includes errors
        """

        # Add and import source with errors (we want to remove it)
        # The source is added to a dataset called 'test-csv' (but
        # we'll just use source.dataset.name in case it changes)
        source = csvimport_fixture('import_errors')
        source.dataset.managers.append(Account.by_name('test'))
        importer = CSVImporter(source)
        importer.run()

        # Make sure the source is imported
        assert db.session.query(Source).filter_by(id=source.id).count() == 1, \
            "Import of csv failed. Source not found"

        # Delete the source
        self.app.post(url(controller='source',
                          action='delete',
                          dataset=source.dataset.name,
                          id=source.id),
                      extra_environ={'REMOTE_USER': '******'})

        # Check if source has been deleted
        assert db.session.query(Source).filter_by(id=source.id).count() == 0, \
            "Deleting source unsuccessful. Source still exists."
Esempio n. 18
0
    def profile(self, name=None):
        """
        Generate a profile page for a user (from the provided name)
        """

        # Get the account, if it's none we return a 404
        account = Account.by_name(name)
        if account is None:
            response.status = 404
            return None

        # Set the account we got as the context variable 'profile'
        # Note this is not the same as the context variable 'account'
        # which is the account for a logged in user
        c.profile = account

        # Set a context boo if email/twitter should be shown, it is only shown
        # to administrators and to owner (account is same as context account)
        show_info = (c.account and c.account.admin) or (c.account == account)

        # ..or if the user has chosen to make it public 
        c.show_email = show_info or account.public_email
        c.show_twitter = show_info or account.public_twitter

        # Collect and sort the account's datasets and views
        c.account_datasets = sorted(account.datasets, key=lambda d: d.label)
        c.account_views = sorted(account.views, key=lambda d: d.label)

        # Render the profile
        return templating.render('account/profile.html')
Esempio n. 19
0
def create_view(dataset, view_config):
    """
    Create view for a provided dataset from a view provided as dict
    """

    # Check if it exists (if not we create it)
    existing = View.by_name(dataset, view_config['name'])
    if existing is None:
        # Create the view
        view = View()

        # Set saved configurations
        view.widget = view_config['widget']
        view.state = view_config['state']
        view.name = view_config['name']
        view.label = view_config['label']
        view.description = view_config['description']
        view.public = view_config['public']

        # Set the dataset as the current dataset
        view.dataset = dataset

        # Try and set the account provided but if it doesn't exist
        # revert to shell account
        view.account = Account.by_name(view_config['account'])
        if view.account is None:
            view.account = shell_account()

        # Commit view to database
        db.session.add(view)
        db.session.commit()
Esempio n. 20
0
    def test_delete_successfully_loaded_source(self):
        """
        Test source removal with a source that has been successfully loaded.
        Removing a source that has been successfully loaded should not be
        possible.
        """

        # Add and import source without errors.
        # The source is added to a dataset called 'test-csv' (but
        # we'll just use source.dataset.name in case it changes)
        source = csvimport_fixture('successful_import')
        source.dataset.managers.append(Account.by_name('test'))
        importer = CSVImporter(source)
        importer.run()

        # Make sure the source is imported
        assert db.session.query(Source).filter_by(id=source.id).count() == 1, \
            "Import of csv failed. Source not found"

        # Delete the source
        self.app.post(url(controller='source',
                          action='delete',
                          dataset=source.dataset.name,
                          id=source.id),
                      extra_environ={'REMOTE_USER': '******'})

        # Check if source has been deleted
        assert db.session.query(Source).filter_by(id=source.id).count() == 1, \
            "Deleting source succeeded. The source is gone."
Esempio n. 21
0
    def test_delete_source(self):
        """
        Test source removal with a source that includes errors
        """

        # Add and import source with errors (we want to remove it)
        # The source is added to a dataset called 'test-csv' (but
        # we'll just use source.dataset.name in case it changes)
        source = csvimport_fixture('import_errors')
        source.dataset.managers.append(Account.by_name('test'))
        importer = CSVImporter(source)
        importer.run()

        # Make sure the source is imported
        assert db.session.query(Source).filter_by(id=source.id).count() == 1, \
            "Import of csv failed. Source not found"

        # Delete the source
        self.app.post(url(controller='source',
                          action='delete',
                          dataset=source.dataset.name,
                          id=source.id),
                      extra_environ={'REMOTE_USER': '******'})

        # Check if source has been deleted
        assert db.session.query(Source).filter_by(id=source.id).count() == 0, \
            "Deleting source unsuccessful. Source still exists."
Esempio n. 22
0
    def test_delete_successfully_loaded_source(self):
        """
        Test source removal with a source that has been successfully loaded.
        Removing a source that has been successfully loaded should not be
        possible.
        """

        # Add and import source without errors.
        # The source is added to a dataset called 'test-csv' (but
        # we'll just use source.dataset.name in case it changes)
        source = csvimport_fixture('successful_import')
        source.dataset.managers.append(Account.by_name('test'))
        importer = CSVImporter(source)
        importer.run()

        # Make sure the source is imported
        assert db.session.query(Source).filter_by(id=source.id).count() == 1, \
            "Import of csv failed. Source not found"

        # Delete the source
        self.app.post(url(controller='source',
                          action='delete',
                          dataset=source.dataset.name,
                          id=source.id),
                      extra_environ={'REMOTE_USER': '******'})

        # Check if source has been deleted
        assert db.session.query(Source).filter_by(id=source.id).count() == 1, \
            "Deleting source succeeded. The source is gone."
Esempio n. 23
0
 def register(self):
     require.account.create()
     self._disable_cache()
     errors, values = {}, None
     if request.method == 'POST':
         try:
             schema = AccountRegister()
             values = request.params
             data = schema.deserialize(values)
             if Account.by_name(data['name']):
                 raise colander.Invalid(
                     AccountRegister.name,
                     _("Login name already exists, please choose a "
                       "different one"))
             if not data['password1'] == data['password2']:
                 raise colander.Invalid(AccountRegister.password1,
                                        _("Passwords don't match!"))
             account = Account()
             account.name = data['name']
             account.fullname = data['fullname']
             account.email = data['email']
             account.password = generate_password_hash(data['password1'])
             db.session.add(account)
             db.session.commit()
             who_api = get_api(request.environ)
             authenticated, headers = who_api.login({
                 "login": account.name,
                 "password": data['password1']
             })
             response.headers.extend(headers)
             return redirect("/")
         except colander.Invalid, i:
             errors = i.asdict()
Esempio n. 24
0
 def profile(self, name=None):
     c.config = config
     account = Account.by_name(name)
     if account is None:
         response.status = 404
         return None
     c.profile = account
     c.is_admin = True if (c.account and c.account.admin is True) else False
     return render('account/profile.html')
Esempio n. 25
0
 def profile(self, name=None):
     c.config = config
     account = Account.by_name(name)
     if account is None:
         response.status = 404
         return None
     c.profile = account
     c.is_admin = True if (c.account and c.account.admin is True) else False
     return render('account/profile.html')
Esempio n. 26
0
    def command(self):
        super(GrantAdminCommand, self).command()
        self._check_args_length(1)

        from openspending.model.account import Account

        username = self.args[0]
        account = Account.by_name(username)

        if account is None:
            print "Account `%s' not found." % username
            return False

        roles = set(account["_roles"])

        roles |= set([u'admin'])
        account["_roles"] = list(roles)

        Account.save(account)
Esempio n. 27
0
def login_perform():
    account = Account.by_email(request.form.get('login'))
    #if account is not None and account.verified == True:
    if account is not None:
        if check_password_hash(account.password, request.form.get('password')):
            logout_user()
            login_user(account, remember=True)
            flash_success("Welcome back, " + account.fullname + "!")
            return redirect(url_for('home.index'))
    flash_error("Incorrect user name or password!")
    return login()
Esempio n. 28
0
 def authenticate(self, environ, identity):
     if 'login' not in identity or 'password' not in identity:
         return None
     account = Account.by_name(identity['login'])
     if account is None:
         return None
     if account.password is None:
         return None
     if check_password_hash(account.password, identity['password']):
         return account.name
     return None
Esempio n. 29
0
def login_perform():
    account = Account.by_email(request.form.get('login'))
    #if account is not None and account.verified == True:
    if account is not None:
        if check_password_hash(account.password, request.form.get('password')):
            logout_user()
            login_user(account, remember=True)
            flash_success("Welcome back, " + account.fullname + "!")
            return redirect(url_for('home.index'))
    flash_error("Incorrect user name or password!")
    return login()
Esempio n. 30
0
 def register(self):
     require.account.create()
     errors, values = {}, None
     if request.method == 'POST':
         try:
             schema = AccountRegister()
             values = request.params
             data = schema.deserialize(values)
             if Account.by_name(data['name']):
                 raise colander.Invalid(
                     AccountRegister.name,
                     _("Login name already exists, please choose a "
                       "different one"))
             if not data['password1'] == data['password2']:
                 raise colander.Invalid(AccountRegister.password1, _("Passwords \
                     don't match!"))
             account = Account()
             account.name = data['name']
             account.fullname = data['fullname']
             account.email = data['email']
             account.password = generate_password_hash(data['password1'])
             db.session.add(account)
             db.session.commit()
             who_api = get_api(request.environ)
             authenticated, headers = who_api.login({
                 "login": account.name,
                 "password": data['password1']
             })
             response.headers.extend(headers)
             return redirect("/")
         except colander.Invalid, i:
             errors = i.asdict()
Esempio n. 31
0
    def authenticate(self, environ, identity):
        """
        Try to authenticate user based on api key identity
        """

        # If identity has apikey we get the account by the api key
        # and return none if no account or apikey is found is found
        if 'apikey' in identity:
            acc = Account.by_api_key(identity.get('apikey'))
            if acc is not None:
                return acc.name

        return None
Esempio n. 32
0
    def __before__(self, action, **params):
        account_name = request.environ.get('REMOTE_USER', None)
        if account_name:
            c.account = Account.by_name(account_name)
        else:
            c.account = None

        i18n.handle_request(request, c)

        c._cache_disabled = False
        c._must_revalidate = False
        c.content_section = c.dataset = None

        c.detected_l10n_languages = i18n.get_language_pairs()
Esempio n. 33
0
    def __before__(self, action, **params):
        account_name = request.environ.get('REMOTE_USER', None)
        if account_name:
            c.account = Account.by_name(account_name)
        else:
            c.account = None

        i18n.handle_request(request, c)

        c._cache_disabled = False
        c._must_revalidate = False
        c.content_section = c.dataset = None

        c.detected_l10n_languages = i18n.get_language_pairs()
Esempio n. 34
0
    def test_new_dataset(self):
        user = Account.by_name('test_new')
        assert user.api_key == 'd0610659-627b-4403-8b7f-6e2820ebc95d'

        u = url(controller='api/version2', action='create')
        params = {
            'metadata':
            'https://dl.dropbox.com/u/3250791/sample-openspending-model.json',
            'csv_file':
            'http://mk.ucant.org/info/data/sample-openspending-dataset.csv'
        }
        apikey_header = 'apikey {0}'.format(user.api_key)
        response = self.app.post(u, params, {'Authorization': apikey_header})
        assert "200" in response.status
        assert Dataset.by_name('openspending-example') is not None
Esempio n. 35
0
    def test_new_dataset(self):
        user = Account.by_name('test_new')
        assert user.api_key == 'd0610659-627b-4403-8b7f-6e2820ebc95d'

        u = url(controller='api/version2', action='create')
        params = {
            'metadata':
            'https://dl.dropbox.com/u/3250791/sample-openspending-model.json',
            'csv_file':
            'http://mk.ucant.org/info/data/sample-openspending-dataset.csv'
        }
        apikey_header = 'apikey {0}'.format(user.api_key)
        response = self.app.post(u, params, {'Authorization': apikey_header})
        assert "200" in response.status
        assert Dataset.by_name('openspending-example') is not None
Esempio n. 36
0
def grant_admin(username):
    from openspending.model import meta as db
    from openspending.model.account import Account

    a = Account.by_name(username)

    if a is None:
        print "Account `%s` not found." % username
        return 1

    a.admin = True
    db.session.add(a)
    db.session.commit()

    return 0
Esempio n. 37
0
    def trigger_reset(self):
        self._disable_cache()
        if request.method == 'GET':
            return render('account/trigger_reset.html')
        email = request.params.get('email')
        if email is None or not len(email):
            h.flash_error(_("Please enter an email address!"))
            return render('account/trigger_reset.html')
        account = Account.by_email(email)
        if account is None:
            h.flash_error(_("No user is registered under this address!"))
            return render('account/trigger_reset.html')
        send_reset_link(account)

        h.flash_success(_("You've received an email with a link to reset your "
            + "password. Please check your inbox."))
        redirect(h.url_for(controller='account', action='login'))
Esempio n. 38
0
def edit_profile(account_id):
    account = Account.by_id(account_id)
    if not account:
        flash_error("This is not a valid account")
        abort(404)
    if account.id != current_user.id and not current_user.admin:
        flash_error("You cannot access this content")
        abort(403)

    values = {
        "fullname": account.fullname,
        "website": account.website,
        "csrf_token": generate_csrf_token()
    }

    return render_template('account/edit_profile.jade',
                           form_fill=values,
                           account_id=account_id)
Esempio n. 39
0
def email_message():

    user_id = request.args.get('id')

    useraccount = Account.by_id(user_id)

    if not useraccount:
        message = "There is no user with this account"
        return render_template('account/email_message.jade', message=message)

    if useraccount.admin:
        message = "This operation is not possible for this user type"
        return render_template('account/email_message.jade', message=message)

    message_dict = sendhash(useraccount, gettext=True)
    message = str(message_dict) + "<br/><br/><a href='" + message_dict['verifylink'] + "'><h3>Click to Verify</h3></a>"

    return render_template('account/email_message.jade', message=message)
Esempio n. 40
0
    def trigger_reset(self):
        self._disable_cache()
        if request.method == 'GET':
            return render('account/trigger_reset.html')
        email = request.params.get('email')
        if email is None or not len(email):
            h.flash_error(_("Please enter an email address!"))
            return render('account/trigger_reset.html')
        account = Account.by_email(email)
        if account is None:
            h.flash_error(_("No user is registered under this address!"))
            return render('account/trigger_reset.html')
        send_reset_link(account)

        h.flash_success(
            _("You've received an email with a link to reset your " +
              "password. Please check your inbox."))
        redirect(h.url_for(controller='account', action='login'))
Esempio n. 41
0
 def team_update(self, dataset, format='html'):
     self._get_dataset(dataset)
     require.dataset.update(c.dataset)
     errors, accounts = {}, []
     for account_name in request.params.getall('accounts'):
         account = Account.by_name(account_name)
         if account is None:
             errors[account_name] = _("User account cannot be found.")
         else:
             accounts.append(account)
     if c.account not in accounts:
         accounts.append(c.account)
     if not len(errors):
         c.dataset.managers = accounts
         c.dataset.updated_at = datetime.utcnow()
         db.session.commit()
         h.flash_success(_("The team has been updated."))
     return self.team_edit(dataset, errors=errors, accounts=accounts)
Esempio n. 42
0
 def do_reset(self):
     email = request.params.get('email')
     if email is None or not len(email):
         h.flash_error(_("The reset link is invalid!"))
         redirect(h.url_for(controller='account', action='login'))
     account = Account.by_email(email)
     if account is None:
         h.flash_error(_("No user is registered under this address!"))
         redirect(h.url_for(controller='account', action='login'))
     if request.params.get('token') != account.token:
         h.flash_error(_("The reset link is invalid!"))
         redirect(h.url_for(controller='account', action='login'))
     who_api = request.environ['repoze.who.plugins']['auth_tkt']
     headers = who_api.remember(request.environ,
             {'repoze.who.userid': account.name})
     response.headers.extend(headers)
     h.flash_success(_("Thanks! You have now been signed in - please change "
         + "your password!"))
     redirect(h.url_for(controller='account', action='settings'))
Esempio n. 43
0
def email_message():

    user_id = request.args.get('id')

    useraccount = Account.by_id(user_id)

    if not useraccount:
        message = "There is no user with this account"
        return render_template('account/email_message.jade', message=message)

    if useraccount.admin:
        message = "This operation is not possible for this user type"
        return render_template('account/email_message.jade', message=message)

    message_dict = sendhash(useraccount, gettext=True)
    message = str(message_dict) + "<br/><br/><a href='" + message_dict[
        'verifylink'] + "'><h3>Click to Verify</h3></a>"

    return render_template('account/email_message.jade', message=message)
Esempio n. 44
0
 def do_reset(self):
     email = request.params.get('email')
     if email is None or not len(email):
         h.flash_error(_("The reset link is invalid!"))
         redirect(h.url_for(controller='account', action='login'))
     account = Account.by_email(email)
     if account is None:
         h.flash_error(_("No user is registered under this address!"))
         redirect(h.url_for(controller='account', action='login'))
     if request.params.get('token') != account.token:
         h.flash_error(_("The reset link is invalid!"))
         redirect(h.url_for(controller='account', action='login'))
     who_api = request.environ['repoze.who.plugins']['auth_tkt']
     headers = who_api.remember(request.environ,
                                {'repoze.who.userid': account.name})
     response.headers.extend(headers)
     h.flash_success(
         _("Thanks! You have now been signed in - please change " +
           "your password!"))
     redirect(h.url_for(controller='account', action='settings'))
Esempio n. 45
0
    def register(self):
        require.account.create()
        c.config = config
        self._disable_cache()
        errors, values = {}, None
        if request.method == 'POST':
            try:
                schema = AccountRegister()
                values = request.params
                data = schema.deserialize(values)
                if Account.by_name(data['name']):
                    raise colander.Invalid(
                        AccountRegister.name,
                        _("Login name already exists, please choose a "
                          "different one"))
                if not data['password1'] == data['password2']:
                    raise colander.Invalid(AccountRegister.password1,
                                           _("Passwords don't match!"))
                account = Account()
                account.name = data['name']
                account.fullname = data['fullname']
                account.email = data['email']
                account.password = generate_password_hash(data['password1'])
                db.session.add(account)
                db.session.commit()
                who_api = get_api(request.environ)
                authenticated, headers = who_api.login({
                    "login":
                    account.name,
                    "password":
                    data['password1']
                })

                errors = subscribe_lists(('community', 'developer'), data)
                if errors:
                    h.flash_notice(
                        _("Subscription to the following mailing " +
                          "lists probably failed: %s.") % ', '.join(errors))

                response.headers.extend(headers)
                return redirect("/")
            except colander.Invalid, i:
                errors = i.asdict()
Esempio n. 46
0
def make_account(name='test',
                 fullname='Test User',
                 email='*****@*****.**',
                 twitter='testuser',
                 admin=False):
    from openspending.model.account import Account

    # First see if the account already exists and if so, return it
    account = Account.by_name(name)
    if account:
        return account

    # Account didn't exist so we create it and return it
    account = Account()
    account.name = name
    account.fullname = fullname
    account.email = email
    account.twitter_handle = twitter
    account.admin = admin
    db.session.add(account)
    db.session.commit()

    return account
Esempio n. 47
0
def make_account(name='test',
                 fullname='Test User',
                 email='*****@*****.**',
                 admin=False,
                 verified=True,
                 moderator=False):
    from openspending.model.account import Account

    # First see if the account already exists and if so, return it
    account = Account.by_email(email)
    if account:
        return account

    # Account didn't exist so we create it and return it
    account = Account()
    account.fullname = fullname
    account.email = email
    account.admin = admin
    account.moderator = moderator
    account.verified = verified
    db.session.add(account)
    db.session.commit()
    return account
Esempio n. 48
0
def trigger_reset():
    """
    Allow user to trigger a reset of the password in case they forget it
    """

    values = {"csrf_token": generate_csrf_token()}

    # If it's a simple GET method we return the form
    if request.method == 'GET':
        return render_template('account/trigger_reset.html', form_fill=values)

    # Get the email
    email = request.form.get('email')

    # Simple check to see if the email was provided. Flash error if not
    if email is None or not len(email):
        flash_error("Please enter an email address!")
        return render_template('account/trigger_reset.html',  form_fill=values)

    # Get the account for this email
    account = Account.by_email(email)

    # If no account is found we let the user know that it's not registered
    if account is None:
        flash_error("No user is registered under this address!")
        return render_template('account/trigger_reset.html',  form_fill=values)

    account.reset_loginhash()
    db.session.commit()



    # Send the reset link to the email of this account
    sendhash(account)


    # Redirect to the login page
    return redirect(url_for('account.email_message', id=account.id))
Esempio n. 49
0
def make_account(name='test', fullname='Test User',
                 email='*****@*****.**', twitter='testuser',
                 admin=False):
    from openspending.model.account import Account

    # First see if the account already exists and if so, return it
    account = Account.by_name(name)
    if account:
        return account

    # Account didn't exist so we create it and return it
    account = Account()
    account.name = name
    account.fullname = fullname
    account.email = email
    account.twitter_handle = twitter
    account.admin = admin
    db.session.add(account)
    db.session.commit()

    return account
Esempio n. 50
0
    def trigger_reset(self):
        """
        Allow user to trigger a reset of the password in case they forget it
        """

        # Disable the cache
        self._disable_cache()

        # If it's a simple GET method we return the form
        if request.method == 'GET':
            return templating.render('account/trigger_reset.html')

        # Get the email
        email = request.params.get('email')

        # Simple check to see if the email was provided. Flash error if not
        if email is None or not len(email):
            h.flash_error(_("Please enter an email address!"))
            return templating.render('account/trigger_reset.html')

        # Get the account for this email
        account = Account.by_email(email)

        # If no account is found we let the user know that it's not registered
        if account is None:
            h.flash_error(_("No user is registered under this address!"))
            return templating.render('account/trigger_reset.html')

        # Send the reset link to the email of this account
        send_reset_link(account)

        # Let the user know that email with link has been sent
        h.flash_success(
            _("You've received an email with a link to reset your " +
              "password. Please check your inbox."))

        # Redirect to the login page
        redirect(h.url_for(controller='account', action='login'))
Esempio n. 51
0
    def trigger_reset(self):
        """
        Allow user to trigger a reset of the password in case they forget it
        """

        # Disable the cache
        self._disable_cache()

        # If it's a simple GET method we return the form
        if request.method == 'GET':
            return templating.render('account/trigger_reset.html')

        # Get the email
        email = request.params.get('email')

        # Simple check to see if the email was provided. Flash error if not
        if email is None or not len(email):
            h.flash_error(_("Please enter an email address!"))
            return templating.render('account/trigger_reset.html')

        # Get the account for this email
        account = Account.by_email(email)

        # If no account is found we let the user know that it's not registered
        if account is None:
            h.flash_error(_("No user is registered under this address!"))
            return templating.render('account/trigger_reset.html')

        # Send the reset link to the email of this account
        send_reset_link(account)

        # Let the user know that email with link has been sent
        h.flash_success(_("You've received an email with a link to reset your "
            + "password. Please check your inbox."))

        # Redirect to the login page
        redirect(h.url_for(controller='account', action='login'))
Esempio n. 52
0
def make_account(name='test', fullname='Test User',
                 email='*****@*****.**', 
                 admin=False, verified=True):
    from openspending.model.account import Account

    # First see if the account already exists and if so, return it
    account = Account.by_email(email)
    if account:
        return account

    # Account didn't exist so we create it and return it
    account = Account()
    account.fullname = fullname
    account.email = email
    account.admin = admin
    account.verified = verified
    db.session.add(account)
    db.session.commit()
    return account
Esempio n. 53
0
    def register(self):
        require.account.create()
        c.config = config
        self._disable_cache()
        errors, values = {}, None
        if request.method == 'POST':
            try:
                schema = AccountRegister()
                values = request.params
                data = schema.deserialize(values)
                if Account.by_name(data['name']):
                    raise colander.Invalid(
                        AccountRegister.name,
                        _("Login name already exists, please choose a "
                          "different one"))
                if not data['password1'] == data['password2']:
                    raise colander.Invalid(AccountRegister.password1,
                                           _("Passwords don't match!"))
                account = Account()
                account.name = data['name']
                account.fullname = data['fullname']
                account.email = data['email']
                account.password = generate_password_hash(data['password1'])
                db.session.add(account)
                db.session.commit()
                who_api = get_api(request.environ)
                authenticated, headers = who_api.login({
                    "login": account.name,
                    "password": data['password1']
                })

                errors = subscribe_lists(('community', 'developer'), data)
                if errors:
                    h.flash_notice(_("Subscription to the following mailing " +
                            "lists probably failed: %s.") % ', '.join(errors))

                response.headers.extend(headers)
                return redirect("/")
            except colander.Invalid, i:
                errors = i.asdict()
Esempio n. 54
0
def register():
    """ Perform registration of a new user """
    errors, values = {}, dict(request.form.items())

    try:
        # Grab the actual data and validate it
        data = AccountRegister().deserialize(values)

        #check if email is already registered
            # it is, then send the email hash for the login

        #check that email is real
        #get the domain
        print data['email']
        if (data['email'].find('@') == -1 or data['email'].find('.') == -1):
            raise colander.Invalid(AccountRegister.email,
                    "You must use a valid USG email address")

        domain = data['email'][data['email'].find('@') + 1:]

        if 'EMAIL_WHITELIST' not in current_app.config.keys():
            raise colander.Invalid(AccountRegister.email,
                "System not set correctly.  Please contact the administrator.")

        domainvalid = False

        for domainemail in current_app.config['EMAIL_WHITELIST']:
            if domain.lower() == domainemail.lower():
                domainvalid = True

        if not domainvalid:
            raise colander.Invalid(AccountRegister.email,
                "Your email is not available for registration.  Currently it is only available for US Government emails.")



        # Check if the username already exists, return an error if so
        if Account.by_email(data['email']):
            #resend the hash here to the email and notify the user
            raise colander.Invalid(
                AccountRegister.email,
                "Login Name already exists.  Click reset password.")



        # Create the account
        account = Account()
        account.fullname = data['fullname']
        account.email = data['email']
        

        db.session.add(account)
        db.session.commit()

        # Perform a login for the user
        #login_user(account, remember=True)

        sendhash(account)


        # TO DO redirect to email sent page
        return redirect(url_for('account.email_message', id=account.id))
    except colander.Invalid as i:
        errors = i.asdict()
    values["csrf_token"] = generate_csrf_token()
    return render_template('account/login.jade', form_fill=values,
                           form_errors=errors)
Esempio n. 55
0
    def register(self):
        """
        Perform registration of a new user
        """

        # We must allow account creation
        require.account.create()

        # We add the config as a context variable in case anything happens
        # (like with login we need this to allow subscriptions to mailing lists)
        c.config = config

        # Disable the cache (don't want anything getting in the way)
        self._disable_cache()

        # Initial values and errors
        errors, values = {}, None

        # If this is a POST operation somebody is trying to register
        if request.method == 'POST':
            try:
                # Get the account register schema (for validation)
                schema = AccountRegister()

                # Set values from the request parameters
                # (for validation and so we can autofill forms)
                values = request.params

                # Grab the actual data and validate it
                data = schema.deserialize(values)

                # Check if the username already exists, return an error if so
                if Account.by_name(data['name']):
                    raise colander.Invalid(
                        AccountRegister.name,
                        _("Login name already exists, please choose a "
                          "different one"))

                # Check if passwords match, return error if not
                if not data['password1'] == data['password2']:
                    raise colander.Invalid(AccountRegister.password1,
                                           _("Passwords don't match!"))

                # Create the account
                account = Account()

                # Set username and full name
                account.name = data['name']
                account.fullname = data['fullname']

                # Set email and if email address should be public
                account.email = data['email']
                account.public_email = data['public_email']

                # Hash the password and store the hash
                account.password = generate_password_hash(data['password1'])

                # Commit the new user account to the database
                db.session.add(account)
                db.session.commit()

                # Perform a login for the user
                who_api = get_api(request.environ)
                authenticated, headers = who_api.login({
                    "login": account.name,
                    "password": data['password1']
                })
                # Add the login headers
                response.headers.extend(headers)

                # Subscribe the user to the mailing lists
                errors = subscribe_lists(('community', 'developer'), data)
                # Notify if the mailing list subscriptions failed
                if errors:
                    h.flash_notice(_("Subscription to the following mailing " +
                            "lists probably failed: %s.") % ', '.join(errors))

                # Registration successful - Redirect to the front page
                return redirect("/")
            except colander.Invalid, i:
                # Mark colander errors
                errors = i.asdict()