Python flask_login.current_user.get_id() Examples

The following are 30 code examples of flask_login.current_user.get_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_login.current_user , or try the search function .
Example #1
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def favourite_shlokas():
    badge_list = []
    current_app.logger.info("RadhaKrishna")
    verses = None
    if current_user.is_authenticated:
        verses = UserFavourite.query.filter_by(
            user_id=current_user.get_id()).order_by(
                UserFavourite.user_favourite_id.desc()).all()

    return render_template(
        'main/favourite.html', verses=verses, badge_list=badge_list) 
Example #2
Source File: Flask_hunter.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def tracked_menu_word():
    filter_type = 'word'
    user_id = current_user.get_id()
    user_term = Term.get_all_user_tracked_terms(user_id, filter_type='word')
    global_term = Term.get_all_global_tracked_terms(filter_type='word')
    return render_template("trackersManagement.html", user_term=user_term, global_term=global_term, bootstrap_label=bootstrap_label, filter_type=filter_type) 
Example #3
Source File: Flask_hunter.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def tracked_menu_set():
    filter_type = 'set'
    user_id = current_user.get_id()
    user_term = Term.get_all_user_tracked_terms(user_id, filter_type=filter_type)
    global_term = Term.get_all_global_tracked_terms(filter_type=filter_type)
    return render_template("trackersManagement.html", user_term=user_term, global_term=global_term, bootstrap_label=bootstrap_label, filter_type=filter_type) 
Example #4
Source File: Flask_hunter.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_tracked_menu():
    if request.method == 'POST':
        term = request.form.get("term")
        term_type  = request.form.get("tracker_type")
        nb_words = request.form.get("nb_word", 1)
        description = request.form.get("description", '')
        level = request.form.get("level", 0)
        tags = request.form.get("tags", [])
        mails = request.form.get("mails", [])

        if level == 'on':
            level = 1

        if mails:
            mails = mails.split()
        if tags:
            tags = tags.split()

        input_dict = {"term": term, "type": term_type, "nb_words": nb_words, "tags": tags, "mails": mails, "level": level, "description": description}
        user_id = current_user.get_id()
        res = Term.parse_json_term_to_add(input_dict, user_id)
        if res[1] == 200:
            return redirect(url_for('hunter.tracked_menu'))
        else:
            ## TODO: use modal
            return Response(json.dumps(res[0], indent=2, sort_keys=True), mimetype='application/json'), res[1]
    else:
        return render_template("Add_tracker.html") 
Example #5
Source File: Flask_hunter.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def show_tracker():
    user_id = current_user.get_id()
    term_uuid = request.args.get('uuid', None)
    res = Term.check_term_uuid_valid_access(term_uuid, user_id)
    if res: # invalid access
        return Response(json.dumps(res[0], indent=2, sort_keys=True), mimetype='application/json'), res[1]

    date_from = request.args.get('date_from')
    date_to = request.args.get('date_to')

    if date_from:
        date_from = date_from.replace('-', '')
    if date_to:
        date_to = date_to.replace('-', '')

    tracker_metadata = Term.get_term_metedata(term_uuid, user_id=True, level=True, description=True, tags=True, mails=True, sparkline=True)

    if date_from:
        res = Term.parse_get_tracker_term_item({'uuid': term_uuid, 'date_from': date_from, 'date_to': date_to}, user_id)
        if res[1] !=200:
            return Response(json.dumps(res[0], indent=2, sort_keys=True), mimetype='application/json'), res[1]
        tracker_metadata['items'] = res[0]['items']
        tracker_metadata['date_from'] = res[0]['date_from']
        tracker_metadata['date_to'] = res[0]['date_to']
    else:
        tracker_metadata['items'] = []
        tracker_metadata['date_from'] = ''
        tracker_metadata['date_to'] = ''

    return render_template("showTracker.html", tracker_metadata=tracker_metadata, bootstrap_label=bootstrap_label) 
Example #6
Source File: Flask_hunter.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def update_tracker_tags():
    user_id = current_user.get_id()
    term_uuid = request.form.get('uuid')
    res = Term.check_term_uuid_valid_access(term_uuid, user_id)
    if res: # invalid access
        return Response(json.dumps(res[0], indent=2, sort_keys=True), mimetype='application/json'), res[1]
    tags = request.form.get('tags')
    if tags:
        tags = tags.split()
    else:
        tags = []
    Term.replace_tracked_term_tags(term_uuid, tags)
    return redirect(url_for('hunter.show_tracker', uuid=term_uuid)) 
