Python flask.ext.login.current_user.id() Examples

The following are 29 code examples of flask.ext.login.current_user.id(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.ext.login.current_user , or try the search function .
Example #1
Source File: remedyblueprint.py    From radremedy with Mozilla Public License 2.0 6 votes vote down vote up
def news_item(news_id):
    """
    Displays a single news post.

    Args:
        news_id: The ID of the news post to show.

    Returns:
        A templated resource information page (via news-item.html).
        This template is provided with the following variables:
            news: The news post to display.
    """
    news_post = db.session.query(News). \
        filter(News.id == news_id). \
        filter(News.visible == True). \
        first()

    if news_post is None:
        abort(404)

    return render_template('news-item.html', news=news_post) 
Example #2
Source File: remedyblueprint.py    From radremedy with Mozilla Public License 2.0 6 votes vote down vote up
def resource_with_id(id):
    """
    Returns a resource from the database or aborts with a
    404 Not Found if it was not found.

    Args:
        id: The ID of the resource to retrieve.

    Returns:
        The specified resource.
    """
    result = rad.resourceservice.search(
        limit=1,
        search_params={
            'id': id,
            'visible': True,
            'is_approved': True
        })

    if result:
        return result[0]
    else:
        abort(404) 
Example #3
Source File: views.py    From BackManager with Apache License 2.0 6 votes vote down vote up
def upuser(userid):
    if current_user.id == userid or current_user.role == '0':
        form = UserEditForm()
        if form.validate_on_submit():
            user = users.query.filter_by(id=userid).first()
            if user is not None and user.verify_password(form.oldpassword.data):
                user.password = form.password.data
                db.session.add(user)
                db.session.commit()
                flash(u'密码更改成功!')
                return render_template('useredit.html',form=form)

        user = users.query.filter_by(id=userid).first()
        form.username.data = user.username
        form.name.data = user.name
        return render_template('useredit.html',form=form)
    else:
        abort(403) 
Example #4
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 6 votes vote down vote up
def searchnotif():
    notification = models.Notification(user_id=current_user.id,
                                       fulltxt=True,
                                       vendor=escape(request.json['searchquery']),
                                       product='',
                                       version='')
    # Checking Integrity Before Insert  #
    if models.Notification.query.filter_by(user_id=notification.user_id,
                                           vendor=notification.vendor,
                                           fulltxt=notification.fulltxt).first() is None:
        models.db.session.add(notification)
        models.db.session.commit()
        flash('Notification Successfully Created.', 'success')
        syslog.syslog(syslog.LOG_DEBUG, "New notification created by: " + current_user.email)
        return redirect(url_for("notif.notiftab"))
    else:
        flash('Notification Already existing.', 'warning')
        syslog.syslog(syslog.LOG_ERR, "Notification Already existing: " + current_user.email)
        return redirect(url_for("notif.notiftab")) 
Example #5
Source File: views.py    From online-ratings with MIT License 6 votes vote down vote up
def verify_player(payload):
    s = get_serializer()
    try:
        user_id, aga_id = s.loads(payload)
    except BadSignature:
        current_app.logger.info('Verify called with invalid paylod')
        abort(404)

    if user_id != current_user.id:
        current_app.logger.warn("Verify called for id %s, but wrong user answered, %s" % (user_id, current_user))
        abort(404)

    aga_info = get_aga_info(aga_id)
    if aga_info is None:
        current_app.logger.warn("Could not fetch AGA info for aga_id %s" % aga_id)
        abort(404)
    name = aga_info.get('full_name', '')

    update_user_info(user_id, aga_id, name)
    msg = 'Linked account with AGA #%s' % aga_id
    current_app.logger.info(msg)
    return redirect(url_for('ratings.myaccount')) 
Example #6
Source File: views.py    From online-ratings with MIT License 5 votes vote down vote up
def listgames():
    limit = request.args.get('limit', 30)
    aga_id = request.args.get('aga_id')
    player_id = request.args.get('player_id')
    sid = request.args.get('server_id')

    players = []
    games = []

    if aga_id:
        user_ids = [tup[0] for tup in User.query.filter(User.aga_id == aga_id).with_entities(User.id).all()]
        players = Player.query.filter(Player.user_id.in_(user_ids)).all()
    elif player_id:
        players = Player.query.filter(Player.id == player_id).all()

    if players:
        for p in players:
            game_filter = ((Game.white_id==p.id) | (Game.black_id==p.id))
            if sid:
                game_filter = game_filter & (Game.server_id==sid)
            games.extend(Game.query.filter(game_filter).all())
    else:
        query = Game.query.order_by(Game.date_reported.desc()).limit(limit)
        if sid:
            query = query.filter(Game.server_id == sid)
        games = query.all()

    return render_template('latestgames.html', user=current_user, games=games) 
Example #7
Source File: helpers.py    From mma-dexter with Apache License 2.0 5 votes vote down vote up
def body_tag_args():
    from flask.ext.login import current_user

    classes = []
    args = {}

    if current_user.is_authenticated():
        classes.append('loggedin')
        args['dataUserName'] = current_user.full_name()
        args['dataUserEmail'] = current_user.email
        args['dataUserId'] = current_user.id

    args['class_'] = ' '.join(classes)
    return args 
Example #8
Source File: forms.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def validate_email(self, field):
        """
        Validates that the provided email is unique.
        """
        existing_user = User.query. \
            filter(User.email == field.data). \
            filter(User.id != current_user.id). \
            first()

        if existing_user:
            raise ValidationError(
                'A user already exists in the database with that email.') 
Example #9
Source File: forms.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, formdata, obj, grouped_population_choices):
        super(UserSettingsForm, self).__init__(formdata=formdata, obj=obj)

        # Pass in our grouped populations verbatim
        self.populations.choices = grouped_population_choices

        # Set the default and force a re-analysis of populations *without* the
        # underlying object (i.e. only with form data), because WTForms
        # doesn't know how to translate the populations collection into
        # appropriate defaults from the obj instance.
        self.populations.default = [p.id for p in obj.populations]
        self.populations.process(formdata) 
