コード例 #1
0
ファイル: account.py プロジェクト: mariarivera30/PybossaBL
def _show_own_profile(user, form, can_update):
    user_dict = cached_users.get_user_summary(user.name)
    rank_and_score = cached_users.rank_and_score(user.id)
    user.rank = rank_and_score['rank']
    user.score = rank_and_score['score']
    user.total = cached_users.get_total_users()
    projects_contributed = cached_users.public_projects_contributed_cached(
        user.id)
    projects_published, projects_draft = _get_user_projects(user.id)
    cached_users.get_user_summary(user.name)

    response = dict(template='account/profile.html',
                    title=gettext("Profile"),
                    projects_contrib=projects_contributed,
                    projects_published=projects_published,
                    projects_draft=projects_draft,
                    user=user_dict,
                    form=form,
                    can_update=can_update,
                    private_instance=bool(data_access_levels),
                    upref_mdata_enabled=bool(app_settings.upref_mdata))

    response = make_response(handle_content_type(response))
    response.headers['Cache-Control'] = 'no-store'
    response.headers['Pragma'] = 'no-cache'
    return response
コード例 #2
0
ファイル: jobs.py プロジェクト: liubin192837/pybossa
def warm_cache():  # pragma: no cover
    """Background job to warm cache."""
    from pybossa.core import create_app
    app = create_app(run_as_server=False)
    # Cache 3 pages
    projects_cached = []
    pages = range(1, 4)
    import pybossa.cache.projects as cached_projects
    import pybossa.cache.categories as cached_cat
    import pybossa.cache.users as cached_users
    import pybossa.cache.project_stats as stats

    def warm_project(_id, short_name, featured=False):
        if _id not in projects_cached:
            cached_projects.get_project(short_name)
            cached_projects.n_tasks(_id)
            n_task_runs = cached_projects.n_task_runs(_id)
            cached_projects.overall_progress(_id)
            cached_projects.last_activity(_id)
            cached_projects.n_completed_tasks(_id)
            cached_projects.n_volunteers(_id)
            if n_task_runs >= 1000 or featured:
                # print ("Getting stats for %s as it has %s task runs" %
                #        (short_name, n_task_runs))
                stats.get_stats(_id, app.config.get('GEO'))
            projects_cached.append(_id)

    # Cache top projects
    projects = cached_projects.get_top()
    for p in projects:
        warm_project(p['id'], p['short_name'])
    for page in pages:
        projects = cached_projects.get_featured('featured', page,
                                                app.config['APPS_PER_PAGE'])
        for p in projects:
            warm_project(p['id'], p['short_name'], featured=True)

    # Categories
    categories = cached_cat.get_used()
    for c in categories:
        for page in pages:
            projects = cached_projects.get(c['short_name'], page,
                                           app.config['APPS_PER_PAGE'])
            for p in projects:
                warm_project(p['id'], p['short_name'])
    # Users
    users = cached_users.get_leaderboard(app.config['LEADERBOARD'],
                                         'anonymous')
    for user in users:
        # print "Getting stats for %s" % user['name']
        cached_users.get_user_summary(user['name'])
        cached_users.projects_contributed_cached(user['id'])
        cached_users.published_projects_cached(user['id'])
        cached_users.draft_projects_cached(user['id'])

    cached_users.get_top()

    return True
コード例 #3
0
ファイル: jobs.py プロジェクト: Genius38/pybossa-1
def warm_cache():  # pragma: no cover
    """Background job to warm cache."""
    from pybossa.core import create_app
    app = create_app(run_as_server=False)
    projects_cached = []
    import pybossa.cache.projects as cached_projects
    import pybossa.cache.categories as cached_cat
    import pybossa.cache.users as cached_users
    import pybossa.cache.project_stats as stats
    from pybossa.util import rank
    from pybossa.core import user_repo

    def warm_project(_id, short_name, featured=False):
        if _id not in projects_cached:
            #cached_projects.get_project(short_name)
            #cached_projects.n_tasks(_id)
            #n_task_runs = cached_projects.n_task_runs(_id)
            #cached_projects.overall_progress(_id)
            #cached_projects.last_activity(_id)
            #cached_projects.n_completed_tasks(_id)
            #cached_projects.n_volunteers(_id)
            #cached_projects.browse_tasks(_id)
            #if n_task_runs >= 1000 or featured:
            #    # print ("Getting stats for %s as it has %s task runs" %
            #    #        (short_name, n_task_runs))
            stats.update_stats(_id, app.config.get('GEO'))
            projects_cached.append(_id)

    # Cache top projects
    projects = cached_projects.get_top()
    for p in projects:
        warm_project(p['id'], p['short_name'])

    # Cache 3 pages
    to_cache = 3 * app.config['APPS_PER_PAGE']
    projects = rank(cached_projects.get_all_featured('featured'))[:to_cache]
    for p in projects:
        warm_project(p['id'], p['short_name'], featured=True)

    # Categories
    categories = cached_cat.get_used()
    for c in categories:
        projects = rank(cached_projects.get_all(c['short_name']))[:to_cache]
        for p in projects:
            warm_project(p['id'], p['short_name'])
    # Users
    users = cached_users.get_leaderboard(app.config['LEADERBOARD'])
    for user in users:
        # print "Getting stats for %s" % user['name']
        print user_repo
        u = user_repo.get_by_name(user['name'])
        cached_users.get_user_summary(user['name'])
        cached_users.projects_contributed_cached(u.id)
        cached_users.published_projects_cached(u.id)
        cached_users.draft_projects_cached(u.id)

    return True
