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 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: auth.py    From flask-session-tutorial with MIT License 5 votes vote down vote up
def login():
    """
    Log-in page for registered users.
    GET: Serve Log-in page.
    POST: Validate form and redirect user to dashboard.
    """
    if current_user.is_authenticated:
        return redirect(url_for('main_bp.dashboard'))  # Bypass if user is logged in

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()  # Validate Login Attempt
        if user and user.check_password(password=form.password.data):
            login_user(user)
            next_page = request.args.get('next')
            return redirect(next_page or url_for('main_bp.dashboard'))
        flash('Invalid username/password combination')
        return redirect(url_for('auth_bp.login'))
    return render_template(
        'login.jinja2',
        form=form,
        title='Log in.',
        template='login-page',
        body="Log in with your User account."
    ) 
Example #19
Source File: decorators.py    From comport with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def authorized_access_only(dataset=None):
    ''' Decorates views that require authentication if the department is not public
    '''
    def check_authorized(view_function):
        @wraps(view_function)
        def decorated_function(*args, **kwargs):
            try:
                department = Department.query.filter_by(short_name=kwargs["short_name"].upper()).first()
            except KeyError:
                department = Department.query.filter_by(id=kwargs["department_id"]).first()

            # check whether the current dataset is public
            dataset_is_public = True
            if dataset:
                try:
                    dataset_is_public = getattr(department, "is_public_{}".format(dataset))
                except ValueError:
                    dataset_is_public = True

            # check whether the user has access to this department
            if current_user.is_authenticated():
                user_has_dept_access = current_user.has_department(department.id) or current_user.is_admin()
            else:
                user_has_dept_access = False

            # abort with a 403 Forbidden if the department or dataset's not public and the user's not authorized to access it
            if (not department.is_public or not dataset_is_public) and (not current_user.is_authenticated() or not user_has_dept_access):
                abort(403)

            return view_function(*args, **kwargs)
        return decorated_function
    return check_authorized 
Example #20
Source File: routes.py    From thewarden with MIT License 5 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.
    if current_user.is_authenticated:
        transactions = Trades.query.filter_by(user_id=current_user.username)
        if transactions.count() == 0:
            return redirect(url_for("main.get_started")) 
Example #21
Source File: routes.py    From thewarden with MIT License 5 votes vote down vote up
def register():
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    form = RegistrationForm()
    if form.validate_on_submit():
        hash = generate_password_hash(form.password.data)
        user = User(username=form.username.data,
                    email=form.email.data,
                    password=hash)
        db.session.add(user)
        db.session.commit()
        flash(f"Account created for {form.username.data}.", "success")
        return redirect(url_for("users.login"))
    return render_template("register.html", title="Register", form=form) 
Example #22
Source File: middleware.py    From gitlab-tools with GNU General Public License v3.0 5 votes vote down vote up
def before_request():
    menu_items = []

    if current_user.is_authenticated:
        menu_items.append(navigation.Item('Home', 'home.index.get_home'))
        menu_items.append(navigation.Item('Pull mirrors', 'pull_mirror.index.get_mirror'))
        menu_items.append(navigation.Item('Push mirrors', 'push_mirror.index.get_mirror'))
        menu_items.append(navigation.Item('Fingerprints', 'fingerprint.index.get_fingerprint'))

    navigation.Bar('top', menu_items) 
Example #23
Source File: server.py    From app with MIT License 5 votes vote down vote up
def set_index_page(app):
    @app.route("/", methods=["GET", "POST"])
    def index():
        if current_user.is_authenticated:
            return redirect(url_for("dashboard.index"))
        else:
            return redirect(url_for("auth.login"))

    @app.after_request
    def after_request(res):
        # not logging /static call
        if (
            not request.path.startswith("/static")
            and not request.path.startswith("/admin/static")
            and not request.path.startswith("/_debug_toolbar")
        ):
            LOG.debug(
                "%s %s %s %s %s",
                request.remote_addr,
                request.method,
                request.path,
                request.args,
                res.status_code,
            )

        return res 
Example #24
Source File: social.py    From app with MIT License 5 votes vote down vote up
def social():
    if current_user.is_authenticated:
        LOG.d("user is already authenticated, redirect to dashboard")
        return redirect(url_for("dashboard.index"))

    return render_template("auth/social.html") 
Example #25
Source File: login.py    From app with MIT License 5 votes vote down vote up
def login():
    if current_user.is_authenticated:
        LOG.d("user is already authenticated, redirect to dashboard")
        return redirect(url_for("dashboard.index"))

    form = LoginForm(request.form)
    next_url = request.args.get("next")
    show_resend_activation = False

    if form.validate_on_submit():
        user = User.filter_by(email=form.email.data.strip().lower()).first()

        if not user or not user.check_password(form.password.data):
            # Trigger rate limiter
            g.deduct_limit = True
            form.password.data = None
            flash("Email or password incorrect", "error")
        elif not user.activated:
            show_resend_activation = True
            flash(
                "Please check your inbox for the activation email. You can also have this email re-sent",
                "error",
            )
        else:
            return after_login(user, next_url)

    return render_template(
        "auth/login.html",
        form=form,
        next_url=next_url,
        show_resend_activation=show_resend_activation,
    ) 
Example #26
Source File: admin_model.py    From app with MIT License 5 votes vote down vote up
def is_accessible(self):
        return current_user.is_authenticated and current_user.is_admin 
Example #27
Source File: admin_model.py    From app with MIT License 5 votes vote down vote up
def index(self):
        if not current_user.is_authenticated or not current_user.is_admin:
            return redirect(url_for("auth.login", next=request.url))

        return super(SLAdminIndexView, self).index() 
Example #28
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def filter_logic(self, filters, skip, limit=None):
    query = self.generate_full_query(filters)
    limit = limit if limit else self.args['pageLength']
    cve   = db.getCVEs(limit=limit, skip=skip, query=query)
    # marking relevant records
    if current_user.is_authenticated():
        if filters['whitelistSelect'] == "on":   cve = self.list_mark('white', cve)
        if filters['blacklistSelect'] == "mark": cve = self.list_mark('black', cve)
    self.plugManager.mark(cve, **self.pluginArgs)
    cve = list(cve)
    return cve 
Example #29
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def _get_plugins(self):
    if not current_user.is_authenticated(): # Don't show plugins requiring auth if not authenticated
      plugins = [{"name": x.getName(), "link": x.getUID()} for x in
                 self.plugManager.getWebPluginsWithPage(**self.pluginArgs) if not x.requiresAuth]
    else:
      plugins = [{"name": x.getName(), "link": x.getUID()} for x in
                 self.plugManager.getWebPluginsWithPage(**self.pluginArgs)]
    return jsonify({"plugins": plugins})


  # /plugin/_get_cve_actions 
Example #30
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def _get_cve_actions(self):
    cve = request.args.get('cve', type=str)
    if not current_user.is_authenticated(): # Don't show actions requiring auth if not authenticated
      actions = [x for x in self.plugManager.getCVEActions(cve, **self.pluginArgs) if not x['auth']]
    else:
      actions = self.plugManager.getCVEActions(cve, **self.pluginArgs)
    return jsonify({"actions": actions})


  # /plugin/<plugin>