flask_login.current_user.is_anonymous

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

68 Examples 7

Page 1 Selected Page 2

Example 1

Project: histsync Source File: app.py
Function: edit_command
@app.route('/_edit_command/<int:id>', methods=["POST"])
def _edit_command(id):
    c = Command.query.get_or_404(id)
    if current_user.is_anonymous() or current_user != c.user:
        abort(403)
    c.text = request.form['command']
    c.description = request.form['description']
    db.session.commit()
    return jsonify(result="OK")

Example 2

Project: flask-oauth-example Source File: app.py
@app.route('/authorize/<provider>')
def oauth_authorize(provider):
    if not current_user.is_anonymous:
        return redirect(url_for('index'))
    oauth = OAuthSignIn.get_provider(provider)
    return oauth.authorize()

Example 3

Project: viaduct Source File: user.py
    @staticmethod
    def get_membership_warning():
        """Render a warning if the current user has not payed."""
        if current_user.is_anonymous or\
                (current_user.is_authenticated and
                    (current_user.has_payed or current_user.alumnus)):
            return ''

        return render_template('user/membership_warning.htm')

Example 4

Project: pittsburgh-purchasing-suite Source File: decorators.py
Function: requires_roles
def requires_roles(*roles):
    '''
    Takes in a list of roles and checks whether the user
    has access to those role
    '''
    def check_roles(view_function):
        @wraps(view_function)
        def decorated_function(*args, **kwargs):

            if current_user.is_anonymous():
                flash('This feature is for city staff only. If you are staff, log in with your pittsburghpa.gov email using the link to the upper right.', 'alert-warning')
                return redirect(request.args.get('next') or '/')
            elif current_user.role.name not in roles:
                flash('You do not have sufficent permissions to do that!', 'alert-danger')
                return redirect(request.args.get('next') or '/')
            return view_function(*args, **kwargs)
        return decorated_function
    return check_roles

Example 5

Project: realms-wiki Source File: views.py
@blueprint.route('/_search')
def search():
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    results = search_engine.wiki(request.args.get('q'))
    return render_template('search/search.html', results=results)

Example 6

Project: histsync Source File: app.py
@app.route('/_publish_command/<int:id>', methods=["POST"])
def _publish_command(id):
    c = Command.query.get_or_404(id)
    if current_user.is_anonymous() or current_user != c.user:
        abort(403)
    c.is_public = True
    c.text = request.form['command']
    c.description = request.form['description']
    c.time_shared = datetime.utcnow()
    db.session.commit()

    return jsonify(result="OK")

Example 7

Project: braindump Source File: views.py
@auth.route('/reset/<token>', methods=['GET', 'POST'])
def password_reset(token):
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(
            email=form.email.data.lower().strip()).first()
        if user is None:
            return redirect(url_for('main.index'))
        if user.reset_password(token, form.password.data):
            flash('Your password has been updated.')
            return redirect(url_for('auth.login'))
        else:
            return redirect(url_for('main.index'))
    return render_template('auth/reset_password.html', form=form)

Example 8

Project: realms-wiki Source File: views.py
@blueprint.route("/", defaults={'name': 'home'})
@blueprint.route("/<path:name>")
def page(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)
    if cname != name:
        return redirect(url_for('wiki.page', name=cname))

    data = g.current_wiki.get_page(cname)

    if data:
        return render_template('wiki/page.html', name=cname, page=data, partials=_partials(data.imports))
    else:
        return redirect(url_for('wiki.create', name=cname))

Example 9

Project: flask-oauth-example Source File: app.py
@app.route('/callback/<provider>')
def oauth_callback(provider):
    if not current_user.is_anonymous:
        return redirect(url_for('index'))
    oauth = OAuthSignIn.get_provider(provider)
    social_id, username, email = oauth.callback()
    if social_id is None:
        flash('Authentication failed.')
        return redirect(url_for('index'))
    user = User.query.filter_by(social_id=social_id).first()
    if not user:
        user = User(social_id=social_id, nickname=username, email=email)
        db.session.add(user)
        db.session.commit()
    login_user(user, True)
    return redirect(url_for('index'))

Example 10

