Python flask_login.current_user.is_authenticated() Examples

The following are 30 code examples of flask_login.current_user.is_authenticated(). 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: routes.py    From thewarden with MIT License 8 votes vote down vote up
def home():
    if current_user.is_authenticated:
        return redirect(url_for("portfolio.portfolio_main"))
    else:
        form = LoginForm()
        if form.validate_on_submit():
            user = User.query.filter_by(email=form.email.data).first()
            if user and check_password_hash(user.password, form.password.data):
                login_user(user, remember=form.remember.data)
                # The get method below is actually very helpful
                # it returns None if empty. Better than using [] for a dictionary.
                next_page = request.args.get("next")  # get the original page
                if next_page:
                    return redirect(next_page)
                else:
                    return redirect(url_for("main.home"))
            else:
                flash("Login failed. Please check e-mail and password",
                      "danger")

        return render_template("index.html", title="Login", form=form) 
Example #2
Source File: routes.py    From thewarden with MIT License 8 votes vote down vote up
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    user = User.verify_reset_token(token)
    if user is None:
        flash("That is an invalid or expired token", "warning")
        return redirect(url_for("users.reset_request"))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hash = generate_password_hash(form.password.data)
        user.password = hash
        db.session.commit()
        flash("Your password has been updated! You are now able to log in",
              "success")
        return redirect(url_for("users.login"))
    return render_template("reset_token.html",
                           title="Reset Password",
                           form=form) 
Example #3
Source File: routes.py    From VectorCloud with GNU General Public License v3.0 6 votes vote down vote up
def check_valid_login():
    user = db.session.query(User).first()

    if any([request.endpoint.startswith('static'),
            current_user.is_authenticated,
            getattr(app.view_functions[request.endpoint],
                    'is_public', False)]):
        return

    elif user is None:
        return redirect(url_for('user_system.register'))

    else:
        return redirect(url_for('user_system.login'))