コード例 #4
0
ファイル: jobs.py プロジェクト: fiorda/pybossa
def warm_cache():  # pragma: no cover
    """Background job to warm cache."""
    from pybossa.core import create_app
    app = create_app(run_as_server=False)
    projects_cached = []
    import pybossa.cache.projects as cached_projects
    import pybossa.cache.categories as cached_cat
    import pybossa.cache.users as cached_users
    import pybossa.cache.project_stats as stats
    from pybossa.util import rank
    from pybossa.core import user_repo

    def warm_project(_id, short_name, featured=False):
        if _id not in projects_cached:
            #cached_projects.get_project(short_name)
            #cached_projects.n_tasks(_id)
            #n_task_runs = cached_projects.n_task_runs(_id)
            #cached_projects.overall_progress(_id)
            #cached_projects.last_activity(_id)
            #cached_projects.n_completed_tasks(_id)
            #cached_projects.n_volunteers(_id)
            #cached_projects.browse_tasks(_id)
            #if n_task_runs >= 1000 or featured:
            #    # print ("Getting stats for %s as it has %s task runs" %
            #    #        (short_name, n_task_runs))
            stats.update_stats(_id, app.config.get('GEO'))
            projects_cached.append(_id)

    # Cache top projects
    projects = cached_projects.get_top()
    for p in projects:
        warm_project(p['id'], p['short_name'])

    # Cache 3 pages
    to_cache = 3 * app.config['APPS_PER_PAGE']
    projects = rank(cached_projects.get_all_featured('featured'))[:to_cache]
    for p in projects:
        warm_project(p['id'], p['short_name'], featured=True)

    # Categories
    categories = cached_cat.get_used()
    for c in categories:
        projects = rank(cached_projects.get_all(c['short_name']))[:to_cache]
        for p in projects:
            warm_project(p['id'], p['short_name'])
    # Users
    users = cached_users.get_leaderboard(app.config['LEADERBOARD'])
    for user in users:
        # print "Getting stats for %s" % user['name']
        print user_repo
        u = user_repo.get_by_name(user['name'])
        cached_users.get_user_summary(user['name'])
        cached_users.projects_contributed_cached(u.id)
        cached_users.published_projects_cached(u.id)
        cached_users.draft_projects_cached(u.id)

    return True
コード例 #5
0
ファイル: account.py プロジェクト: copra2005/pybossa
def _show_own_profile(user):
    rank_and_score = cached_users.rank_and_score(user.id)
    user.rank = rank_and_score['rank']
    user.score = rank_and_score['score']
    user.total = cached_users.get_total_users()
    projects_contributed = cached_users.projects_contributed_cached(user.id)
    projects_published, projects_draft = _get_user_projects(user.id)
    cached_users.get_user_summary(user.name)

    return render_template('account/profile.html', title=gettext("Profile"),
                           projects_contrib=projects_contributed,
                           projects_published=projects_published,
                           projects_draft=projects_draft,
                           user=user)
コード例 #6
0
ファイル: account.py プロジェクト: bluetropic/pybossa
def _show_own_profile(user):
    rank_and_score = cached_users.rank_and_score(user.id)
    user.rank = rank_and_score['rank']
    user.score = rank_and_score['score']
    user.total = cached_users.get_total_users()
    projects_contributed = cached_users.projects_contributed_cached(user.id)
    projects_published, projects_draft = _get_user_projects(user.id)
    cached_users.get_user_summary(user.name)

    return render_template('account/profile.html', title=gettext("Profile"),
                           projects_contrib=projects_contributed,
                           projects_published=projects_published,
                           projects_draft=projects_draft,
                           user=user)
コード例 #7
0
ファイル: account.py プロジェクト: mariarivera30/PybossaBL
def _show_public_profile(user, form, can_update):
    if current_user.id == user.id:
        user_dict = cached_users.get_user_summary(user.name)
    else:
        user_dict = cached_users.public_get_user_summary(user.name)
    if current_user.admin:
        user_dict['email_addr'] = user.email_addr
    projects_contributed = cached_users.public_projects_contributed_cached(
        user.id)
    projects_created = cached_users.public_published_projects_cached(user.id)
    total_projects_contributed = '{} / {}'.format(
        cached_users.n_projects_contributed(user.id), n_published())
    percentage_tasks_completed = user_dict['n_answers'] * 100 / (
        n_total_tasks() or 1)

    if current_user.is_authenticated() and current_user.admin:
        draft_projects = cached_users.draft_projects(user.id)
        projects_created.extend(draft_projects)

    title = "%s · User Profile" % user_dict['fullname']
    response = dict(template='/account/public_profile.html',
                    title=title,
                    user=user_dict,
                    projects=projects_contributed,
                    projects_created=projects_created,
                    total_projects_contributed=total_projects_contributed,
                    percentage_tasks_completed=percentage_tasks_completed,
                    form=form,
                    can_update=can_update,
                    private_instance=bool(data_access_levels),
                    upref_mdata_enabled=bool(app_settings.upref_mdata))

    return handle_content_type(response)
コード例 #8
0
ファイル: account.py プロジェクト: epiraces/pybossa
def settings():
    #user = User.query.get_or_404(current_user.id)
    user, apps, apps_created = cached_users.get_user_summary(current_user.name)
    title = "User: %s · Settings" % user['fullname']
    return render_template('account/settings.html',
                           title=title,
                           user=user)
コード例 #9
0
ファイル: account.py プロジェクト: fiorda/pybossa
def _show_own_profile(user):
    user_dict = cached_users.get_user_summary(user.name)
    rank_and_score = cached_users.rank_and_score(user.id)
    user.rank = rank_and_score['rank']
    user.score = rank_and_score['score']
    user.total = cached_users.get_total_users()
    projects_contributed = cached_users.public_projects_contributed_cached(user.id)
    projects_published, projects_draft = _get_user_projects(user.id)
    cached_users.get_user_summary(user.name)

    response = dict(template='account/profile.html', title=gettext("Profile"),
                    projects_contrib=projects_contributed,
                    projects_published=projects_published,
                    projects_draft=projects_draft,
                    user=user_dict)

    return handle_content_type(response)
コード例 #10
0
ファイル: account.py プロジェクト: russkociuba/pybossa
def _show_own_profile(user):
    user_dict = cached_users.get_user_summary(user.name)
    rank_and_score = cached_users.rank_and_score(user.id)
    user.rank = rank_and_score['rank']
    user.score = rank_and_score['score']
    user.total = cached_users.get_total_users()
    projects_contributed = cached_users.public_projects_contributed_cached(user.id)
    projects_published, projects_draft = _get_user_projects(user.id)
    cached_users.get_user_summary(user.name)

    response = dict(template='account/profile.html', title=gettext("Profile"),
                    projects_contrib=projects_contributed,
                    projects_published=projects_published,
                    projects_draft=projects_draft,
                    user=user_dict)

    return handle_content_type(response)