Example #7
Source File: Flask_hunter.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def update_tracker_mails():
    user_id = current_user.get_id()
    term_uuid = request.form.get('uuid')
    res = Term.check_term_uuid_valid_access(term_uuid, user_id)
    if res: # invalid access
        return Response(json.dumps(res[0], indent=2, sort_keys=True), mimetype='application/json'), res[1]
    mails = request.form.get('mails')
    if mails:
        mails = mails.split()
    else:
        mails = []
    res = Term.replace_tracked_term_mails(term_uuid, mails)
    if res: # invalid mail
        return Response(json.dumps(res[0], indent=2, sort_keys=True), mimetype='application/json'), res[1]
    return redirect(url_for('hunter.show_tracker', uuid=term_uuid)) 
Example #8
Source File: Flask_hunter.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete_tracker():
    user_id = current_user.get_id()
    term_uuid = request.args.get('uuid')
    res = Term.parse_tracked_term_to_delete({'uuid': term_uuid}, user_id)
    if res[1] !=200:
        return Response(json.dumps(res[0], indent=2, sort_keys=True), mimetype='application/json'), res[1]
    return redirect(url_for('hunter.tracked_menu')) 
Example #9
Source File: Flask_settings.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def edit_profile():
    user_metadata = get_user_metadata(current_user.get_id())
    admin_level = current_user.is_in_role('admin')
    return render_template("edit_profile.html", user_metadata=user_metadata,
                            admin_level=admin_level) 
Example #10
Source File: Flask_settings.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def new_token():
    generate_new_token(current_user.get_id())
    return redirect(url_for('settings.edit_profile')) 
Example #11
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def chapter(chapter_number):
    badge_list = []
    read_verses = []
    if chapter_number not in range(1, 19):
        abort(404)
    language = "en"
    if "settings" in request.cookies:
        if json.loads(request.cookies.get('settings'))["language"]:
            language = json.loads(request.cookies.get('settings'))["language"]

    if request.args.get('page'):
        page_number = int(request.args.get('page'))
    else:
        page_number = 1

    if language == "en":
        if current_user.is_authenticated:
            sql = """
                    SELECT verse
                    FROM user_progress
                    WHERE user_id = %s
                    AND chapter = %s
                """ % (current_user.get_id(), chapter_number)
            result = db.session.execute(sql)
            read_verses = [r['verse'] for r in result]

        chapter = ChapterModel.find_by_chapter_number(chapter_number)
        verses = VerseModel.query.filter_by(
            chapter_number=chapter_number).order_by(
                VerseModel.verse_order).paginate(
                    per_page=6, page=page_number, error_out=True)
        return render_template(
            'main/chapter.html',
            chapter=chapter,
            verses=verses,
            badge_list=badge_list,
            read_verses=read_verses)
    else:
        return redirect('/chapter/' + str(chapter_number) + '/' + language +
                        '/') 
Example #12
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def chapter_radhakrishna(chapter_number, language):
    badge_list = []
    read_verses = []
    if chapter_number not in range(1, 19):
        abort(404)
    if language not in LANGUAGES.keys():
        abort(404)
    if request.args.get('page'):
        page_number = int(request.args.get('page'))
    else:
        page_number = 1
    if current_user.is_authenticated:
        sql = """
                SELECT verse
                FROM user_progress
                WHERE user_id = %s
                AND chapter = %s
            """ % (current_user.get_id(), chapter_number)
        result = db.session.execute(sql)
        read_verses = [r['verse'] for r in result]
    chapter = ChapterModel.query.join(
        ChapterModelHindi, ChapterModel.chapter_number ==
        ChapterModelHindi.chapter_number).add_columns(
            ChapterModelHindi.name_translation, ChapterModelHindi.name_meaning,
            ChapterModelHindi.chapter_summary, ChapterModel.image_name,
            ChapterModel.chapter_number).filter(
                ChapterModel.chapter_number == chapter_number).order_by(
                    ChapterModel.chapter_number).first()
    verses = VerseModelHindi.query.filter_by(
        chapter_number=chapter_number).order_by(
            VerseModelHindi.verse_order).paginate(
                per_page=6, page=page_number, error_out=True)
    return render_template(
        'main/chapter.html',
        chapter=chapter,
        verses=verses,
        badge_list=badge_list,
        read_verses=read_verses) 
