Python flask.ext.login.current_user() Examples

The following are 16 code examples of flask.ext.login.current_user(). 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 , or try the search function .
Example #1
Source File: __init__.py    From JmilkFan-s-Blog with Apache License 2.0 6 votes vote down vote up
def new_post():
    """View function for new_port."""

    form = PostForm()

    # Ensure the user logged in.
    # Flask-Login.current_user can be access current user.
    if not current_user:
        return redirect(url_for('main.login'))

    # Will be execute when click the submit in the create a new post page.
    if form.validate_on_submit():
        new_post = Post()
        new_post.title = form.title.data
        new_post.text = form.text.data
        new_post.publish_date = datetime.now()
        new_post.user = current_user

        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('blog.home'))

    return render_template('new_post.html',
                           form=form) 
Example #2
Source File: test_lib_auth_auth_types_constant.py    From build-relengapi with Mozilla Public License 2.0 6 votes vote down vote up
def test_constant_login_logout(app, client):
    @app.route('/username')
    def username():
        return str(current_user)

    rv = client.get("/username")
    eq_((rv.status_code, rv.data), (200, "anonymous:"))
    rv = client.get(
        "/userauth/login?next=%2Fusername")
    eq_((rv.status_code, rv.headers['Location']), (
        302, "http://localhost/username"))
    rv = client.get("/username")
    eq_((rv.status_code, rv.data), (200, "human:me@me.com"))
    rv = client.get("/userauth/logout")
    eq_((rv.status_code, rv.headers['Location']), (302, "http://localhost/"))
    rv = client.get("/username")
    eq_((rv.status_code, rv.data), (200, "anonymous:")) 
Example #3
Source File: test_lib_auth_auth_types_external.py    From build-relengapi with Mozilla Public License 2.0 6 votes vote down vote up
def test_external_login_logout(app, client):
    @app.route('/username')
    def username():
        return str(current_user)

    rv = client.get("/username")
    eq_((rv.status_code, rv.data), (200, "anonymous:"))
    rv = client.get(
        "/userauth/login?next=%2Fusername", environ_overrides={'TEST': 'jimmy'})
    eq_((rv.status_code, rv.headers['Location']), (
        302, "http://localhost/username"))
    rv = client.get("/username")
    eq_((rv.status_code, rv.data), (200, "human:jimmy"))
    rv = client.get("/userauth/logout")
    eq_((rv.status_code, rv.headers['Location']), (302, "http://localhost/"))
    rv = client.get("/username")
    eq_((rv.status_code, rv.data), (200, "anonymous:")) 
Example #4
Source File: app.py    From imgfab with MIT License 5 votes vote down vote up
def global_user():
    g.user = login.current_user


# Make current user available on templates 
Example #5
Source File: forms.py    From scan with GNU Affero General Public License v3.0 5 votes vote down vote up
def save(self):
        from app import db
        q = Question(user=current_user)
        self.populate_obj(q)
        db.session.add(q)
        db.session.commit() 
Example #6
Source File: dataset.py    From spendb with GNU Affero General Public License v3.0 5 votes vote down vote up
def query_index():
    q = Dataset.all_by_account(current_user, order=False)
    q = q.order_by(Dataset.updated_at.desc())

    # Filter by languages if they have been provided
    for language in request.args.getlist('languages'):
        l = aliased(DatasetLanguage)
        q = q.join(l, Dataset._languages)
        q = q.filter(l.code == language)

    # Filter by territories if they have been provided
    for territory in request.args.getlist('territories'):
        t = aliased(DatasetTerritory)
        q = q.join(t, Dataset._territories)
        q = q.filter(t.code == territory)

    # Filter by account if one has been provided
    for account in request.args.getlist('account'):
        a = aliased(Account)
        q = q.join(a, Dataset.managers)
        q = q.filter(a.name == account)

    # Return a list of languages as dicts with code, count, url and label
    languages = [{'code': code, 'count': count, 'label': LANGUAGES.get(code)}
                 for (code, count) in DatasetLanguage.dataset_counts(q)]

    territories = [{'code': code, 'count': count, 'label': COUNTRIES.get(code)}
                   for (code, count) in DatasetTerritory.dataset_counts(q)]

    pager = Pager(q, limit=15)
    return pager, languages, territories 
Example #7
Source File: dataset.py    From spendb with GNU Affero General Public License v3.0 5 votes vote down vote up
def create():
    require.dataset.create()
    dataset = request_data()
    data = validate_dataset(dataset)
    if Dataset.by_name(data['name']) is not None:
        raise Invalid(SchemaNode(String(), name='name'),
                      _("A dataset with this identifer already exists!"))
    dataset = Dataset({'dataset': data, 'model': {}})
    dataset.managers.append(current_user)
    db.session.add(dataset)
    db.session.commit()
    return view(dataset.name) 