コード例 #11
0
ファイル: account.py プロジェクト: idahoan/pybossa
def _show_own_profile(user):
    rank_and_score = cached_users.rank_and_score(user.id)
    user.rank = rank_and_score['rank']
    user.score = rank_and_score['score']
    user.total = cached_users.get_total_users()
    user.valid_email = user.valid_email
    user.confirmation_email_sent = user.confirmation_email_sent
    apps_contributed = cached_users.apps_contributed_cached(user.id)
    apps_published, apps_draft = _get_user_apps(user.id)
    apps_published.extend(cached_users.hidden_apps(user.id))
    cached_users.get_user_summary(user.name)

    return render_template('account/profile.html',
                           title=gettext("Profile"),
                           apps_contrib=apps_contributed,
                           apps_published=apps_published,
                           apps_draft=apps_draft,
                           user=user)
コード例 #12
0
    def test_get_user_summary_returns_fields(self):
        """Test CACHE USERS get_user_summary all the fields in the dict"""
        UserFactory.create(name='user')
        fields = ('id', 'name', 'fullname', 'created', 'api_key', 'info',
                  'admin', 'email_addr', 'n_answers', 'rank', 'score', 'total')
        user = cached_users.get_user_summary('user')

        for field in fields:
            assert field in list(user.keys()), field
コード例 #13
0
ファイル: account.py プロジェクト: ywrsusan/pybossa
def add_metadata(name):
    """
    Admin can save metadata for selected user.
    Regular user can save their own metadata.

    Redirects to public profile page for selected user.

    """
    user = user_repo.get_by_name(name=name)
    (can_update, disabled_fields) = can_update_user_info(current_user, user)
    if not can_update:
        abort(403)
    form_data = get_form_data(request, user, disabled_fields)
    form = UserPrefMetadataForm(form_data,
                                can_update=(can_update, disabled_fields))
    form.set_upref_mdata_choices()

    if not form.validate():
        if current_user.id == user.id:
            user_dict = cached_users.get_user_summary(user.name)
        else:
            user_dict = cached_users.public_get_user_summary(user.name)
        projects_contributed = cached_users.projects_contributed_cached(
            user.id)
        projects_created = cached_users.published_projects_cached(user.id)
        total_projects_contributed = '{} / {}'.format(
            cached_users.n_projects_contributed(user.id), n_published())
        percentage_tasks_completed = user_dict['n_answers'] * 100 / (
            n_total_tasks() or 1)
        if current_user.is_authenticated and current_user.admin:
            draft_projects = cached_users.draft_projects(user.id)
            projects_created.extend(draft_projects)
        title = "%s · User Profile" % user.name
        flash("Please fix the errors", 'message')
        return render_template(
            '/account/public_profile.html',
            title=title,
            user=user,
            projects=projects_contributed,
            projects_created=projects_created,
            total_projects_contributed=total_projects_contributed,
            percentage_tasks_completed=percentage_tasks_completed,
            form=form,
            input_form=True,
            can_update=can_update,
            upref_mdata_enabled=bool(app_settings.upref_mdata))

    user_pref, metadata = get_user_pref_and_metadata(name, form)
    user.info['metadata'] = metadata
    ensure_data_access_assignment_from_form(user.info, form)
    user.user_pref = user_pref
    user_repo.update(user)
    cached_users.delete_user_pref_metadata(user.name)
    cached_users.delete_user_access_levels_by_id(user.id)
    delete_memoized(get_user_preferences, user.id)
    flash("Input saved successfully", "info")
    return redirect(url_for('account.profile', name=name))
コード例 #14
0
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)

    if not user.admin :        
        if is_amnesty_sso_enable():        
            return redirect(amnesty_url_for('/<name>/'))

    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')
    # Creation of forms
    update_form = UpdateProfileForm(obj=user)
    update_form.set_locales(current_app.config['LOCALES'])

    avatar_form = AvatarUploadForm()
    password_form = ChangePasswordForm()

    if request.method == 'POST':

        # Update user avatar
        if request.form.get('btn') == 'Upload':
            _handle_avatar_update(user, avatar_form)
        # Update user profile
        elif request.form.get('btn') == 'Profile':
            _handle_profile_update(user, update_form)
        # Update user password
        elif request.form.get('btn') == 'Password':
            _handle_password_update(user, password_form)
        # Update user external services
        elif request.form.get('btn') == 'External':
            _handle_external_services_update(user, update_form)
        # Otherwise return 415
        else:
            return abort(415)
        return redirect(url_for('.update_profile', name=user.name))

    title_msg = "Update your profile: %s" % user.fullname
    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)
コード例 #15
0
    def test_get_user_summary_returns_fields(self):
        """Test CACHE USERS get_user_summary all the fields in the dict"""
        UserFactory.create(name='user')
        fields = ('id', 'name', 'fullname', 'created', 'api_key',
                  'twitter_user_id', 'google_user_id', 'facebook_user_id',
                  'info', 'email_addr', 'n_answers', 'rank', 'score', 'total')
        user = cached_users.get_user_summary('user')

        for field in fields:
            assert field in user.keys(), field
コード例 #16
0
    def test_get_user_summary_user_exists(self):
        """Test CACHE USERS get_user_summary returns a dict with the user data
        if the user exists"""
        UserFactory.create(name='zidane')
        UserFactory.create(name='figo')

        zizou = cached_users.get_user_summary('zidane')

        assert type(zizou) is dict, type(zizou)
        assert zizou != None, zizou
コード例 #17
0
    def test_get_user_summary_user_exists(self):
        """Test CACHE USERS get_user_summary returns a dict with the user data
        if the user exists"""
        UserFactory.create(name='zidane')
        UserFactory.create(name='figo')

        zizou = cached_users.get_user_summary('zidane')

        assert type(zizou) is dict, type(zizou)
        assert zizou != None, zizou
コード例 #18
0
ファイル: account.py プロジェクト: heeroyui202/pybossa
def settings():
    """
    Configure user settings.

    Returns a Jinja2 template.

    """
    # user = User.query.get_or_404(current_user.id)
    user, apps, apps_created = cached_users.get_user_summary(current_user.name)
    title = "User: %s &middot; Settings" % user["fullname"]
    return render_template("account/settings.html", title=title, user=user)
コード例 #19
0
def public_profile(name):
    """Render the public user profile"""
    user, apps, apps_created = cached_users.get_user_summary(name)
    if user:
        title = "%s &middot; User Profile" % user['fullname']
        return render_template('/account/public_profile.html',
                               title=title,
                               user=user,
                               apps=apps,
                               apps_created=apps_created)
    else:
        abort(404)