Example #13
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def share():
    current_app.logger.info("RadhaKrishna")
    badge_list = []
    if current_user.is_authenticated:
        badge_id_list = [34]
        if badge_id_list != []:
            for badge_id in badge_id_list:
                sql = """
                        SELECT COUNT(*) as count
                        FROM user_badges
                        WHERE user_id = %s
                        AND badge_id = %s
                    """ % (current_user.get_id(), badge_id)
                result = db.session.execute(sql)
                badge_count = [dict(r) for r in result][0]['count']

                if badge_count < 1:
                    timestamp = datetime.now()
                    sql = """
                        INSERT INTO user_badges (user_id, badge_id, timestamp)
                        VALUES (%s, %s, '%s')
                    """ % (current_user.get_id(), badge_id, timestamp)
                    db.session.execute(sql)
                    db.session.commit()

                    sql = """
                        SELECT *
                        FROM badges
                        WHERE badge_id = %s
                    """ % (badge_id)
                    result = db.session.execute(sql)
                    badge = [dict(r) for r in result][0]
                    badge_list.append(badge)
    return jsonify(badge_list) 
Example #14
Source File: Flask_hunter.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def tracked_menu_regex():
    filter_type = 'regex'
    user_id = current_user.get_id()
    user_term = Term.get_all_user_tracked_terms(user_id, filter_type=filter_type)
    global_term = Term.get_all_global_tracked_terms(filter_type=filter_type)
    return render_template("trackersManagement.html", user_term=user_term, global_term=global_term, bootstrap_label=bootstrap_label, filter_type=filter_type) 
Example #15
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def badges():
    current_app.logger.info("RadhaKrishna")
    badges = None
    badge_list = []
    user_badges = None
    if current_user.is_authenticated:
        sql = """
            SELECT *
            FROM badges
            ORDER BY badges.badge_id
        """
        result = db.session.execute(sql)
        badges = [dict(d) for d in result]

        sql = """
            SELECT badge_id
            FROM user_badges
            WHERE user_id = %s
            ORDER BY badge_id
        """ % (current_user.get_id())
        result = db.session.execute(sql)
        user_badges = [d['badge_id'] for d in result]

    return render_template(
        'main/badges.html',
        badges=badges,
        user_badges=user_badges,
        badge_list=badge_list) 
Example #16
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def thegita():
    current_app.logger.info("RadhaKrishna")

    sql = """
            SELECT EXTRACT(EPOCH FROM timestamp), count(*)
            FROM user_progress
            WHERE user_id = %s
            AND date_part('year', timestamp) = '2018'
            GROUP BY EXTRACT(EPOCH FROM timestamp)
        """ % (current_user.get_id())
    result = db.session.execute(sql)
    thegita = {r['date_part']: r['count'] for r in result}

    return jsonify(thegita) 
Example #17
Source File: grader.py    From faceworks with MIT License 5 votes vote down vote up
def get_id(self):
        return str(self.id) 
Example #18
Source File: grader.py    From faceworks with MIT License 5 votes vote down vote up
def score_route_view():
    next_image = _select_image(int(current_user.get_id()))
    if not next_image:
        return redirect('/finished')
    return redirect('/score/%s' % next_image.id) 
Example #19
Source File: grader.py    From faceworks with MIT License 5 votes vote down vote up
def score_view(vid):
    if request.method == 'GET':
        image = db_session.query(Image).filter(
            Image.id == int(vid)).one_or_none()
        if not image:
            return redirect('/score')
        return render_template('score.html', image_url='/images/' + image.md5,
                               sys_process=_get_sys_process(),
                               user_process=_get_user_process(int(current_user.get_id())))
    else:
        score = request.form.get('score')
        if score == None:
            abort(405)
        score = int(score)
        _put_score(int(current_user.get_id()), int(vid), score=score)
        return redirect('/score') 