Example #8
Source File: dataset.py    From spendb with GNU Affero General Public License v3.0 5 votes vote down vote up
def update_managers(name):
    dataset = get_dataset(name)
    require.dataset.update(dataset)
    data = validate_managers(request_data())
    if current_user not in data['managers']:
        data['managers'].append(current_user)
    dataset.managers = data['managers']
    dataset.touch()
    db.session.commit()
    return managers(name) 
Example #9
Source File: context.py    From spendb with GNU Affero General Public License v3.0 5 votes vote down vote up
def etag_cache_keygen(key_obj, private=False):
    request._http_private = private

    args = sorted(set(request.args.items()))
    # jquery where is your god now?!?
    args = filter(lambda (k, v): k != '_', args)

    request._http_etag = cache_hash(args, current_user,
                                    key_obj, get_locale())
    if request.if_none_match == request._http_etag:
        raise NotModified() 
Example #10
Source File: __init__.py    From JmilkFan-s-Blog with Apache License 2.0 5 votes vote down vote up
def check_user():
    """Check the user whether logged in."""

    if 'username' in session:
        g.current_user = User.query.filter_by(
            username=session['username']).first()
    else:
        g.current_user = None 
Example #11
Source File: forms.py    From WatchPeopleCode with MIT License 5 votes vote down vote up
def validate_youtube_channel(form, field):
        yc = form.youtube_channel_extract()
        if yc is None:
            # FIXME: add explanation here or hint to page
            raise ValidationError("This field should contain a valid YouTube channel.")

        streamer = get_or_create(YoutubeChannel, channel_id=yc).streamer
        if streamer and streamer.checked and streamer != current_user:
            raise ValidationError("There is another user with this channel. If it is your channel, please message about that to /r/WatchPeoplecode moderators.") 
Example #12
Source File: forms.py    From WatchPeopleCode with MIT License 5 votes vote down vote up
def validate_twith_channel(form, field):
        tc = form.twitch_channel_extract()
        if tc is None:
            raise ValidationError('This field should contain a valid Twitch channel.')

        streamer = Streamer.query.filter_by(twitch_channel=tc).first()
        if streamer and streamer.checked and streamer != current_user:
            raise ValidationError("There is another user with this channel. If it is your channel, please message about that to /r/WatchPeoplecode moderators.") 
Example #13
Source File: test_lib_auth_auth_types_external.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def test_external_login_header(app, client):
    @app.route('/username')
    def username():
        return str(current_user)

    rv = client.get(
        "/userauth/login", headers={'USERNAME': 'jimmy'})
    rv = client.get("/username")
    eq_((rv.status_code, rv.data), (200, "human:jimmy")) 
Example #14
Source File: test_lib_auth_auth_types_external.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def test_external_login_no_data(app, client):
    @app.route('/username')
    def username():
        return str(current_user)

    rv = client.get("/userauth/login")  # no auth data
    eq_(rv.status_code, 500) 
Example #15
Source File: test_lib_auth.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def test_request_loader(app, client):
    @auth.request_loader
    def rl(req):
        if 'user' in req.headers:
            return auth.HumanUser(req.headers['user'])

    @app.route("/test")
    def test():
        return str(current_user)
    eq_(client.get('/test').data, 'anonymous:')
    eq_(client.get('/test', headers=[('user', 'f@n.com')]).data,
        'human:f@n.com') 
Example #16
Source File: __init__.py    From JmilkFan-s-Blog with Apache License 2.0 4 votes vote down vote up
def edit_post(id):
    """View function for edit_post."""

    post = Post.query.get_or_404(id)

    # Ensure the user logged in.
    if not current_user:
        return redirect(url_for('main.login'))

    # Only the post onwer can be edit this post.
    if current_user != post.user:
        return redirect(url_for('blog.post', post_id=id))

    # Admin can be edit the post.
    permission = Permission(UserNeed(post.user.id))
    if permission.can() or admin_permission.can():
        form = PostForm()

        # if current_user != post.user:
        #    abort(403)

        if form.validate_on_submit():
            post.title = form.title.data
            post.text = form.text.data
            post.publish_date = datetime.now()

            # Update the post
            db.session.add(post)
            db.session.commit()

            return redirect(url_for('blog.post', post_id=post.id))
    else:
        abort(403)

    # Still retain the original content, if validate is false.
    form.title.data = post.title
    form.text.data = post.text
    return render_template('edit_post.html', form=form, post=post)


# NOTE(Jmilk Fan): Use the Flask-Login's current_user object to replace
#                  g.current_user
# @blog_blueprint.before_request