# this was a fix to make sure images stored in the cache are deleted when
# a new image is uploaded 
Example #4
Source File: routes.py    From AUCR with GNU General Public License v3.0 6 votes vote down vote up
def reset_password(token):
    """User reset password with token AUCR auth plugin blueprint."""
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    user_name = User.verify_reset_password_token(token)
    if not user_name:
        return redirect(url_for('index'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        user_name.set_password(form.password.data)
        db.session.commit()
        flash(_('Your password has been reset.'))
        return redirect(url_for('auth.login'))
    else:
        for error in form.errors:
            flash(str(form.errors[error][0]), 'error')
        return render_template('reset_password.html', form=form) 
Example #5
Source File: login.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def login():
    if current_user.is_authenticated:
        return redirect(url_for('tracker.index'))

    form = LoginForm()
    if not form.validate_on_submit():
        status_code = Unauthorized.code if form.is_submitted() else 200
        return render_template('login.html',
                               title='Login',
                               form=form,
                               User=User,
                               password_length={'min': TRACKER_PASSWORD_LENGTH_MIN,
                                                'max': TRACKER_PASSWORD_LENGTH_MAX}), status_code

    user = user_assign_new_token(form.user)
    user.is_authenticated = True
    login_user(user)
    return redirect(url_for('tracker.index')) 
Example #6
Source File: index.py    From watchdog with Apache License 2.0 6 votes vote down vote up
def admin(self):
    if Configuration.loginRequired():
        if not current_user.is_authenticated():
            return render_template('login.html')
    else:
        person = User.get("_dummy_", self.auth_handler)
        login_user(person)
    output = None
    if os.path.isfile(Configuration.getUpdateLogFile()):
        with open(Configuration.getUpdateLogFile()) as updateFile:
            separator="==========================\n"
            output=updateFile.read().split(separator)[-2:]
            output=separator+separator.join(output)
    return render_template('admin.html', status="default", **self.adminInfo(output))


  # /admin/change_pass 
Example #7
Source File: routes.py    From AUCR with GNU General Public License v3.0 6 votes vote down vote up
def register():
    """AUCR auth plugin user register flask blueprint."""
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    form = RegistrationForm()
    if request.method == "POST":
        form = RegistrationForm(request.form)
        if form.validate_on_submit():
            user_name = User.__call__(username=form.username.data, email=form.email.data,  website=form.website.data,
                                      affiliation=form.affiliation.data, country=form.country.data)
            user_name.set_password(form.password.data)
            db.session.add(user_name)
            db.session.commit()
            user_group = Group.__call__(groups_id=2, username_id=user_name.id)
            db.session.add(user_group)
            db.session.commit()
            session['username'] = user_name.username
            flash(_('Congratulations, you are now a registered user!'))
            return redirect(url_for('auth.login'))
        else:
            for error in form.errors:
                flash(str(form.errors[error][0]), 'error')
            return redirect(url_for('auth.register'))
    return render_template('register.html', title=_('Register'), form=form) 
Example #8
Source File: utils.py    From flask-security with MIT License 6 votes vote down vote up
def suppress_form_csrf():
    """
    Return meta contents if we should suppress form from attempting to validate CSRF.

    If app doesn't want CSRF for unauth endpoints then check if caller is authenticated
    or not (many endpoints can be called either way).
    """
    if get_request_attr("fs_ignore_csrf"):
        # This is the case where CsrfProtect was already called (e.g. @auth_required)
        return {"csrf": False}
    if (
        config_value("CSRF_IGNORE_UNAUTH_ENDPOINTS")
        and not current_user.is_authenticated
    ):
        return {"csrf": False}
    return {} 
Example #9
Source File: index.py    From watchdog with Apache License 2.0 6 votes vote down vote up
def generate_full_query(self, f):
    query = self.generate_minimal_query(f)
    if current_user.is_authenticated():
        if f['blacklistSelect'] == "on":
            regexes = db.getRules('blacklist')
            if len(regexes) != 0:
                exp = "^(?!" + "|".join(regexes) + ")"
                query.append({'$or': [{'vulnerable_configuration': re.compile(exp)},
                                      {'vulnerable_configuration': {'$exists': False}},
                                      {'vulnerable_configuration': []} ]})
        if f['whitelistSelect'] == "hide":
            regexes = db.getRules('whitelist')
            if len(regexes) != 0:
                exp = "^(?!" + "|".join(regexes) + ")"
                query.append({'$or': [{'vulnerable_configuration': re.compile(exp)},
                                      {'vulnerable_configuration': {'$exists': False}},
                                      {'vulnerable_configuration': []} ]})
        if f['unlistedSelect'] == "hide":
            wlregexes = tk.compile(db.getRules('whitelist'))
            blregexes = tk.compile(db.getRules('blacklist'))
            query.append({'$or': [{'vulnerable_configuration': {'$in': wlregexes}},
                                  {'vulnerable_configuration': {'$in': blregexes}}]})
    return query 
Example #10
Source File: sites.py    From daimaduan.com with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def finish_signup():
    form = UserInfoForm(request.form)
    if form.validate():
        if current_user.is_authenticated:
            current_user.user.username = form.username.data
            return redirect('/')
        else:
            user = User(email=form.email.data, username=form.username.data,
                        is_email_confirmed=True)
            user.save()
            bookmark = Bookmark(user=user,
                                title=u"%s 的收藏夹" % user.username,
                                is_default=True)
            bookmark.save()
            user_mixin = LoginManagerUser(user)
            login_user(user_mixin)
            flash(u"登录成功", category='info')
            if 'email' in session:
                del (session['email'])
            return redirect('/')
    return render_template('users/finish_signup.html',
                           form=form) 
Example #11
Source File: helper.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def get_download_link(book_id, book_format, client):
    book_format = book_format.split(".")[0]
    book = calibre_db.get_filtered_book(book_id)
    if book:
        data1 = calibre_db.get_book_format(book.id, book_format.upper())
    else:
        abort(404)
    if data1:
        # collect downloaded books only for registered user and not for anonymous user
        if current_user.is_authenticated:
            ub.update_download(book_id, int(current_user.id))
        file_name = book.title
        if len(book.authors) > 0:
            file_name = book.authors[0].name + '_' + file_name
        file_name = get_valid_filename(file_name)
        headers = Headers()
        headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream")
        headers["Content-Disposition"] = "attachment; filename=%s.%s; filename*=UTF-8''%s.%s" % (
            quote(file_name.encode('utf-8')), book_format, quote(file_name.encode('utf-8')), book_format)
        return do_download_file(book, book_format, client, data1, headers)
    else:
        abort(404) 
Example #12
Source File: base.py    From app with MIT License 6 votes vote down vote up
def require_api_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if current_user.is_authenticated:
            g.user = current_user
        else:
            api_code = request.headers.get("Authentication")
            api_key = ApiKey.get_by(code=api_code)

            if not api_key:
                return jsonify(error="Wrong api key"), 401

            # Update api key stats
            api_key.last_used = arrow.now()
            api_key.times += 1
            db.session.commit()

            g.user = api_key.user

        return f(*args, **kwargs)

    return decorated 
Example #13
Source File: views.py    From circleci-demo-python-flask with MIT License 6 votes vote down vote up
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and \
            form.validate_on_submit():
        post = Post(body=form.body.data,
                    author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    return render_template('index.html', form=form, posts=posts,
                           show_followed=show_followed, pagination=pagination) 
Example #14
Source File: routes.py    From thewarden with MIT License 6 votes vote down vote up
def reset_request():
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash(
            "An email has been sent with instructions to reset your" +
            " password.",
            "info",
        )
        return redirect(url_for("users.login"))
    return render_template("reset_request.html",
                           title="Reset Password",
                           form=form) 
Example #15
Source File: routes.py    From thewarden with MIT License 6 votes vote down vote up
def before_request():
    # Before any request at main, check if API Keys are set
    # But only if user is logged in.
    exclude_list = ["main.get_started", "main.importcsv", "main.csvtemplate"]
    if request.endpoint not in exclude_list:
        if current_user.is_authenticated:
            from thewarden.pricing_engine.pricing import api_keys_class
            api_keys_json = api_keys_class.loader()
            aa_apikey = api_keys_json['alphavantage']['api_key']
            if aa_apikey is None:
                logging.error("NO AA API KEY FOUND!")
                return render_template("welcome.html", title="Welcome")
            transactions = Trades.query.filter_by(
                user_id=current_user.username)
            if transactions.count() == 0:
                return redirect(url_for("main.get_started")) 
Example #16
Source File: admin.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def _configuration_result(error_flash=None, gdriveError=None):
    gdrive_authenticate = not is_gdrive_ready()
    gdrivefolders = []
    if gdriveError is None:
        gdriveError = gdriveutils.get_error_text()
    if gdriveError:
        gdriveError = _(gdriveError)
    else:
        # if config.config_use_google_drive and\
        if not gdrive_authenticate and gdrive_support:
            gdrivefolders = gdriveutils.listRootFolders()

    show_back_button = current_user.is_authenticated
    show_login_button = config.db_configured and not current_user.is_authenticated
    if error_flash:
        config.load()
        flash(error_flash, category="error")
        show_login_button = False

    return render_title_template("config_edit.html", config=config, provider=oauthblueprints,
                                 show_back_button=show_back_button, show_login_button=show_login_button,
                                 show_authenticate_google_drive=gdrive_authenticate,
                                 gdriveError=gdriveError, gdrivefolders=gdrivefolders, feature_support=feature_support,
                                 title=_(u"Basic Configuration"), page="config") 
Example #17
Source File: routes.py    From thewarden with MIT License 6 votes vote down vote up
def contact():

    form = ContactForm()

    if form.validate_on_submit():
        if current_user.is_authenticated:
            message = Contact(
                user_id=current_user.id,
                email=form.email.data,
                message=form.message.data,
            )
        else:
            message = Contact(user_id=0,
                              email=form.email.data,
                              message=form.message.data)

        db.session.add(message)
        db.session.commit()
        flash(f"Thanks for your message", "success")
        return redirect(url_for("main.home"))

    if current_user.is_authenticated:
        form.email.data = current_user.email
    return render_template("contact.html", form=form, title="Contact Form") 
Example #18
Source File: views.py    From Flashcards with MIT License 5 votes vote down vote up
def before_request():
    if current_user.is_authenticated:
        if not current_user.confirmed \
                and request.endpoint \
                and request.endpoint[:5] != 'auth.' \
                and request.endpoint != 'static':
            return redirect(url_for('auth.unconfirmed')) 
Example #19
Source File: visualisation.py    From contextualise with MIT License 5 votes vote down vote up
def network(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    collaboration_mode = None
    if current_user.is_authenticated:  # User is logged in
        is_map_owner = topic_store.is_topic_map_owner(map_identifier, current_user.id)
        if is_map_owner:
            topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
        else:
            topic_map = topic_store.get_topic_map(map_identifier)
        if topic_map is None:
            abort(404)
        collaboration_mode = topic_store.get_collaboration_mode(map_identifier, current_user.id)
        # The map is private and doesn't belong to the user who is trying to
        # access it
        if not topic_map.published and not is_map_owner:
            if not collaboration_mode:  # The user is not collaborating on the map
                abort(403)
    else:  # User is not logged in
        topic_map = topic_store.get_topic_map(map_identifier)
        if topic_map is None:
            abort(404)
        if not topic_map.published:  # User is not logged in and the map is not published
            abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "visualisation/network.html",
        topic_map=topic_map,
        topic=topic,
        creation_date=creation_date,
        collaboration_mode=collaboration_mode,
    ) 
Example #20
Source File: routes.py    From Hands-on-Microservices-with-Python with MIT License 5 votes vote down vote up
def home():
    # session.clear()
    if current_user.is_authenticated:
        # order = order
        session['order'] = OrderClient.get_order_from_session()

    try:
        products = ProductClient.get_products()
    except requests.exceptions.ConnectionError:
        products = {
            'results': []
        }

    return render_template('home/index.html', products=products)


# Login 
Example #21
Source File: decorators.py    From website with MIT License 5 votes vote down vote up
def http_cache(timeout=None):
    """
    Add Flask cache response headers based on timeout in seconds.

    If timeout is None, caching will be disabled.
    Otherwise, caching headers are set to expire in now + timeout seconds

    Example usage:

    @app.route('/map')
    @http_cache(timeout=60)
    def index():
      return render_template('index.html')

    Originally from https://gist.github.com/glenrobertson/954da3acec84606885f5
    """

    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            response = make_response(f(*args, **kwargs))
            if current_user.is_authenticated:
                return response
            else:
                return patch_http_cache_headers(response, timeout)

        return decorated_function

    return decorator 
Example #22
Source File: routes.py    From AUCR with GNU General Public License v3.0 5 votes vote down vote up
def login():
    """Flask AUCR user login route."""
    if current_user.is_authenticated:
        # if user is logged in we get out of here
        return redirect(url_for('main.index'))
    if request.method == "POST":
        form = LoginForm()
        if form.validate_on_submit():
            user_name = User.query.filter_by(username=form.username.data).first()
            if user_name is not None and user_name.otp_secret is not None:
                otp_auth_check = user_name.verify_totp(form.token.data)
                if otp_auth_check is False or not user_name.check_password(form.password.data):
                    flash('Invalid username, password or token.')
                    return redirect(url_for('auth.login'))
            if user_name is None or not user_name.check_password(form.password.data):
                flash('Invalid username, password or token.')
                return redirect(url_for('auth.login'))
            # log user in
            if form.remember_me.data:
                login_user(user_name, remember=form.remember_me.data)
            else:
                login_user(user_name)
            session["navbar"] = get_group_permission_navbar()
            session["groups"] = get_groups()
            flash('You are now logged in!')
            user_name.set_last_used_ip(request.access_route[0])
            db.session.add(user_name)
            db.session.commit()
            page = request.args.get('page', 1, type=int)
            return redirect(url_for('main.index', page=page))
        else:
            for error in form.errors:
                flash(str(form.errors[error][0]), 'error')
        flash('Invalid username, password or token.')
        return redirect(url_for('auth.login'))
    page = request.args.get('page', 1, type=int)
    form = LoginForm()
    return render_template('login.html', title=_('Sign In'), form=form, page=page) 
Example #23
Source File: login.py    From arch-security-tracker with MIT License 5 votes vote down vote up
def logout():
    if not current_user.is_authenticated:
        return redirect(url_for('tracker.index'))

    user_invalidate(current_user)
    logout_user()
    return redirect(url_for('tracker.index')) 
Example #24
Source File: routes.py    From AUCR with GNU General Public License v3.0 5 votes vote down vote up
def reset_password_request():
    """AUCR auth plugin reset password request flask blueprint."""
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    form = ResetPasswordRequestForm()
    if form.validate_on_submit():
        user_name = User.query.filter_by(email=form.email.data).first()
        if user_name:
            send_password_reset_email(user_name)
        flash(_('If that is a valid email the instructions have been sent to reset your password'))
        return redirect(url_for('auth.login'))
    else:
        for error in form.errors:
            flash(str(form.errors[error][0]), 'error')
        return render_template('reset_password_request.html', form=form) 
Example #25
Source File: permissions.py    From invenio-app-ils with MIT License 5 votes vote down vote up
def check_permission(permission):
    """Abort if permission is not allowed.

    :param permission: The permission to check.
    """
    if permission is not None and not permission.can():
        if not current_user.is_authenticated:
            abort(401)
        abort(403) 
Example #26
Source File: routes.py    From AUCR with GNU General Public License v3.0 5 votes vote down vote up
def before_request() -> None:
    """Set user last seen time user."""
    if current_user.is_authenticated:
        current_user.last_seen = udatetime.utcnow().replace(tzinfo=None)
        db.session.commit()
        g.search_form = SearchForm()
    g.locale = str(get_locale()) 
Example #27
Source File: views.py    From ACE with Apache License 2.0 5 votes vote down vote up
def index():
    # are we logged in?
    if not current_user.is_authenticated:
        return redirect(url_for('auth.login'))

    form = AppModeSelectionForm()
    if form.validate_on_submit():
        if form.manage_alerts.data: # submit form .data value is True when clicked
            flash("Feature is not implemented yet.")
        else:
            return redirect(url_for('analysis.index'))

    return render_template('index.html', form=form)#, ace_config=saq.CONFIG) 
Example #28
Source File: sites.py    From daimaduan.com with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def confirm_email(token):
    email = validate_token(current_app.config, token)
    if email:
        user = User.objects(email=email).first_or_404()
        if (current_user.is_authenticated and user == current_user.user) or not current_user.is_authenticated:
            if user.is_email_confirmed:
                return render_template('email/confirm.html', title=u"Email已经激活过了", message=u"对不起,您的email已经激活过了。")
            else:
                user.is_email_confirmed = True
                user.email_confirmed_on = datetime.now()
                user.save()
                return render_template('email/confirm.html', title=u'Email已经激活', message=u'您的email已经激活,请点击登录查看最新代码段。')
    return render_template('email/confirm.html',
                           title=u'Email验证链接错误',
                           message=u'对不起,您的验证链接无效或者已经过期。') 
Example #29
Source File: pastes.py    From daimaduan.com with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def view_paste(hash_id):
    paste = Paste.objects.get_or_404(hash_id=hash_id)
    paste.increase_views()

    paste_lists = []
    if current_user.is_authenticated:
        paste_lists = Bookmark.objects(user=current_user.user)

    syntax_list = [code.syntax for code in paste.codes]
    related_pastes = Paste.objects(codes__syntax__in=syntax_list).order_by('-created_at')[:10]

    return render_template('pastes/view.html',
                           paste=paste,
                           related_pastes=related_pastes,
                           paste_lists=paste_lists) 
Example #30
Source File: users.py    From daimaduan.com with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def view(username):
    page = get_page()
    user = User.objects.get_or_404(username=username)

    pastes = user.pastes.order_by('-updated_at')
    if not (current_user.is_authenticated and current_user.user == user):
        pastes = pastes(is_private=False)

    pagination = pastes.paginate(page, per_page=20)

    pastes = Paste.objects(user=user)
    syntax = {}
    for paste in pastes:
        for code in paste.codes:
            if code.syntax.name not in syntax:
                syntax[code.syntax.name] = 1
            else:
                syntax[code.syntax.name] += 1

    if len(syntax.keys()) > 3:
        most_syntax = [get_most_syntax(syntax) for i in range(3)]
    else:
        most_syntax = [Syntax.objects(name=key).first() for key in syntax]

    return render_template('users/user.html',
                           user=user,
                           pagination=pagination,
                           most_syntax=most_syntax,
                           tags=Tag.objects().order_by('-popularity')[:10])