我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.ext.login.current_user.is_authenticated()。
def index(window=0): """Get the last activity from users and projects.""" if current_user.is_authenticated(): user_id = current_user.id else: user_id = None if window >= 10: window = 10 top_users = cached_users.get_leaderboard(current_app.config['LEADERBOARD'], user_id=user_id, window=window) response = dict(template='/stats/index.html', title="Community Leaderboard", top_users=top_users) return handle_content_type(response)
def sanitize_project_owner(project, owner, current_user): """Sanitize project and owner data.""" if current_user.is_authenticated() and owner.id == current_user.id: if isinstance(project, Project): project_sanitized = project.dictize() # Project object else: project_sanitized = project # dict object owner_sanitized = cached_users.get_user_summary(owner.name) else: # anonymous or different owner if request.headers.get('Content-Type') == 'application/json': if isinstance(project, Project): project_sanitized = project.to_public_json() # Project object else: project_sanitized = Project().to_public_json(project) # dict object else: # HTML # Also dictize for HTML to have same output as authenticated user (see above) if isinstance(project, Project): project_sanitized = project.dictize() # Project object else: project_sanitized = project # dict object owner_sanitized = cached_users.public_get_user_summary(owner.name) return project_sanitized, owner_sanitized
def setup_babel(app): """Return babel handler.""" babel.init_app(app) @babel.localeselector def _get_locale(): locales = [l[0] for l in app.config.get('LOCALES')] if current_user.is_authenticated(): lang = current_user.locale else: lang = request.cookies.get('language') if (lang is None or lang == '' or lang.lower() not in locales): lang = request.accept_languages.best_match(locales) if (lang is None or lang == '' or lang.lower() not in locales): lang = app.config.get('DEFAULT_LOCALE') or 'en' if request.headers.get('Content-Type') == 'application/json': lang = 'en' return lang.lower() return babel
def detail(book_id): the_book = Book.query.get_or_404(book_id) if the_book.hidden and (not current_user.is_authenticated or not current_user.is_administrator()): abort(404) show = request.args.get('show', 0, type=int) page = request.args.get('page', 1, type=int) form = CommentForm() if show in (1, 2): pagination = the_book.logs.filter_by(returned=show - 1) \ .order_by(Log.borrow_timestamp.desc()).paginate(page, per_page=5) else: pagination = the_book.comments.filter_by(deleted=0) \ .order_by(Comment.edit_timestamp.desc()).paginate(page, per_page=5) data = pagination.items return render_template("book_detail.html", book=the_book, data=data, pagination=pagination, form=form, title=the_book.title)
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['FLASKY_POSTS_PER_PAGE'], error_out=False) posts = pagination.items return render_template('index.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination)
def reset_password(token): if current_user.is_authenticated: return redirect('main.index') form = ResetPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is None: flash('????!??????') form.email.data = '' return redirect(url_for('auth.reset_password')) else: if user.reset_password(token, form.password.data): flash('?????????????') else: flash('?????????????') return redirect(url_for('auth.request_reset_password')) return redirect(url_for('auth.login')) return render_template('auth/reset_password.html', form=form) # ??????
def admin_required(func): ''' ???admin????????route example:: @app.route('/post') @admin_required def post(): pass ''' @wraps(func) def decorated_view(*args, **kwargs): if not current_user.is_authenticated: return current_app.login_manager.unauthorized() if not current_user.admin: abort(403) return func(*args, **kwargs) return decorated_view
def _ajax_login_required(func): ''' Verify the user if request is ajax. ''' def verify_login(*args, **kwargs): if login_manager._login_disabled: return func(*args, **kwargs) elif not current_user.is_authenticated(): context = { 'status': 'fail', 'msg': u'?????' } return make_json_response(context) else: return func(*args, **kwargs) return verify_login
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['FLASKY_POSTS_PER_PAGE'], error_out = False) posts = pagination.items return render_template('index.html', form = form, posts = posts, show_followed = show_followed, pagination = pagination)
def test_correct_login(self): with self.client: response = self.login("admin", "adminpassword") # 200 (OK) HTTP status code self.assert200(response) # check if user is authenticated self.assertTrue(current_user.is_authenticated()) # check if user is not anonymous self.assertFalse(current_user.is_anonymous()) # get user id self.assertEqual(current_user.get_id(), "1") # test user redirects to the main page self.assertIn('/posts', request.url) # Ensure alert is shown after logging in # Binary format because str() object doesn't support Buffer api self.assertIn(b'you were just logged in', response.data)
def require(self, *needed_permissions): """Make view function only for autorized users accessible. This is a decorator generator for flask view functions, It checks if the current session has a authenticated user and if the user is in a group that has _one_ of the needed permissions. The permissions are strings that are given as positional arguments to the decorator generator. """ def decorator(fn): if len(needed_permissions): endpoint = bake_endpoint(self.blueprint, fn) self._restrictions[endpoint] = tuple(needed_permissions) @wraps(fn) def nufun(*args, **kwargs): if not current_user.is_authenticated(): return current_app.login_manager.unauthorized() if self._current_has_access(needed_permissions): return fn(*args, **kwargs) abort(401) return nufun return decorator
def initiate(): """ 1. step Initiate app installation """ args = request.args # get shop url from args shop_url = args.get('shop') # TODO: validate HMAC, so we know that request really is from shopify if not current_user.is_authenticated: return redirect(url_for('main.signup', next=url_join(request.host_url, url_for('shopify.initiate', shop=shop_url)))) api_key = current_app.config['SHOPIFY_API_KEY'] secret = current_app.config['SHOPIFY_API_SECRET'] url = get_permission_url(shop_url, api_key, secret) return redirect(url)
def login(): """ show log in page or log in a User :return: the log in page or redirect to the index page """ # don't allow login when User is logged in already if current_user.is_authenticated: return redirect(url_for("mod_index.index")) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data, password=hashlib.sha256(form.password.data.encode("utf8")).hexdigest()).first() if user is not None: login_user(user, remember=form.remember.data) return redirect(request.args.get("next") or url_for("mod_index.index")) else: flash(_("Invalid Username or Password. Please try again!"), "error") return render_template("auth/login.html", form=form, title=_("Login"))
def set_language(language): """ set a new language as active for the currently logged in User :param language: the new language :return: redirect to referrer """ if language in ("de", "en"): # only store language in database when the User is logged in if current_user.is_authenticated: current_user.language = language db.session.commit() session["language"] = language return redirect(request.referrer or url_for("mod_index.index")) else: abort(404)
def index(): form = PostForm() if form.validate_on_submit() and current_user.can(Permission.WRITE_ARTICLES): #?????????????? post = Post(body=form.body.data, author=current_user._get_current_object()) #_get_current_object()??????? db.session.add(post) return redirect(url_for('.index')) #posts = Post.query.order_by(Post.timestamp.desc()).all() #???????????? 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['FLASKY_POSTS_PER_PAGE'], error_out=False) #?????????? posts = pagination.items return render_template('index.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination) #?????????
def admin_login_required(method): def is_admin(user): if isinstance(user.is_admin, bool): return user.is_admin else: return user.is_admin() @functools.wraps(method) def wrapper(*args, **kwargs): if not current_user.is_authenticated: flash("This section is for logged in users only.", 'warning') return redirect(url_for('redberry.home')) if not hasattr(current_user, 'is_admin'): flash("Redberry expects your user instance to implement an `is_admin` boolean attribute " "or an `is_admin()` method.", 'warning') return redirect(url_for('redberry.home')) if not is_admin(current_user): flash("This section is for admin users only.", 'warning') return redirect(url_for('redberry.home')) return method(*args, **kwargs) return wrapper ############ # CMS ROUTES ############
def api_context(self, all_arg, **filters): if current_user.is_authenticated(): filters['owner_id'] = current_user.id if filters.get('owner_id') and all_arg == '1': del filters['owner_id'] return filters
def _select_attributes(self, data): if current_user.is_anonymous(): data = self._filter_private_data(data) return data if (current_user.is_authenticated and (current_user.id == data['owner_id'] or current_user.admin)): return data else: data = self._filter_private_data(data) return data
def _select_attributes(self, user_data): if current_user.is_authenticated() and current_user.admin: tmp = User().to_public_json(user_data) tmp['id'] = user_data['id'] tmp['email_addr'] = user_data['email_addr'] return tmp else: privacy = self._is_user_private(user_data) for attribute in user_data.keys(): self._remove_attribute_if_private(attribute, user_data, privacy) return user_data
def _is_requester_admin(self): return current_user.is_authenticated() and current_user.admin
def home(): """Render home page with the cached projects and users.""" page = 1 per_page = current_app.config.get('APPS_PER_PAGE') if per_page is None: # pragma: no cover per_page = 5 d = {'top_projects': cached_projects.get_top(), 'top_users': None} # Get all the categories with projects categories = cached_cat.get_used() d['categories'] = categories d['categories_projects'] = {} for c in categories: tmp_projects = cached_projects.get(c['short_name'], page, per_page) d['categories_projects'][c['short_name']] = rank(tmp_projects) # Add featured tmp_projects = cached_projects.get_featured('featured', page, per_page) if len(tmp_projects) > 0: featured = Category(name='Featured', short_name='featured') d['categories'].insert(0, featured) d['categories_projects']['featured'] = rank(tmp_projects) if (current_app.config['ENFORCE_PRIVACY'] and current_user.is_authenticated()): if current_user.admin: d['top_users'] = cached_users.get_leaderboard(10) if not current_app.config['ENFORCE_PRIVACY']: d['top_users'] = cached_users.get_leaderboard(10) response = dict(template='/home/index.html', **d) return handle_content_type(response)
def get_user_id_or_ip(): """Return the id of the current user if is authenticated. Otherwise returns its IP address (defaults to 127.0.0.1). """ user_id = current_user.id if current_user.is_authenticated() else None user_ip = request.remote_addr or "127.0.0.1" \ if current_user.is_anonymous() else None return dict(user_id=user_id, user_ip=user_ip)
def auth_func(*args, **kw): if not current_user.is_authenticated(): raise ProcessingException(description='Not authenticated!', code=401)
def is_accessible(self): """Setup the access permission for CustomModelView.""" # callable function `User.is_authenticated()`. # FIXME(JMilkFan): # Using function is_authenticated(), # Can return the value of current_user.is_authenticated() # when user was logged in. return current_user.is_authenticated and\ admin_permission.can()
def is_accessible(self): """Setup the access permission for CustomFileAdmin.""" # callable function `User.is_authenticated()`. return current_user.is_authenticated and\ admin_permission.can()
def before_request(): if current_user.is_authenticated: current_user.ping() # ??????????? if not current_user.confirmed \ and request.endpoint[:5] != 'auth.' \ and request.endpoint != 'static': return redirect(url_for('auth.unconfirmed')) # ???????
def request_reset_password(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = ResetPasswordRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is None: flash('???????????????????') return redirect(url_for('auth.login')) token = user.generate_reset_password_token() send_mail(form.email.data, '??????', 'auth/email/reset_password_confirm', user=user, token=token) flash('????????????????????????') return render_template('auth/reset_password_request.html', form=form) # ????
def post(id): post = Post.query.get_or_404(id) comments = Comment.query.order_by(Comment.timestamp.desc()) if current_user.is_authenticated: form = CommentForm() author = current_user._get_current_object() else: form = VisitorCommentForm() author = User(username=form.name.data) if form.validate_on_submit(): comment = Comment(body=form.body.data, post=post, author=author) db.session.add(comment) db.session.commit() flash('??????!') return redirect(url_for('.post', id=post.id, page=-1)) if post is None: abort(404) else: post.view_count += 1 db.session.add(post) db.session.commit() page = request.args.get('page', 1, type=int) if page == -1: page = (post.comments.count() - 1) / current_app.config['COMMENT_PER_PAGE'] + 1 pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(page, per_page=current_app.config['COMMENT_PER_PAGE'], error_out=False) comments=pagination.items return render_template('post.html', post=post, form=form, comments=comments, pagination=pagination) # ????
def before_request(): if current_user.is_authenticated and not current_user.confirmed and request.endpoint[:5] != 'auth.': return redirect(url_for('auth.unconfirmed'))
def before_request(): if current_user.is_authenticated: current_user.ping() if not current_user.confirmed and request.endpoint[:5] != 'auth.': return redirect(url_for('auth.unconfirmed'))
def is_accessible(self): return current_user.is_authenticated() and admin_permission.can()
def test_sign_up_success_doesnt_authenticate_user(self): with self.app.test_client() as client: client.post(url_for('sign_up'), data=self.data) self.assertFalse(current_user.is_authenticated)
def test_sign_in_success_puts_user_email_in_session(self): with self.app.test_client() as client: client.post(url_for('sign_in'), data=self.valid_data) self.assertEquals(self.email, session.get('user_email')) self.assertFalse(current_user.is_authenticated)
def test_sign_in_failure_doesnt_authenticate(self): with self.app.test_client() as client: client.post(url_for('sign_in'), data=self.invalid_data) self.assertFalse(current_user.is_authenticated)
def test_logout_kills_session(self): with self.app.test_client() as client: with client.session_transaction() as current_session: current_session['user_email'] = self.email current_session['confirmation_code'] = '1234' client.get(url_for('logout')) self.assertNotIn('confirmation_code', session) self.assertNotIn('user_email', session) self.assertFalse(current_user.is_authenticated)
def test_confirmation_page_authenticates_on_success(self): with self.app.test_client() as client: with client.session_transaction() as current_session: current_session['user_email'] = self.email current_session['verification_code'] = '1234' client.post(url_for('confirmation'), data={'verification_code': '1234'}) self.assertTrue(current_user.is_authenticated)
def _is_blogger(blogger_permission): authenticated = current_user.is_authenticated() if \ callable(current_user.is_authenticated) \ else current_user.is_authenticated is_blogger = authenticated and \ blogger_permission.require().can() return is_blogger
def studies_summary(): studies = OrderedDict( sorted(study_config.items(), key=lambda t: t[1]["publication"])) for k, v in studies.iteritems(): # Don't show stidies that are not published yet ;-) if not v["public"]: if current_user.is_authenticated and current_user.is_sudo(): continue del studies[k] return studies
def index(): """Return a friendly HTTP greeting.""" if current_user.is_authenticated: # If authenticated - push into app, not homepage if current_user.is_sudo(): # Staffjoy user. Go to Euler. return redirect(url_for("euler.index")) admins = current_user.admin_of.all() if len(admins) > 0: # Go to manage app return redirect( url_for("manager.manager_app", org_id=admins[0].id)) memberships = current_user.memberships() if len(memberships) > 0: # Go to planner m = memberships[0] return redirect( url_for( "myschedules.myschedules_app", org_id=m.get("organization_id"), location_id=m.get("location_id"), role_id=m.get("role_id"), user_id=current_user.id)) # Nothing left - default to portal return redirect(url_for("auth.portal")) if is_native(): return redirect(url_for("auth.native_login")) return render_template("homepage.html")
def sign_up(): """ Lead capture page! """ if current_user.is_authenticated: return redirect(url_for("auth.portal")) return redirect(url_for("auth.free_trial"))
def before_request(): if current_user.is_authenticated: current_user.ping() if not current_user.confirmed \ and request.endpoint[:5] != 'auth.' \ and request.endpoint != 'static': return redirect(url_for('auth.unconfirmed'))
def reader(pathname): article = Article.query.filter_by(pathname=pathname).first() if not article: return abort(404) if article.access == "private" and (not current_user.is_authenticated or \ (current_user.is_authenticated and current_user.id != article.user.id)): return abort(404) return render_template("article/reader.html", article=article)