Project: viaduct Source File: athenaeum.py
@blueprint.route('/', methods=['GET'])
def embed():
    if current_user.is_anonymous:
        flash(_('Using the bookstore requires an account.'), 'warning')
        return abort(403)

    """Embed the athenaeum website."""
    url = 'https://www.athenaeum.nl/studieboeken/studieverenigingen/#A-12;10'

    return render_template('athenaeum/embed.htm', url=url)

Example 11

Project: viaduct Source File: user.py
@blueprint.route('/users/remove_avatar/<int:user_id>', methods=['GET'])
@login_required
def remove_avatar(user_id=None):
    user = User.query.get(user_id)
    if not ModuleAPI.can_write('user') and\
            (current_user.is_anonymous or current_user.id != user_id):
        return abort(403)
    UserAPI.remove_avatar(user)
    return redirect(url_for('user.view_single', user_id=user_id))

Example 12

Project: viaduct Source File: custom_form.py
@blueprint.route('/unarchive/<int:form_id>/', methods=['GET', 'POST'])
@blueprint.route('/unarchive/<int:form_id>/<int:page_nr>/',
                 methods=['GET', 'POST'])
def unarchive(form_id, page_nr=1):
    if not ModuleAPI.can_write('custom_form') or current_user.is_anonymous:
        return abort(403)

    form = CustomForm.query.get(form_id)
    if not form:
        return abort(404)

    form.archived = False
    db.session.commit()

    flash('Formulier gede-archiveerd', 'success')

    return redirect(url_for('custom_form.view', page_nr=page_nr))

Example 13

Project: realms-wiki Source File: views.py
@blueprint.route("/_index", defaults={"path": ""})
@blueprint.route("/_index/<path:path>")
def index(path):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    items = g.current_wiki.get_index()
    if path:
        path = to_canonical(path) + "/"
        items = filter(lambda x: x['name'].startswith(path), items)
    if not request.args.get('flat', '').lower() in ['yes', '1', 'true']:
        items = _tree_index(items, path=path)

    return render_template('wiki/index.html', index=items, path=path)

Example 14

Project: histsync Source File: app.py
Function: delete_command
@app.route('/_delete_command/<int:id>', methods=["POST"])
def delete_command(id):
    c = Command.query.get_or_404(id)
    if current_user.is_anonymous() or current_user != c.user:
        abort(403)

    db.session.delete(c)
    db.session.commit()
    return jsonify(result="OK")

Example 15

Project: histsync Source File: app.py
@app.route('/_unpublish_command/<int:id>', methods=["POST"])
def _unpublish_command(id):
    c = Command.query.get_or_404(id)
    if current_user.is_anonymous() or current_user != c.user:
        abort(403)
    c.is_public = False
    db.session.commit()

    return jsonify(result="OK")

Example 16

Project: heroku-airflow Source File: airflow_login.py
def login(self, request):
    if not current_user.is_anonymous:
        return None
    app = current_app._get_current_object()
    criteria = [
        request.is_secure,
        app.debug == False,
        request.headers.get('X-Forwarded-Proto', 'http') == 'https'
    ]
    scheme = 'http'
    if any(criteria):
        scheme = 'https'
    oauth = OAuthSignIn.get_provider('google')
    return oauth.authorize(scheme)

Example 17

Project: braindump Source File: views.py
@auth.route('/reset', methods=['GET', 'POST'])
def password_reset_request():
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(
            email=form.email.data.lower().strip()).first()
        if user:
            token = user.generate_reset_token()
            send_email(user.email, 'Reset Your Password',
                       'auth/email/reset_password',
                       user=user, token=token,
                       next=request.args.get('next'))
        flash('An email with instructions to reset your password has been '
              'sent to you.')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html', form=form)

Example 18

Project: flask-login Source File: test_login.py
    def test_static_loads_anonymous(self):
        app = Flask(__name__)
        app.static_url_path = '/static'
        app.secret_key = 'this is a temp key'
        lm = LoginManager()
        lm.init_app(app)

        with app.test_client() as c:
            c.get('/static/favicon.ico')
            self.assertTrue(current_user.is_anonymous)

Example 19

Project: pittsburgh-purchasing-suite Source File: decorators.py
Function: is_accessible
    def is_accessible(self):
        if current_user.is_anonymous():
            return False
        if current_user.role.name in self.accepted_roles:
            return True
        return False