Example #10
Source File: forms.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(
            self,
            formdata,
            obj,
            grouped_category_choices,
            grouped_population_choices):
        super(UserSubmitProviderForm, self).__init__(
            formdata=formdata,
            obj=obj)

        # Customize the text label of review_comments to suit
        self.review_comments.label.text = 'Review Comments'

        # Pass in our grouped categories/populations verbatim
        self.categories.choices = grouped_category_choices
        self.populations.choices = grouped_population_choices

        # If we have an object, set the default and force a re-analysis
        # *without* the underlying object (i.e. only with form data),
        # because WTForms doesn't know how to translate the collections into
        # appropriate defaults from the obj instance.
        if obj is not None:
            self.categories.default = [c.id for c in obj.categories]
            self.populations.default = [p.id for p in obj.populations]

        self.categories.process(formdata)
        self.populations.process(formdata) 
Example #11
Source File: remedyblueprint.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def delete_review(review_id):
    """
    Handles the deletion of new reviews.

    Args:
        review_id: The ID of the review to delete.

    Returns:
        When accessed via GET, a form to confirm deletion
            (via find-provider.html).
        This template is provided with the following variables:
            review: The review being deleted.
        When accessed via POST, a redirection action to the
        associated resource after the review has been deleted.
    """
    review = Review.query.filter(Review.id == review_id).first()

    # Make sure we got one
    if review is None:
        abort(404)

    # Make sure we're an admin or the person who actually submitted it
    if not current_user.admin and current_user.id != review.user_id:
        flash('You do not have permission to delete this review.', 'error')
        return resource_redirect(review.resource_id)

    if request.method == 'GET':
        # Return the view for deleting reviews
        return render_template(
            'delete-review.html',
            review=review)
    else:
        rad.reviewservice.delete(db.session, review)
        flash('Review deleted.', 'success')
        return resource_redirect(review.resource_id) 