コード例 #20
0
ファイル: account.py プロジェクト: epiraces/pybossa
def public_profile(name):
    """Render the public user profile"""
    user, apps, apps_created = cached_users.get_user_summary(name)
    if user:
        title = "%s &middot; User Profile" % user['fullname']
        return render_template('/account/public_profile.html',
                               title=title,
                               user=user,
                               apps=apps,
                               apps_created=apps_created)
    else:
        abort(404)
コード例 #21
0
ファイル: account.py プロジェクト: bluetropic/pybossa
def _show_public_profile(user):
    user_dict = cached_users.get_user_summary(user.name)
    projects_contributed = cached_users.projects_contributed_cached(user.id)
    projects_created = cached_users.published_projects_cached(user.id)
    if current_user.is_authenticated() and current_user.admin:
        draft_projects = cached_users.draft_projects(user.id)
        projects_created.extend(draft_projects)
    title = "%s &middot; User Profile" % user_dict['fullname']
    return render_template('/account/public_profile.html',
                           title=title,
                           user=user_dict,
                           projects=projects_contributed,
                           projects_created=projects_created)
コード例 #22
0
def _show_public_profile(user):
    user_dict = cached_users.get_user_summary(user.name)
    projects_contributed = cached_users.projects_contributed_cached(user.id)
    projects_created = cached_users.published_projects_cached(user.id)
    if current_user.is_authenticated() and current_user.admin:
        projects_hidden = cached_users.hidden_projects(user.id)
        projects_created.extend(projects_hidden)
    title = "%s &middot; User Profile" % user_dict['fullname']
    return render_template('/account/public_profile.html',
                           title=title,
                           user=user_dict,
                           projects=projects_contributed,
                           projects_created=projects_created)
コード例 #23
0
def settings():
    """
    Configure user settings.

    Returns a Jinja2 template.

    """
    #user = User.query.get_or_404(current_user.id)
    user, apps, apps_created = cached_users.get_user_summary(current_user.name)
    title = "User: %s &middot; Settings" % user['fullname']
    return render_template('account/settings.html',
                           title=title,
                           user=user)
コード例 #24
0
ファイル: account.py プロジェクト: chamaa/pybossa
def _show_own_profile(user):
    rank_and_score = cached_users.rank_and_score(user.id)
    user.rank = rank_and_score['rank']
    user.score = rank_and_score['score']
    user.total = cached_users.get_total_users()
    apps_contributed = cached_users.apps_contributed_cached(user.id)
    apps_published, apps_draft = _get_user_apps(user.id)
    apps_published.extend(cached_users.hidden_apps(user.id))

    return render_template('account/profile.html', title=gettext("Profile"),
                          apps_contrib=apps_contributed,
                          apps_published=apps_published,
                          apps_draft=apps_draft,
                          user=cached_users.get_user_summary(user.name))
コード例 #25
0
ファイル: account.py プロジェクト: bcfuchs/pybossa
def _show_public_profile(user):
    user_dict = cached_users.get_user_summary(user.name)
    apps_contributed = cached_users.apps_contributed_cached(user.id)
    apps_created = cached_users.published_apps_cached(user.id)
    if current_user.is_authenticated() and current_user.admin:
        apps_hidden = cached_users.hidden_apps(user.id)
        apps_created.extend(apps_hidden)
    if user_dict:
        title = "%s &middot; User Profile" % user_dict['fullname']
        return render_template('/account/public_profile.html',
                               title=title,
                               user=user_dict,
                               apps=apps_contributed,
                               apps_created=apps_created)
コード例 #26
0
ファイル: account.py プロジェクト: jinwg/pybossa
def add_metadata(name):
    """
    Admin can save metadata for selected user
    Redirects to public profile page for selected user.
    """
    user = user_repo.get_by_name(name=name)
    form = UserPrefMetadataForm(request.form)
    form.set_upref_mdata_choices()
    if not form.validate():
        if current_user.id == user.id:
            user_dict = cached_users.get_user_summary(user.name)
        else:
            user_dict = cached_users.public_get_user_summary(user.name)
        projects_contributed = cached_users.projects_contributed_cached(
            user.id)
        projects_created = cached_users.published_projects_cached(user.id)
        if current_user.is_authenticated() and current_user.admin:
            draft_projects = cached_users.draft_projects(user.id)
            projects_created.extend(draft_projects)
        title = "%s &middot; User Profile" % user.name
        flash("Please fix the errors", 'message')
        can_update = current_user.admin
        return render_template('/account/public_profile.html',
                               title=title,
                               user=user_dict,
                               projects=projects_contributed,
                               projects_created=projects_created,
                               form=form,
                               can_update=can_update,
                               input_form=True)

    user_pref, metadata = get_user_pref_and_metadata(name, form)
    user.info['metadata'] = metadata
    user.user_pref = user_pref
    user_repo.update(user)
    cached_users.delete_user_pref_metadata(user.name)
    flash("Input saved successfully", "info")
    return redirect(url_for('account.profile', name=name))
コード例 #27
0
def add_metadata(name):
    """
    Admin can save metadata for selected user
    Redirects to public profile page for selected user.
    """
    user = user_repo.get_by_name(name=name)
    form = UserPrefMetadataForm(request.form)
    form.set_upref_mdata_choices()
    if not form.validate():
        if current_user.id == user.id:
            user_dict = cached_users.get_user_summary(user.name)
        else:
            user_dict = cached_users.public_get_user_summary(user.name)
        projects_contributed = cached_users.projects_contributed_cached(user.id)
        projects_created = cached_users.published_projects_cached(user.id)
        if current_user.is_authenticated() and current_user.admin:
            draft_projects = cached_users.draft_projects(user.id)
            projects_created.extend(draft_projects)
        title = "%s &middot; User Profile" % user.name
        flash("Please fix the errors", 'message')
        can_update = current_user.admin
        return render_template('/account/public_profile.html',
                               title=title,
                               user=user_dict,
                               projects=projects_contributed,
                               projects_created=projects_created,
                               form=form,
                               can_update=can_update,
                               input_form=True)

    user_pref, metadata = get_user_pref_and_metadata(name, form)
    user.info['metadata'] = metadata
    user.user_pref = user_pref
    user_repo.update(user)
    cached_users.delete_user_pref_metadata(user.name)
    flash("Input saved successfully", "info")
    return redirect(url_for('account.profile', name=name))