Example 20

Project: flasky Source File: views.py
Function: password_reset_request
@auth.route('/reset', methods=['GET', 'POST'])
def password_reset_request():
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_reset_token()
            send_email(user.email, 'Reset Your Password',
                       'auth/email/reset_password',
                       user=user, token=token,
                       next=request.args.get('next'))
        flash('An email with instructions to reset your password has been '
              'sent to you.')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html', form=form)

Example 21

Project: realms-wiki Source File: views.py
@blueprint.route("/_commit/<sha>/<path:name>")
def commit(name, sha):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    cname = to_canonical(name)

    data = g.current_wiki.get_page(cname, sha=sha)

    if not data:
        abort(404)

    partials = _partials(data.imports, sha=sha)

    return render_template('wiki/page.html', name=name, page=data, commit=sha, partials=partials)

Example 22

Project: flasky Source File: views.py
Function: password_reset
@auth.route('/reset/<token>', methods=['GET', 'POST'])
def password_reset(token):
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is None:
            return redirect(url_for('main.index'))
        if user.reset_password(token, form.password.data):
            flash('Your password has been updated.')
            return redirect(url_for('auth.login'))
        else:
            return redirect(url_for('main.index'))
    return render_template('auth/reset_password.html', form=form)

Example 23

Project: acousticbrainz-server Source File: __init__.py
Function: login_forbidden
def login_forbidden(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if current_user.is_anonymous is False:
            return redirect(url_for('index.index'))
        return f(*args, **kwargs)

    return decorated

Example 24

Project: viaduct Source File: custom_form.py
@blueprint.route('/archive/<int:form_id>/', methods=['GET', 'POST'])
@blueprint.route('/archive/<int:form_id>/<int:page_nr>/',
                 methods=['GET', 'POST'])
def archive(form_id, page_nr=1):
    if not ModuleAPI.can_write('custom_form') or current_user.is_anonymous:
        return abort(403)

    form = CustomForm.query.get(form_id)
    if not form:
        return abort(404)

    form.archived = True
    db.session.commit()

    flash('Formulier gearchiveerd', 'success')

    return redirect(url_for('custom_form.view', page_nr=page_nr))

Example 25

Project: viaduct Source File: module.py
Function: can_read
    @staticmethod
    def can_read(module_name, needs_payed=False):
        """
        Check if the current user can view the module_name.

        Distinguishes between payed members and regular users
        """
        if needs_payed and\
                (current_user.is_anonymous or not current_user.has_payed):
            return False
        return ModuleAPI\
            .get_highest_permission_for_module(module_name) >= 1

Example 26

Project: viaduct Source File: lang.py
@blueprint.route('/set/<path:lang>', methods=['GET'])
def set_user_lang(lang=None):
    if lang not in app.config['LANGUAGES'].keys():
        flash(_('Language unsupported on this site') + ': ' + lang, 'warning')
        return redirect(url_for('home.home'))
    if current_user.is_anonymous:
        flash(_('You need to be logged in to set a permanent language.'))
        return redirect(redirect_url())

    current_user.locale = lang
    db.session.add(current_user)
    db.session.commit()
    refresh()
    return redirect(redirect_url())

Example 27

Project: viaduct Source File: elections.py
@blueprint.route('/nomineren/remove/', methods=['POST'])
def remove_nomination():
    if not can_nominate():
        return jsonify(error='Het nomineren is gesloten')

    if current_user.is_anonymous or not current_user.has_payed:
        return jsonify(error='Je hebt hier helemaal niks te zoeken'), 403

    nomination = Nomination.query.get(request.form.get('id'))

    if nomination.user_id != current_user.id:
        return jsonify(error='Haha, NOPE! Pff, sukkel.'), 403

    db.session.delete(nomination)
    db.session.commit()

    return jsonify()

Example 28

Project: viaduct Source File: page.py
    @staticmethod
    def can_read(page):
        if page.needs_payed and (current_user.is_anonymous or
                                 not current_user.has_payed):
            return False

        return PagePermission.get_user_rights(current_user, page.id) > 0

Example 29

Project: burp-ui Source File: i18n.py
@babel.localeselector
def get_locale():
    locale = None
    if current_user and not current_user.is_anonymous:
        locale = getattr(current_user, 'language', None)
    return locale or request.accept_languages.best_match(config['LANGUAGES'].keys())

Example 30

Project: incubator-airflow Source File: utils.py
Function: is_accessible
    def is_accessible(self):
        return (
            not AUTHENTICATE or (
                not current_user.is_anonymous() and
                current_user.is_authenticated()
            )
        )

Example 31

Project: flaskbb Source File: views.py
@auth.route('/reset-password', methods=["GET", "POST"])
def forgot_password():
    """Sends a reset password token to the user."""
    if not current_user.is_anonymous:
        return redirect(url_for("forum.index"))

    form = ForgotPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()

        if user:
            send_reset_token.delay(user)
            flash(_("Email sent! Please check your inbox."), "info")
            return redirect(url_for("auth.forgot_password"))
        else:
            flash(_("You have entered an username or email address that is "
                    "not linked with your account."), "danger")
    return render_template("auth/forgot_password.html", form=form)

Example 32

Project: realms-wiki Source File: views.py
Function: compare
@blueprint.route(r"/_compare/<path:name>/<regex('\w+'):fsha><regex('\.{2,3}'):dots><regex('\w+'):lsha>")
def compare(name, fsha, dots, lsha):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()

    diff = g.current_wiki.get_page(name, sha=lsha).compare(fsha)
    return render_template('wiki/compare.html',
                           name=name, diff=diff, old=fsha, new=lsha)

Example 33

Project: viaduct Source File: module.py
Function: can_write
    @staticmethod
    def can_write(module_name, needs_payed=False):
        """Check if the current user can edit the module_name."""
        if needs_payed and\
                (current_user.is_anonymous or not current_user.has_payed):
            return False
        return ModuleAPI\
            .get_highest_permission_for_module(module_name) >= 2

Example 34

Project: viaduct Source File: elections.py
@blueprint.route('/stemmen/', methods=['GET'])
def vote():
    if not can_vote():
        return redirect(url_for('elections.main'))

    if current_user.is_anonymous or not current_user.has_payed:
        return abort(403)

    nominees = Nominee.query.filter(Nominee.valid == True)\
        .order_by(Nominee.name).all()  # noqa
    nominee_bound = int(ceil(len(nominees) / 2))

    vote = current_user.vote[0] if current_user.vote else Vote()

    return render_template('elections/vote.htm',
                           title='Docent van het jaar IW/Stemmen',
                           nominees=nominees,
                           nominee_bound=nominee_bound,
                           vote=vote)

Example 35

Project: viaduct Source File: pimpy.py
    @staticmethod
    def get_navigation_menu(group_id, personal, type):
        if not ModuleAPI.can_read('pimpy'):
            return abort(403)
        if current_user.is_anonymous:
            flash('Huidige gebruiker niet gevonden!', 'danger')
            return redirect(url_for('pimpy.view_minutes'))

        groups = current_user.groups\
            .filter(Group.name != 'all').order_by(Group.name.asc()).all()

        if not type:
            type = 'minutes'
        endpoint = 'pimpy.view_' + type
        endpoints = {'view_chosentype': endpoint,
                     'view_chosentype_personal': endpoint + '_personal',
                     'view_chosentype_chosenpersonal': endpoint +
                     ('_personal' if personal and type != 'minutes' else ''),
                     'view_tasks': 'pimpy.view_tasks',
                     'view_tasks_personal': 'pimpy.view_tasks_personal',
                     'view_tasks_chosenpersonal': 'pimpy.view_tasks',
                     'view_minutes': 'pimpy.view_minutes'}
        if personal:
            endpoints['view_tasks_chosenpersonal'] += '_personal'

        if not group_id:
            group_id = 'all'
        if group_id != 'all':
            group_id = int(group_id)

        return Markup(render_template('pimpy/api/side_menu.htm', groups=groups,
                                      group_id=group_id, personal=personal,
                                      type=type, endpoints=endpoints,
                                      title='PimPy'))

Example 36

Project: viaduct Source File: pimpy.py
    @staticmethod
    def get_all_tasks(group_id):
        """
        Show all tasks ever made.

        Can specify specific group.
        No internal permission system made yet.
        Do not make routes to this module yet.
        """
        if not ModuleAPI.can_read('pimpy'):
            return abort(403)
        if current_user.is_anonymous:
            flash('Huidige gebruiker niet gevonden.', 'danger')
            return redirect(url_for('pimpy.view_tasks'))

        status_meanings = Task.get_status_meanings()

        list_items = {}
        if group_id == 'all':
            for group in UserAPI.get_groups_for_current_user():
                list_users = {}
                list_users['Iedereen'] = group.tasks
                list_items[group.name] = list_users
        else:
            list_users = {}
            tasks = Task.query.filter(Task.group_id == group_id).all()
            group = Group.query.filter(Group.id == group_id).first()
            if not group:
                return abort(404)
            if group not in UserAPI.get_groups_for_current_user():
                return abort(403)
            list_users['Iedereen'] = tasks
            list_items[group.name] = list_users

        return Markup(render_template('pimpy/api/tasks.htm',
                                      list_items=list_items, type='tasks',
                                      group_id=group_id, personal=False,
                                      status_meanings=status_meanings,
                                      title='PimPy'))

Example 37

Project: realms-wiki Source File: views.py
@blueprint.route("/_revert", methods=['POST'])
@login_required
def revert():
    cname = to_canonical(request.form.get('name'))
    commit = request.form.get('commit')
    message = request.form.get('message', "Reverting %s" % cname)

    if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous:
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
        return dict(error=True, message="Page is locked"), 403

    try:
        sha = g.current_wiki.get_page(cname).revert(commit,
                                                    message=message,
                                                    username=current_user.username,
                                                    email=current_user.email)
    except PageNotFound as e:
        return dict(error=True, message=e.message), 404

    if sha:
        flash("Page reverted")

    return dict(sha=sha)

Example 38

Project: realms-wiki Source File: views.py
@blueprint.route("/<path:name>", methods=['POST', 'PUT', 'DELETE'])
@login_required
def page_write(name):
    cname = to_canonical(name)

    if not cname:
        return dict(error=True, message="Invalid name")

    if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous:
        return dict(error=True, message="Anonymous posting not allowed"), 403

    if request.method == 'POST':
        # Create
        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        sha = g.current_wiki.get_page(cname).write(request.form['content'],
                                                   message=request.form['message'],
                                                   username=current_user.username,
                                                   email=current_user.email)

    elif request.method == 'PUT':
        edit_cname = to_canonical(request.form['name'])

        if edit_cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        if edit_cname != cname:
            g.current_wiki.get_page(cname).rename(edit_cname)

        sha = g.current_wiki.get_page(edit_cname).write(request.form['content'],
                                                        message=request.form['message'],
                                                        username=current_user.username,
                                                        email=current_user.email)

        return dict(sha=sha)

    elif request.method == 'DELETE':
        # DELETE
        if cname in current_app.config.get('WIKI_LOCKED_PAGES'):
            return dict(error=True, message="Page is locked"), 403

        sha = g.current_wiki.get_page(cname).delete(username=current_user.username,
                                                    email=current_user.email)

    return dict(sha=sha)

Example 39

Project: viaduct Source File: pimpy.py
    @staticmethod
    def get_tasks(group_id, personal):
        if not ModuleAPI.can_read('pimpy'):
            return abort(403)
        if current_user.is_anonymous:
            flash('Huidige gebruiker niet gevonden', 'danger')
            return redirect(url_for('pimpy.view_tasks'))

        status_meanings = Task.get_status_meanings()

        tasks_rel = TaskUserRel.query.join(Task).join(User)

        groups = UserAPI.get_groups_for_current_user()
        groups = map(lambda x: x.id, groups)

        if group_id == 'all':
            tasks_rel = tasks_rel.filter(Task.group_id.in_(groups))

        else:
            group_id = int(group_id)
            if group_id not in groups:
                return abort(403)

            tasks_rel = tasks_rel.filter(Task.group_id == group_id)

        if personal:
            tasks_rel = tasks_rel.filter(User.id == current_user.id)

        tasks_rel = tasks_rel.filter(~Task.status.in_((4, 5))).join(Group)
        tasks_rel = tasks_rel.order_by(Group.name.asc(), User.first_name.asc(),
                                       User.last_name.asc(), Task.id.asc())

        return Markup(render_template('pimpy/api/tasks.htm',
                                      personal=personal,
                                      group_id=group_id,
                                      tasks_rel=tasks_rel,
                                      type='tasks',
                                      status_meanings=status_meanings,
                                      title='PimPy'))

Example 40

Project: viaduct Source File: pimpy.py
    @staticmethod
    def get_tasks_in_date_range(group_id, personal, start_date, end_date):
        """Load all tasks for a given group in a daterange."""

        if not ModuleAPI.can_read('pimpy'):
            return abort(403)
        if current_user.is_anonymous:
            flash('Huidige gebruiker niet gevonden', 'danger')
            return redirect(url_for('pimpy.view_tasks'))

        status_meanings = Task.get_status_meanings()

        tasks_rel = TaskUserRel.query.join(Task).join(User)

        groups = UserAPI.get_groups_for_current_user()
        groups = map(lambda x: x.id, groups)

        if group_id == 'all':
            tasks_rel = tasks_rel.filter(Task.group_id.in_(groups))

        else:
            group_id = int(group_id)
            if group_id not in groups:
                return abort(403)

            tasks_rel = tasks_rel.filter(Task.group_id == group_id)

        if personal:
            tasks_rel = tasks_rel.filter(User.id == current_user.id)

        tasks_rel = tasks_rel.filter(~Task.status.in_((4, 5))).join(Group).\
            filter(start_date <= Task.timestamp,
                   Task.timestamp <= end_date)
        tasks_rel = tasks_rel.order_by(Group.name.asc(), User.first_name.asc(),
                                       User.last_name.asc(), Task.id.asc())

        return Markup(render_template('pimpy/api/tasks.htm',
                                      personal=personal,
                                      group_id=group_id,
                                      tasks_rel=tasks_rel,
                                      type='tasks',
                                      status_meanings=status_meanings,
                                      title='PimPy'))

Example 41

Project: viaduct Source File: pimpy.py
    @staticmethod
    def get_minutes(group_id):
        """Load all minutes in the given group."""

        if not ModuleAPI.can_read('pimpy'):
            return abort(403)
        if current_user.is_anonymous:
            flash('Huidige gebruiker niet gevonden', 'danger')
            return redirect(url_for('pimpy.view_minutes'))

        list_items = {}

        if group_id != 'all':
            query = Minute.query.filter(Minute.group_id == group_id).\
                order_by(Minute.minute_date.desc())
            list_items[Group.query.filter(Group.id == group_id).first().name]\
                = query.all()
        # this should be done with a sql in statement, or something, but meh
        else:
            for group in current_user.groups:
                list_items[group.name] = Minute.query\
                    .filter(Minute.group_id == group.id)\
                    .order_by(Minute.minute_date.desc())\
                    .all()

        return render_template('pimpy/api/minutes.htm',
                               list_items=list_items, type='minutes',
                               group_id=group_id, line_number=-1,
                               title='PimPy')

Example 42

Project: realms-wiki Source File: views.py
Function: history
@blueprint.route("/_history/<path:name>")
def history(name):
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()
    return render_template('wiki/history.html', name=name)

Example 43

Project: viaduct Source File: pimpy.py
    @staticmethod
    def get_minutes_in_date_range(group_id, start_date, end_date):
        """Load all minutes in the given group."""

        if not ModuleAPI.can_read('pimpy'):
            return abort(403)
        if current_user.is_anonymous:
            flash('Huidige gebruiker niet gevonden', 'danger')
            return redirect(url_for('pimpy.view_minutes'))

        list_items = {}

        start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")

        if group_id != 'all':
            query = Minute.query.filter(Minute.group_id == group_id).\
                filter(start_date <= Minute.minute_date,
                       Minute.minute_date <= end_date).\
                order_by(Minute.minute_date.desc())
            list_items[Group.query.filter(Group.id == group_id).first().name]\
                = query.all()
        # this should be done with a sql in statement, or something, but meh
        else:
            for group in current_user.groups:
                query = Minute.query.filter(Minute.group_id == group.id)
                query = query.order_by(Minute.minute_date.desc())
                list_items[group.name] = query.all()

        return Markup(render_template('pimpy/api/minutes.htm',
                                      list_items=list_items, type='minutes',
                                      group_id=group_id, line_number=-1,
                                      title='PimPy'))

Example 44

Project: flaskbb Source File: views.py
Function: reset_password
@auth.route("/reset-password/<token>", methods=["GET", "POST"])
def reset_password(token):
    """Handles the reset password process."""
    if not current_user.is_anonymous:
        return redirect(url_for("forum.index"))

    form = ResetPasswordForm()
    if form.validate_on_submit():
        expired, invalid, user = get_token_status(form.token.data,
                                                  "reset_password")

        if invalid:
            flash(_("Your password token is invalid."), "danger")
            return redirect(url_for("auth.forgot_password"))

        if expired:
            flash(_("Your password token is expired."), "danger")
            return redirect(url_for("auth.forgot_password"))

        if user:
            user.password = form.password.data
            user.save()
            flash(_("Your password has been updated."), "success")
            return redirect(url_for("auth.login"))

    form.token.data = token
    return render_template("auth/reset_password.html", form=form)

Example 45

Project: viaduct Source File: challenge.py
@blueprint.route('/', methods=['GET', 'POST'])
@blueprint.route('/dashboard/', methods=['GET', 'POST'])
def view_list(page=1):
    if not ModuleAPI.can_read('challenge') or current_user.is_anonymous:
        return abort(403)

    print((app.config['SQLALCHEMY_DATABASE_URI']))

    challenge = Challenge()
    form = ChallengeForm(request.form, challenge)

    challenges = ChallengeAPI.fetch_all_challenges_user(current_user.id)
    approved_challenges = \
        ChallengeAPI.fetch_all_approved_challenges_user(current_user.id)
    user_points = ChallengeAPI.get_points(current_user.id)
    ranking = ChallengeAPI.get_ranking()

    challenge_description = ChallengeAPI.get_challenge_description()

    return render_template('challenge/dashboard.htm', challenges=challenges,
                           user_points=user_points, ranking=ranking,
                           approved_challenges=approved_challenges, form=form,
                           challenge_description=challenge_description)

Example 46

Project: viaduct Source File: challenge.py
@blueprint.route('/api/new_submission', methods=['GET', 'POST'])
def new_submission(challenge_id=None):
    if not ModuleAPI.can_read('challenge') or current_user.is_anonymous:
        abort(403)

    if request.args.get('challenge_id'):
        challenge_id = request.args.get('challenge_id')
    else:
        return "Error, no 'challenge_id' given"

    if request.args.get('submission'):
        submission = request.args.get('submission')
    else:
        return "Error, no 'submission' given"

    new_submission = ChallengeAPI.create_submission(challenge_id=challenge_id,
                                                    user_id=current_user.id,
                                                    submission=submission,
                                                    image_path=None)

    if new_submission is False:
        return "Question is already submitted"

    challenge = ChallengeAPI.fetch_challenge(challenge_id)

    return ChallengeAPI.validate_question(new_submission, challenge)

Example 47

Project: realms-wiki Source File: views.py
@blueprint.route("/_history_data/<path:name>")
def history_data(name):
    """Ajax provider for paginated history data."""
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()
    draw = int(request.args.get('draw', 0))
    start = int(request.args.get('start', 0))
    length = int(request.args.get('length', 10))
    page = g.current_wiki.get_page(name)
    items = list(itertools.islice(page.history, start, start + length))
    for item in items:
        item['gravatar'] = gravatar_url(item['author_email'])
        item['DT_RowId'] = item['sha']
        date = datetime.fromtimestamp(item['time'])
        item['date'] = date.strftime(current_app.config.get('DATETIME_FORMAT', '%b %d, %Y %I:%M %p'))
        item['link'] = url_for('.commit', name=name, sha=item['sha'])
    total_records, hist_complete = page.history_cache
    if not hist_complete:
        # Force datatables to fetch more data when it gets to the end
        total_records += 1
    return {
        'draw': draw,
        'recordsTotal': total_records,
        'recordsFiltered': total_records,
        'data': items,
        'fully_loaded': hist_complete
    }

Example 48

Project: webhookdb Source File: __init__.py
@ui.route("/")
def index():
    """
    Home page.

    If the user is not currently logged in with Github, explain what WebhookDB
    is, and ask them to log in.

    If the user *is* logged in with Github, show them their Github repos,
    and allow them to re-sync repos from Github.
    """
    if current_user.is_anonymous():
        return render_template("home-anonymous.html")
    else:
        replication_url = url_for(
            "replication.pull_request",
            _external=True,
        )
        is_self_hook = (RepositoryHook.url == replication_url)
        repos = (
            db.session.query(Repository, func.sum(cast(is_self_hook, db.Integer)))
            .outerjoin(RepositoryHook, RepositoryHook.repo_id == Repository.id)
            .join(UserRepoAssociation, UserRepoAssociation.repo_id == Repository.id)
            .filter(UserRepoAssociation.user_id == current_user.id)
            .filter(UserRepoAssociation.can_admin == True)
            .group_by(Repository)
            .order_by(
                (Repository.owner_id == current_user.id).desc(),
                func.lower(Repository.owner_login),
                func.lower(Repository.name),
            )
        )
        return render_template("home.html", repos=repos)

Example 49

Project: viaduct Source File: custom_form.py
@blueprint.route('/create/', methods=['GET', 'POST'])
@blueprint.route('/edit/<int:form_id>', methods=['GET', 'POST'])
def create(form_id=None):
    if not ModuleAPI.can_write('custom_form') or current_user.is_anonymous:
        return abort(403)

    if form_id:
        custom_form = CustomForm.query.get_or_404(form_id)
        prev_max = custom_form.max_attendants
        if not custom_form:
            abort(404)
    else:
        custom_form = CustomForm()

    form = CreateForm(request.form, custom_form)

    if request.method == 'POST':
        custom_form.name = form.name.data
        custom_form.origin = form.origin.data
        custom_form.html = form.html.data
        custom_form.msg_success = form.msg_success.data
        custom_form.max_attendants = form.max_attendants.data
        if form.price.data is None:
            form.price.data = 0.0
        custom_form.price = form.price.data
        custom_form.transaction_description = form.transaction_description.data
        custom_form.terms = form.terms.data

        follower = None

        if not form_id:
            follower = CustomFormFollower(owner_id=current_user.id)
            flash('You\'ve created a form successfully.', 'success')

        else:
            flash('You\'ve updated a form successfully.', 'success')
            cur_max = int(custom_form.max_attendants)
            # print("Current maximum: " + cur_max)
            # print("Previous maximum: " + prev_max)
            # print("Current submissions: " + len(all_sub))
            if cur_max > prev_max:
                all_sub = CustomFormResult.query.filter(
                    CustomFormResult.form_id == form_id
                ).all()
                # Update for users that were on the reserve list that they
                # can now attend.
                if prev_max < len(all_sub):
                    for x in range(prev_max, max(cur_max, len(all_sub) - 1)):
                        sub = all_sub[x]
                        copernica_data = {
                            "Reserve": "Nee"
                        }
                        copernica.update_subprofile(
                            copernica.SUBPROFILE_ACTIVITY, sub.owner_id,
                            sub.form_id, copernica_data)
            elif cur_max < prev_max:
                all_sub = CustomFormResult.query.filter(
                    CustomFormResult.form_id == form_id
                ).all()
                if cur_max < len(all_sub):
                    for x in range(cur_max, max(prev_max, len(all_sub) - 1)):
                        sub = all_sub[x]
                        copernica_data = {
                            "Reserve": "Ja"
                        }
                        copernica.update_subprofile(
                            copernica.SUBPROFILE_ACTIVITY, sub.owner_id,
                            sub.form_id, copernica_data)

        db.session.add(custom_form)
        db.session.commit()

        if follower is not None:
            follower.form_id = custom_form.id
            db.session.add(follower)
            db.session.commit()

        return redirect(url_for('custom_form.view'))
    else:
        flash_form_errors(form)

    return render_template('custom_form/create.htm', form=form)

Example 50

Project: realms-wiki Source File: views.py
Function: partials
@blueprint.route("/_partials")
def partials():
    if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous:
        return current_app.login_manager.unauthorized()
    return {'partials': _partials(request.args.getlist('imports[]'))}
See More Examples - Go to Next Page
Page 1 Selected Page 2