Example #12
Source File: remedyblueprint.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def resource_redirect(id):
    """
    Returns a redirection action to the specified resource.

    Args:
        id: The ID of the resource to redirect to.

    Returns:
        The redirection action.
    """
    return redirect(url_for('remedy.resource', resource_id=id)) 
Example #13
Source File: remedyblueprint.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def get_sorted_options(optionlist):
    """
    Gets sorted options (ID/name tuples) from the provided list,
    sorting by name.

    Args:
        optionlist: The options to sort and convert. Assumes
            the existence of "id" and "name" properties.

    Returns:
        A sorted list of ID/name tuples from the provided option list.
    """
    return [(o.id, o.name) for o in sorted(optionlist, key=attrgetter('name'))] 
Example #14
Source File: views.py    From online-ratings with MIT License 5 votes vote down vote up
def aga_id_already_used(user, aga_id):
    exists = User.query.filter(and_(User.id!=user.id, User.aga_id==str(aga_id), User.fake==False)).count() > 0
    return exists 
Example #15
Source File: views.py    From online-ratings with MIT License 5 votes vote down vote up
def create_game_server():
    form = AddGameServerForm()
    gs = GoServer()
    if form.validate_on_submit():
        gs.name = form.gs_name.data
        gs.url = form.gs_url.data
        gs.token = generate_token()
        db.session.add(gs)
        db.session.commit()
        return server(gs.id)
    return render_template('gameserver.html', form=form, gs=gs) 
Example #16
Source File: views.py    From online-ratings with MIT License 5 votes vote down vote up
def create_player():
    form = AddPlayerForm()
    form.server.choices = [(server.id, server.name) for server in GoServer.query.all()]
    if form.validate_on_submit():
        server_id = form.server.data
        name = form.name.data
        db.session.add(Player(name=name, server_id=server_id, user_id=current_user.id, token=generate_token()))
        db.session.commit()

    return redirect(url_for('ratings.myaccount')) 
Example #17
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def transcribe(id = None, model = None):
    if id is not None:
        recording = recordings_model.get_recording(id)
        backlink = request.args.get('next') or url_for('transcribe', model = recording.model)

    if model is not None:
        recording = recordings_model.get_random_recording(model)
        backlink = url_for('transcribe', model = model)

    return render_template('transcribe.html', recording=recording, backlink=backlink) 
Example #18
Source File: views.py    From online-ratings with MIT License 5 votes vote down vote up
def myaccount():
    form = AddPlayerForm()
    form.server.choices = [(server.id, server.name) for server in GoServer.query.all()]
    players = Player.query.filter(Player.user_id == current_user.id).order_by(Player.name.asc()).all()
    # shows all games so far. Needs to be replaced with a join query that
    # orders by date played and limits to latest 10 games.
    games = itertools.chain(*(
        Game.query.filter(or_(Game.white_id == player.id, Game.black_id == player.id))
        for player in players))
    return render_template('myaccount.html', user=current_user, games=games, players=players, form=form) 
Example #19
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 5 votes vote down vote up
def delnotif():
    row = models.Notification.query.filter_by(id=request.json).first()
    models.db.session.delete(row)
    models.db.session.commit()
    flash('Notification removed ', 'info')
    syslog.syslog(syslog.LOG_DEBUG, "Notification deleted: " + current_user.email)
    return redirect(url_for("notif.notiftab")) 
Example #20
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 5 votes vote down vote up
def addnotif():
    if request.json['allversion'] is True and request.json['allproduct'] is False:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product=escape(request.json['queryproduct'].lower()),
                                           version='')

    elif request.json['allproduct'] is True:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product='',
                                           version='')
    else:
        notification = models.Notification(user_id=current_user.id,
                                           vendor=escape(request.json['queryvendor'].lower()),
                                           product=escape(request.json['queryproduct'].lower()),
                                           version=escape(request.json['queryversion'].lower()))

    # Checking Integrity Before Insert  #
    if models.Notification.query.filter_by(user_id=notification.user_id,
                                           vendor=notification.vendor,
                                           product=notification.product,
                                           version=notification.version).first() is None:
        models.db.session.add(notification)
        models.db.session.commit()
        flash('Notification Successfully Created.', 'success')
        syslog.syslog(syslog.LOG_DEBUG, "New notification created by: " + current_user.email)
        return redirect(url_for("notif.notiftab"))

    else:
        flash('Notification Already existing.', 'warning')
        syslog.syslog(syslog.LOG_ERR, "Notification Already existing: " + current_user.email)
        return redirect(url_for("notif.notiftab")) 