Example #20
Source File: views.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def request_coordinator_privileges():
    """
    Submits a request for coordinator privileges.

    :return:
    """
    _user_id = int(current_user.get_id())
    message = request.form['message']
    experiment = request.form['experiment']

    existing_requests = get_pending_request()

    if len(existing_requests) > 0:
        return jsonify({'message': 'Pending coordinator requests already exist for this user.',
                        'status': 'error'})
    try:
        coordinator_request = CoordinatorRequest(user=_user_id, message=str(message), collaboration=experiment)

        db.session.add(coordinator_request)
        db.session.commit()

        send_coordinator_request_mail(coordinator_request)
    except Exception as e:
        db.session.rollback()
        return jsonify({"status": "error", "message": e.__str__()})

    return jsonify({'message': 'Request sent successfully.', 'status': 'ok'}) 
Example #21
Source File: views.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def assign_role(cookie):
    try:
        participant_record = SubmissionParticipant.query.filter(
            func.lower(SubmissionParticipant.email) == func.lower(current_user.email),
            SubmissionParticipant.invitation_cookie == cookie).first()
        participant_record.user_account = current_user.get_id()

        db.session.add(participant_record)
        db.session.commit()

        return redirect('/record/{0}'.format(participant_record.publication_recid))

    except:
        abort(403) 
Example #22
Source File: api.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def get_records_participated_in_by_user():
    _current_user_id = int(current_user.get_id())
    as_uploader = SubmissionParticipant.query.filter_by(user_account=_current_user_id, role='uploader').order_by(
        SubmissionParticipant.id.desc()).all()
    as_reviewer = SubmissionParticipant.query.filter_by(user_account=_current_user_id, role='reviewer').order_by(
        SubmissionParticipant.id.desc()).all()

    as_coordinator_query = HEPSubmission.query.filter_by(coordinator=_current_user_id).order_by(
        HEPSubmission.created.desc())

    # special case, since this user ID is the one used for loading all submissions, which is in the 1000s.
    if _current_user_id == 1:
        as_coordinator_query = as_coordinator_query.limit(5)

    as_coordinator = as_coordinator_query.all()

    result = {'uploader': [], 'reviewer': [], 'coordinator': []}
    if as_uploader:
        _uploader = [get_record_contents(x.publication_recid) for x in as_uploader]
        result['uploader'] = filter(partial(is_not, None), _uploader)

    if as_reviewer:
        _uploader = [get_record_contents(x.publication_recid) for x in as_reviewer]
        result['reviewer'] = filter(partial(is_not, None), _uploader)

    if as_coordinator:
        _coordinator = [get_record_contents(x.publication_recid) for x in as_coordinator]
        result['coordinator'] = filter(partial(is_not, None), _coordinator)

    return list(result) 
Example #23
Source File: api.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def get_pending_request():
    """
    Returns True if current user has an existing request.

    :return:
    """
    _current_user_id = int(current_user.get_id())

    existing_request = CoordinatorRequest.query.filter_by(
        user=_current_user_id, in_queue=True).all()

    return existing_request 
Example #24
Source File: api.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def user_allowed_to_perform_action(recid):
    """Determines if a user is allowed to perform an action on a record."""
    if not current_user.is_authenticated:
        return False

    if user_is_admin(current_user):
        return True

    is_participant = SubmissionParticipant.query.filter_by(
        user_account=int(current_user.get_id()), publication_recid=recid, status='primary').count() > 0

    if is_participant:
        return True

    is_coordinator = HEPSubmission.query.filter_by(publication_recid=recid,
                                                   coordinator=int(current_user.get_id())).count() > 0

    return is_coordinator 
Example #25
Source File: views.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def submissions():
    from flask import abort

    if has_role(current_user, 'admin'):
        user_profile = current_userprofile.query.filter_by(user_id=current_user.get_id()).first()

        ctx = {'user_is_admin': True,
               'user_profile': user_profile}
        return render_template('hepdata_dashboard/submissions.html', ctx=ctx)
    else:
        abort(403) 