コード例 #28
0
    def test_get_user_summary_nousers(self):
        """Test CACHE USERS get_user_summary returns None if no user exists with
        the name requested"""
        user = cached_users.get_user_summary('nouser')

        assert user is None, user
コード例 #29
0
ファイル: account.py プロジェクト: mariarivera30/PybossaBL
def update_profile(name):
    """
    Update user's profile.

    Returns Jinja2 template.

    """
    user = user_repo.get_by_name(name)
    if not user:
        return abort(404)
    if current_user.name != name:
        return abort(403)
    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')
    btn = request.body.get('btn', 'None').capitalize()
    if 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
        btn = request.body.get('btn', 'None').capitalize()
        if btn == 'Upload':
            succeed = _handle_avatar_update(user, avatar_form)
        # Update user profile
        elif btn == 'Profile':
            succeed = _handle_profile_update(user, update_form)
        # Update user password
        elif btn == 'Password':
            succeed = _handle_password_update(user, password_form)
        # Update user external services
        elif btn == 'External':
            succeed = _handle_external_services_update(user, update_form)
        # Otherwise return 415
        else:
            return abort(415)
        if succeed:
            cached_users.delete_user_summary(user.name)
            return redirect_content_type(url_for('.update_profile',
                                                 name=user.name),
                                         status=SUCCESS)
        else:
            data = dict(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 handle_content_type(data)

    data = dict(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 handle_content_type(data)
コード例 #30
0
def profile(name):
    """
    Get user profile.

    Returns a Jinja2 template with the user information.

    """
    user = db.session.query(model.user.User).filter_by(name=name).first()

    if user is None:
        return abort(404)

    # Show public profile from another user
    if current_user.is_anonymous() or (user.id != current_user.id):
        user, apps_contributed, _ = cached_users.get_user_summary(name)
        apps_created, apps_draft = _get_user_apps(user['id'])
        if user:
            title = "%s &middot; User Profile" % user['fullname']
            return render_template('/account/public_profile.html',
                                   title=title,
                                   user=user,
                                   apps=apps_contributed,
                                   apps_created=apps_created)

    # Show user profile page with admin, as it is the same user
    if user.id == current_user.id and current_user.is_authenticated():
        sql = text('''
                   SELECT app.name, app.short_name, app.info,
                   COUNT(*) as n_task_runs
                   FROM task_run JOIN app ON
                   (task_run.app_id=app.id) WHERE task_run.user_id=:user_id
                   GROUP BY app.name, app.short_name, app.info
                   ORDER BY n_task_runs DESC;''')

        # results will have the following format
        # (app.name, app.short_name, n_task_runs)
        results = db.engine.execute(sql, user_id=current_user.id)

        apps_contrib = []
        for row in results:
            app = dict(name=row.name,
                       short_name=row.short_name,
                       info=json.loads(row.info),
                       n_task_runs=row.n_task_runs)
            apps_contrib.append(app)

        # Rank
        # See: https://gist.github.com/tokumine/1583695
        sql = text('''
                   WITH global_rank AS (
                        WITH scores AS (
                            SELECT user_id, COUNT(*) AS score FROM task_run
                            WHERE user_id IS NOT NULL GROUP BY user_id)
                        SELECT user_id, score, rank() OVER (ORDER BY score desc)
                        FROM scores)
                   SELECT * from global_rank WHERE user_id=:user_id;
                   ''')

        results = db.engine.execute(sql, user_id=current_user.id)
        for row in results:
            user.rank = row.rank
            user.score = row.score

        user.total = db.session.query(model.user.User).count()

        apps_published, apps_draft = _get_user_apps(current_user.id)

        return render_template('account/profile.html',
                               title=gettext("Profile"),
                               apps_contrib=apps_contrib,
                               apps_published=apps_published,
                               apps_draft=apps_draft,
                               user=user)
コード例 #31
0
ファイル: account.py プロジェクト: idahoan/pybossa
def update_profile(name):
    """
    Update user's profile.

    Returns Jinja2 template.

    """
    user = user_repo.get_by_name(name)
    if not user:
        return abort(404)
    require.user.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')
    # Title page
    title_msg = "Update your profile: %s" % user.fullname
    # Creation of forms
    update_form = UpdateProfileForm(obj=user)
    update_form.set_locales(current_app.config['LOCALES'])
    avatar_form = AvatarUploadForm()
    password_form = ChangePasswordForm()
    external_form = update_form

    if request.method == 'GET':
        return render_template('account/update.html',
                               title=title_msg,
                               user=usr,
                               form=update_form,
                               upload_form=avatar_form,
                               password_form=password_form,
                               external_form=external_form,
                               show_passwd_form=show_passwd_form)
    else:
        acc_conf_dis = current_app.config.get('ACCOUNT_CONFIRMATION_DISABLED')
        # Update user avatar
        if request.form.get('btn') == 'Upload':
            avatar_form = AvatarUploadForm()
            if avatar_form.validate_on_submit():
                file = request.files['avatar']
                coordinates = (avatar_form.x1.data, avatar_form.y1.data,
                               avatar_form.x2.data, avatar_form.y2.data)
                prefix = time.time()
                file.filename = "%s_avatar.png" % prefix
                container = "user_%s" % user.id
                uploader.upload_file(file,
                                     container=container,
                                     coordinates=coordinates)
                # Delete previous avatar from storage
                if user.info.get('avatar'):
                    uploader.delete_file(user.info['avatar'], container)
                user.info = {'avatar': file.filename, 'container': container}
                user_repo.update(user)
                cached_users.delete_user_summary(user.name)
                flash(
                    gettext('Your avatar has been updated! It may \
                              take some minutes to refresh...'), 'success')
                return redirect(url_for('.update_profile', name=user.name))
            else:
                flash(
                    "You have to provide an image file to update your avatar",
                    "error")
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Update user profile
        elif request.form.get('btn') == 'Profile':
            update_form = UpdateProfileForm()
            update_form.set_locales(current_app.config['LOCALES'])
            if update_form.validate():
                user.id = update_form.id.data
                user.fullname = update_form.fullname.data
                user.name = update_form.name.data
                if (user.email_addr != update_form.email_addr.data
                        and acc_conf_dis is False):
                    user.valid_email = False
                    user.newsletter_prompted = False
                    account = dict(fullname=update_form.fullname.data,
                                   name=update_form.name.data,
                                   email_addr=update_form.email_addr.data)
                    confirm_url = get_email_confirmation_url(account)
                    subject = ('You have updated your email in %s! Verify it' \
                               % current_app.config.get('BRAND'))
                    msg = dict(subject=subject,
                               recipients=[update_form.email_addr.data],
                               body=render_template(
                                   '/account/email/validate_email.md',
                                   user=account,
                                   confirm_url=confirm_url))
                    msg['html'] = markdown(msg['body'])
                    mail_queue.enqueue(send_mail, msg)
                    user.confirmation_email_sent = True
                    fls = gettext('An email has been sent to verify your \
                                  new email: %s. Once you verify it, it will \
                                  be updated.' % account['email_addr'])
                    flash(fls, 'info')
                if acc_conf_dis:
                    user.email_addr = update_form.email_addr.data
                user.privacy_mode = update_form.privacy_mode.data
                user.locale = update_form.locale.data
                user_repo.update(user)
                cached_users.delete_user_summary(user.name)
                flash(gettext('Your profile has been updated!'), 'success')
                return redirect(url_for('.update_profile', name=user.name))
            else:
                flash(gettext('Please correct the errors'), 'error')
                title_msg = 'Update your profile: %s' % user.fullname
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)

        # Update user password
        elif request.form.get('btn') == 'Password':
            # Update the data because passing it in the constructor does not work
            update_form.name.data = user.name
            update_form.fullname.data = user.fullname
            update_form.email_addr.data = user.email_addr
            update_form.ckan_api.data = user.ckan_api
            external_form = update_form
            if password_form.validate_on_submit():
                user = user_repo.get(user.id)
                if user.check_password(password_form.current_password.data):
                    user.set_password(password_form.new_password.data)
                    user_repo.update(user)
                    flash(
                        gettext('Yay, you changed your password succesfully!'),
                        'success')
                    return redirect(url_for('.update_profile', name=name))
                else:
                    msg = gettext("Your current password doesn't match the "
                                  "one in our records")
                    flash(msg, 'error')
                    return render_template('/account/update.html',
                                           form=update_form,
                                           upload_form=avatar_form,
                                           password_form=password_form,
                                           external_form=external_form,
                                           title=title_msg,
                                           show_passwd_form=show_passwd_form)
            else:
                flash(gettext('Please correct the errors'), 'error')
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Update user external services
        elif request.form.get('btn') == 'External':
            del external_form.locale
            del external_form.email_addr
            del external_form.fullname
            del external_form.name
            if external_form.validate():
                user.ckan_api = external_form.ckan_api.data or None
                user_repo.update(user)
                cached_users.delete_user_summary(user.name)
                flash(gettext('Your profile has been updated!'), 'success')
                return redirect(url_for('.update_profile', name=user.name))
            else:
                flash(gettext('Please correct the errors'), 'error')
                title_msg = 'Update your profile: %s' % user.fullname
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Otherwise return 415
        else:
            return abort(415)
コード例 #32
0
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 or user.wechat_user_id or user.weibo_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')
    btn = request.body.get('btn', 'None').capitalize()
    if 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
        btn = request.body.get('btn', 'None').capitalize()
        if btn == 'Upload':
            succeed = _handle_avatar_update(user, avatar_form)
        # Update user profile
        elif btn == 'Profile':
            succeed = _handle_profile_update(user, update_form)
        # Update user password
        elif btn == 'Password':
            succeed = _handle_password_update(user, password_form)
        # Update user external services
        elif btn == 'External':
            succeed = _handle_external_services_update(user, update_form)
        # Otherwise return 415
        else:
            return abort(415)
        if succeed:
            cached_users.delete_user_summary(user.name)
            return redirect_content_type(url_for('.update_profile',
                                                 name=user.name),
                                         status=SUCCESS)
        else:
            data = dict(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 handle_content_type(data)

    data = dict(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 handle_content_type(data)
コード例 #33
0
ファイル: account.py プロジェクト: orcunacan/pybossa
def profile(name):
    """
    Get user profile.

    Returns a Jinja2 template with the user information.

    """
    user = db.session.query(model.user.User).filter_by(name=name).first()

    if user is None:
        return abort(404)

    # Show public profile from another user
    if current_user.is_anonymous() or (user.id != current_user.id):
        user, apps_contributed, _ = cached_users.get_user_summary(name)
        apps_created, apps_draft = _get_user_apps(user['id'])
        if user:
            title = "%s &middot; User Profile" % user['fullname']
            return render_template('/account/public_profile.html',
                                   title=title,
                                   user=user,
                                   apps=apps_contributed,
                                   apps_created=apps_created)

    # Show user profile page with admin, as it is the same user
    if user.id == current_user.id and current_user.is_authenticated():
        sql = text('''
                   SELECT app.name, app.short_name, app.info,
                   COUNT(*) as n_task_runs
                   FROM task_run JOIN app ON
                   (task_run.app_id=app.id) WHERE task_run.user_id=:user_id
                   GROUP BY app.name, app.short_name, app.info
                   ORDER BY n_task_runs DESC;''')

        # results will have the following format
        # (app.name, app.short_name, n_task_runs)
        results = db.engine.execute(sql, user_id=current_user.id)

        apps_contrib = []
        for row in results:
            app = dict(name=row.name, short_name=row.short_name,
                       info=json.loads(row.info), n_task_runs=row.n_task_runs)
            apps_contrib.append(app)

        # Rank
        # See: https://gist.github.com/tokumine/1583695
        sql = text('''
                   WITH global_rank AS (
                        WITH scores AS (
                            SELECT user_id, COUNT(*) AS score FROM task_run
                            WHERE user_id IS NOT NULL GROUP BY user_id)
                        SELECT user_id, score, rank() OVER (ORDER BY score desc)
                        FROM scores)
                   SELECT * from global_rank WHERE user_id=:user_id;
                   ''')

        results = db.engine.execute(sql, user_id=current_user.id)
        for row in results:
            user.rank = row.rank
            user.score = row.score

        user.total = db.session.query(model.user.User).count()

        apps_published, apps_draft = _get_user_apps(current_user.id)

        return render_template('account/profile.html', title=gettext("Profile"),
                              apps_contrib=apps_contrib,
                              apps_published=apps_published,
                              apps_draft=apps_draft,
                              user=user)
コード例 #34
0
    def test_get_user_summary_nousers(self):
        """Test CACHE USERS get_user_summary returns None if no user exists with
        the name requested"""
        user = cached_users.get_user_summary('nouser')

        assert user is None, user
コード例 #35
0
ファイル: account.py プロジェクト: davidcmm/campinaPulse
def update_profile(name):
    """
    Update user's profile.

    Returns Jinja2 template.

    """
    user = User.query.filter_by(name=name).first()
    if not user:
        return abort(404)
    require.user.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
    current_user.rank = usr.get('rank')
    current_user.score = usr.get('score')
    # Title page
    title_msg = "Update your profile: %s" % current_user.fullname
    # Creation of forms
    update_form = UpdateProfileForm(obj=user)
    update_form.set_locales(current_app.config['LOCALES'])
    avatar_form = AvatarUploadForm()
    password_form = ChangePasswordForm()
    external_form = update_form

    if request.method == 'GET':
        return render_template('account/update.html',
                               title=title_msg,
                               user=usr,
                               form=update_form,
                               upload_form=avatar_form,
                               password_form=password_form,
                               external_form=external_form,
                               show_passwd_form=show_passwd_form)
    else:
        # Update user avatar
        if request.form.get('btn') == 'Upload':
            avatar_form = AvatarUploadForm()
            if avatar_form.validate_on_submit():
                file = request.files['avatar']
                coordinates = (avatar_form.x1.data, avatar_form.y1.data,
                               avatar_form.x2.data, avatar_form.y2.data)
                prefix = time.time()
                file.filename = "%s_avatar.png" % prefix
                container = "user_%s" % current_user.id
                uploader.upload_file(file,
                                     container=container,
                                     coordinates=coordinates)
                # Delete previous avatar from storage
                if current_user.info.get('avatar'):
                    uploader.delete_file(current_user.info['avatar'],
                                         container)
                current_user.info = {
                    'avatar': file.filename,
                    'container': container
                }
                db.session.commit()
                cached_users.delete_user_summary(current_user.name)
                flash(
                    gettext('Your avatar has been updated! It may \
                              take some minutes to refresh...'), 'success')
                return redirect(
                    url_for('.update_profile', name=current_user.name))
            else:
                flash(
                    "You have to provide an image file to update your avatar",
                    "error")
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Update user profile
        elif request.form.get('btn') == 'Profile':
            update_form = UpdateProfileForm()
            update_form.set_locales(current_app.config['LOCALES'])
            if update_form.validate():
                current_user.id = update_form.id.data
                current_user.fullname = update_form.fullname.data
                current_user.name = update_form.name.data
                current_user.email_addr = update_form.email_addr.data
                current_user.privacy_mode = update_form.privacy_mode.data
                current_user.locale = update_form.locale.data
                db.session.commit()
                cached_users.delete_user_summary(current_user.name)
                flash(gettext('Your profile has been updated!'), 'success')
                return redirect(
                    url_for('.update_profile', name=current_user.name))
            else:
                flash(gettext('Please correct the errors'), 'error')
                title_msg = 'Update your profile: %s' % current_user.fullname
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)

        # Update user password
        elif request.form.get('btn') == 'Password':
            # Update the data because passing it in the constructor does not work
            update_form.name.data = user.name
            update_form.fullname.data = user.fullname
            update_form.email_addr.data = user.email_addr
            update_form.ckan_api.data = user.ckan_api
            external_form = update_form
            if password_form.validate_on_submit():
                user = db.session.query(model.user.User).get(current_user.id)
                if user.check_password(password_form.current_password.data):
                    user.set_password(password_form.new_password.data)
                    db.session.add(user)
                    db.session.commit()
                    flash(
                        gettext('Yay, you changed your password succesfully!'),
                        'success')
                    return redirect(url_for('.update_profile', name=name))
                else:
                    msg = gettext("Your current password doesn't match the "
                                  "one in our records")
                    flash(msg, 'error')
                    return render_template('/account/update.html',
                                           form=update_form,
                                           upload_form=avatar_form,
                                           password_form=password_form,
                                           external_form=external_form,
                                           title=title_msg,
                                           show_passwd_form=show_passwd_form)
            else:
                flash(gettext('Please correct the errors'), 'error')
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Update user external services
        elif request.form.get('btn') == 'External':
            del external_form.locale
            del external_form.email_addr
            del external_form.fullname
            del external_form.name
            if external_form.validate():
                current_user.ckan_api = external_form.ckan_api.data or None
                db.session.commit()
                cached_users.delete_user_summary(current_user.name)
                flash(gettext('Your profile has been updated!'), 'success')
                return redirect(
                    url_for('.update_profile', name=current_user.name))
            else:
                flash(gettext('Please correct the errors'), 'error')
                title_msg = 'Update your profile: %s' % current_user.fullname
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Otherwise return 415
        else:
            return abort(415)
コード例 #36
0
ファイル: admin.py プロジェクト: geotagx/geotagx-plugin
def delete_user(name, confirmed):
    """
    Deletes a user on pybossa
    - Only admins will be able to delete other users.
    - Does not let delete admin users.
        Admin users will have to remove the user from the admin lists before they can delete then
    - Marks all the task_runs of the specific user as anonymous
    - Changes the ownership of all the projects owned by the user to the current_user
    TODO: Clean this feature up and push this feature to pybossa core
    """

    """
    Get the user object and contributed projects object from cache to enable
    global helper functions to render it in a uniform way.
    But Obtain the results from the non-memoized functions to get the latest state
    """
    target_user = cached_users.get_user_summary(name)
    if current_user.admin and target_user != None and current_user.id != target_user['id'] :

        user_page_redirect = request.args.get('user_page_redirect')
        if not user_page_redirect:
            user_page_redirect = 1

        if confirmed == "unconfirmed":
            published_projects = cached_users.published_projects(target_user['id'])
            draft_projects = cached_users.draft_projects(target_user['id'])
            owned_projects = published_projects + draft_projects

            return render_template('geotagx/users/delete_confirmation.html', \
                                                        target_user = target_user,
                                                        owned_projects = owned_projects,
                                                        user_page_redirect=user_page_redirect
                                                        )
        elif confirmed == "confirmed":
            """
                Retrieval of the User object necessary as the target_user object
                obtained from `cached_users.get_user_summary` doesnot expose
                the `admin` check that is necessary to prevent the user from
                deleting other admin users, and also the SQLAlchemy `delete`
                function
            """
            user_object = User.query.filter_by(id=target_user['id']).first()
            if user_object.admin:
                # It is not allowed to delete other admin users
                abort(404)

            """
                Mark all task runs by the user as anonymous
                Mark the user_ip field in the task_run by the username instead
                to retain user identity for analytics
            """
            task_runs = TaskRun.query.filter_by(user_id=target_user['id']).all()
            for task_run in task_runs:
                task_run.user_id = None
                task_run.user_ip = "deleted_user_"+target_user['name']
                db.session.commit()

            """
                Change the ownership of all projects owned by the target user
                to that of the current user
            """
            projects = Project.query.filter_by(owner_id=target_user['id']).all()
            for project in projects:
                project.owner_id = current_user.id
                db.session.commit()
                """
                    Clean cached data about the project
                """
                cached_projects.clean_project(project.id)

            """
                Delete the user from the database
            """
            db.session.delete(user_object)
            db.session.commit()

            """
                Clean user data from the cache
                Force Update current_user's data in the cache
            """
            cached_users.delete_user_summary(target_user['id'])
            cached_users.delete_user_summary(current_user.id)

            flash("User <strong>"+target_user['name']+"</strong> has been successfully deleted, and all the projects owned by the user have been transferred to you.", 'success')
            return redirect(url_for('geotagx-admin.manage_users', page=user_page_redirect))
        else:
            abort(404)
    else:
        abort(404)
コード例 #37
0
ファイル: account.py プロジェクト: bcfuchs/pybossa
def update_profile(name):
    """
    Update user's profile.

    Returns Jinja2 template.

    """
    user = User.query.filter_by(name=name).first()
    if not user:
        return abort(404)
    require.user.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
    current_user.rank = usr.get('rank')
    current_user.score = usr.get('score')
    # Title page
    title_msg = "Update your profile: %s" % current_user.fullname
    # Creation of forms
    update_form = UpdateProfileForm(obj=user)
    update_form.set_locales(current_app.config['LOCALES'])
    avatar_form = AvatarUploadForm()
    password_form = ChangePasswordForm()
    external_form = update_form


    if request.method == 'GET':
        return render_template('account/update.html',
                               title=title_msg,
                               user=usr,
                               form=update_form,
                               upload_form=avatar_form,
                               password_form=password_form,
                               external_form=external_form,
                               show_passwd_form=show_passwd_form)
    else:
        # Update user avatar
        if request.form.get('btn') == 'Upload':
            avatar_form = AvatarUploadForm()
            if avatar_form.validate_on_submit():
                file = request.files['avatar']
                coordinates = (avatar_form.x1.data, avatar_form.y1.data,
                               avatar_form.x2.data, avatar_form.y2.data)
                prefix = time.time()
                file.filename = "%s_avatar.png" % prefix
                container = "user_%s" % current_user.id
                uploader.upload_file(file,
                                     container=container,
                                     coordinates=coordinates)
                # Delete previous avatar from storage
                if current_user.info.get('avatar'):
                    uploader.delete_file(current_user.info['avatar'], container)
                current_user.info = {'avatar': file.filename,
                                     'container': container}
                db.session.commit()
                cached_users.delete_user_summary(current_user.name)
                flash(gettext('Your avatar has been updated! It may \
                              take some minutes to refresh...'), 'success')
                return redirect(url_for('.update_profile', name=current_user.name))
            else:
                flash("You have to provide an image file to update your avatar",
                      "error")
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Update user profile
        elif request.form.get('btn') == 'Profile':
            update_form = UpdateProfileForm()
            update_form.set_locales(current_app.config['LOCALES'])
            if update_form.validate():
                current_user.id = update_form.id.data
                current_user.fullname = update_form.fullname.data
                current_user.name = update_form.name.data
                current_user.email_addr = update_form.email_addr.data
                current_user.privacy_mode = update_form.privacy_mode.data
                current_user.locale = update_form.locale.data
                db.session.commit()
                cached_users.delete_user_summary(current_user.name)
                flash(gettext('Your profile has been updated!'), 'success')
                return redirect(url_for('.update_profile', name=current_user.name))
            else:
                flash(gettext('Please correct the errors'), 'error')
                title_msg = 'Update your profile: %s' % current_user.fullname
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)

        # Update user password
        elif request.form.get('btn') == 'Password':
            # Update the data because passing it in the constructor does not work
            update_form.name.data = user.name
            update_form.fullname.data = user.fullname
            update_form.email_addr.data = user.email_addr
            update_form.ckan_api.data = user.ckan_api
            external_form = update_form
            if password_form.validate_on_submit():
                user = db.session.query(model.user.User).get(current_user.id)
                if user.check_password(password_form.current_password.data):
                    user.set_password(password_form.new_password.data)
                    db.session.add(user)
                    db.session.commit()
                    flash(gettext('Yay, you changed your password succesfully!'),
                          'success')
                    return redirect(url_for('.update_profile', name=name))
                else:
                    msg = gettext("Your current password doesn't match the "
                                  "one in our records")
                    flash(msg, 'error')
                    return render_template('/account/update.html',
                                           form=update_form,
                                           upload_form=avatar_form,
                                           password_form=password_form,
                                           external_form=external_form,
                                           title=title_msg,
                                           show_passwd_form=show_passwd_form)
            else:
                flash(gettext('Please correct the errors'), 'error')
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Update user external services
        elif request.form.get('btn') == 'External':
            del external_form.locale
            del external_form.email_addr
            del external_form.fullname
            del external_form.name
            if external_form.validate():
                current_user.ckan_api = external_form.ckan_api.data or None
                db.session.commit()
                cached_users.delete_user_summary(current_user.name)
                flash(gettext('Your profile has been updated!'), 'success')
                return redirect(url_for('.update_profile', name=current_user.name))
            else:
                flash(gettext('Please correct the errors'), 'error')
                title_msg = 'Update your profile: %s' % current_user.fullname
                return render_template('/account/update.html',
                                       form=update_form,
                                       upload_form=avatar_form,
                                       password_form=password_form,
                                       external_form=external_form,
                                       title=title_msg,
                                       show_passwd_form=show_passwd_form)
        # Otherwise return 415
        else:
            return abort(415)