Example #21
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 5 votes vote down vote up
def notiftab():
    jnotif = []
    dic = {}

    limit = request.args.get('limit')
    offset = request.args.get('offset')
    sort = request.args.get('sort')
    order = request.args.get('order')

    if order == 'desc':
        notif_list = models.Notification.query.filter_by(user_id=current_user.id).order_by(desc(sort)).limit(
            limit).offset(offset).all()
    else:
        notif_list = models.Notification.query.filter_by(user_id=current_user.id).order_by(sort).limit(limit).offset(
            offset).all()

    num = models.Notification.query.filter_by(user_id=current_user.id).count()

    for notif in notif_list:
        dnotif = {'id': notif.id,
                  'fulltxt': notif.fulltxt,
                  'vendor': notif.vendor,
                  'product': notif.product,
                  'version': notif.version
                  }
        jnotif.append(dnotif)

    dic['total'] = num
    dic['rows'] = jnotif
    return jsonify(dic) 
Example #22
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def on_identity_loaded(sender, identity):
    identity.user = current_user

    if hasattr(current_user, 'id'):
        identity.provides.add(UserNeed(current_user.id))

    if hasattr(current_user, 'admin') and current_user.admin:
        identity.provides.add(RoleNeed('admin')) 
Example #23
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def load_user(id):
    return users_model.get_user(id) 
Example #24
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def login_google(token, userinfo, **params):
    login_user(users_model.upsert_user(userinfo))

    identity = Identity(userinfo['id'])
    identity_changed.send(app, identity = identity)

    return redirect(url_for('index')) 
Example #25
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def save_worker_description():
    if request.form.get('run_on_marathon', False):
        url = os.environ.get("MARATHON_URL", None)
        login = os.environ.get("MARATHON_LOGIN", None)
        password = os.environ.get("MARATHON_PASSWORD", None)
        config = {
            "id": request.form["id"],
            "model_url": request.form["model_url"],
            "cpu": request.form["cpu"],
            "mem": request.form["mem"],
            "master_addr": os.environ.get("MASTER_ADDR", None),
            "recordings_saver_addr": os.environ.get("RECORDINGS_SAVER_ADDR", None)
        }

        if not run_worker_on_marathon(url, login, password, config):
            flash('Worker wasn\'t started successfully')
            return redirect(url_for('kaldi_worker'))

    flash('Worker\'s description was successfully saved')
    worker_types_model.edit_worker(
        request.form['id'],
        request.form['name'],
        request.form['description'],
        request.form.getlist("lm-id[]"),
        request.form.getlist("lm-name[]")
    )

    return redirect(url_for('worker_types')) 
Example #26
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def kaldi_worker():
    return render_template('kaldi_worker.html', worker = {"id": None}) 
Example #27
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def accept_transcription(recording, transcription):
    recordings_model.set_transcription(recording, transcription)
    return redirect(url_for('transcriptions', id = recording)) 
Example #28
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def transcriptions(id):
    return render_template('transcriptions.html', recording=recordings_model.get_recording(id)) 
Example #29
Source File: run.py    From cloud-asr with Apache License 2.0 5 votes vote down vote up
def save_transcription():
    flash('Recording was successfully transcribed')

    recordings_model.add_transcription(
        current_user.get_id(),
        request.form['id'],
        request.form['transcription'],
        'native_speaker' in request.form,
        'offensive_language' in request.form,
        'not_a_speech' in request.form
    )

    return redirect(request.form['backlink'])