Example #26
Source File: api.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def determine_user_privileges(recid, ctx):
    # show_review_area = not show_upload_area
    ctx['show_review_widget'] = False
    ctx['show_upload_widget'] = False
    ctx['is_submission_coordinator_or_admin'] = False
    ctx['is_admin'] = False

    if current_user.is_authenticated:
        user_id = current_user.get_id()
        participant_records = SubmissionParticipant.query.filter_by(
            user_account=user_id, publication_recid=recid).all()

        for participant_record in participant_records:
            if participant_record is not None:
                if participant_record.role == 'reviewer' and participant_record.status == 'primary':
                    ctx['show_review_widget'] = True

                if participant_record.role == 'uploader' and participant_record.status == 'primary':
                    ctx['show_upload_widget'] = True

        user = User.query.get(current_user.get_id())
        if has_role(user, 'admin'):
            ctx['is_submission_coordinator_or_admin'] = True
            ctx['is_admin'] = True
        else:
            matching_records = HEPSubmission.query.filter_by(
                publication_recid=recid,
                coordinator=current_user.get_id()).count()

            if matching_records > 0:
                ctx['is_submission_coordinator_or_admin'] = True

        ctx['show_upload_widget'] = (
            ctx['show_upload_widget'] or ctx[
                'is_submission_coordinator_or_admin']) 
Example #27
Source File: import_export.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def export_object():
    user_id = current_user.get_id()
    l_obj_to_export = set()

    # get user saved obj to export
    l_obj_to_export = AILObjects.get_user_list_of_obj_to_export(user_id)

    return render_template("export_object.html", l_obj_to_export=l_obj_to_export) 
Example #28
Source File: generic.py    From chirp with MIT License 5 votes vote down vote up
def settings():
    """Render the settings page."""
    c = mongo.db[app.config['USERS_COLLECTION']]
    user = c.find_one({'username': current_user.get_id()})
    if not user:
        return render_template()
    user['id'] = str(user['_id'])
    user.pop('_id', None)
    if current_user.is_admin():
        g = mongo.db[app.config['GLOBAL_COLLECTION']]
        data = g.find_one(dict(), {'_id': 0})
        user['admin'] = data
    user['has_session'] = True
    if not os.path.exists(SESSION_FILE):
        user['has_session'] = False
    return render_template('settings.html', user=user) 
Example #29
Source File: test_views.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def test_editor_get(self):
        user_id = "testuser"
        with self.client:
            # access to editor should be forbidden before login
            response = self.client.get("/blog/editor/")
            self.assertEqual(response.status_code, 401)

            response = self.client.get("/blog/editor/%s/" % self.pids[0])
            self.assertEqual(response.status_code, 401)

            self.login(user_id)
            self.assertEquals(current_user.get_id(), user_id)
            response = self.client.get("/blog/editor/")
            assert response.status_code == 200

            for i in range(1, 21):
                # logged in user can edit their post, and will be redirected
                # if they try to edit other's post
                response = self.client.get("/blog/editor/%s/" % self.pids[i-1])
                expected_status_code = 200 if i <= 10 else 302
                self.assertEqual(response.status_code, expected_status_code,
                                 "Error for item %s %d" %
                                 (self.pids[i - 1], response.status_code))
            # logout and the access should be gone again
            self.logout()
            response = self.client.get("/blog/editor/")
            self.assertEqual(response.status_code, 401)

            response = self.client.get("/blog/editor/%s/" % self.pids[0])
            self.assertEqual(response.status_code, 401) 
Example #30
Source File: test_views.py    From Flask-Blogging with MIT License 5 votes vote down vote up
def test_editor_post(self):
        user_id = "testuser"
        with self.client:
            # access to editor should be forbidden before login
            response = self.client.get("/blog/page/21/",
                                       follow_redirects=True)
            assert "The page you are trying to access is not valid!" in \
                   str(response.data)

            response = self.client.post("/blog/editor/")
            self.assertEqual(response.status_code, 401)

            response = self.client.post("/blog/editor/%s/" % self.pids[0])
            self.assertEqual(response.status_code, 401)

            self.login(user_id)
            self.assertEquals(current_user.get_id(), user_id)

            response = self.client.post("/blog/editor/",
                                        data=dict(text="Test Text",
                                                  tags="tag1, tag2"))
            # should give back the editor page
            self.assertEqual(response.status_code, 200)

            response = self.client.post("/blog/editor/",
                                        data=dict(title="Test Title",
                                                  text="Test Text",
                                                  tags="tag1, tag2"))
            self.assertEqual(response.status_code, 302)

            response = self.client.get("/blog/page/%s/" % self.pids[19])
            self.assertEqual(response.status_code, 200)