Python flask_login.current_user.is_anonymous() Examples
The following are 30
code examples of flask_login.current_user.is_anonymous().
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: server.py From pheweb with GNU Affero General Public License v3.0 | 6 votes |
def check_auth(func): """ This decorator for routes checks that the user is authorized (or that no login is required). If they haven't, their intended destination is stored and they're sent to get authorized. It has to be placed AFTER @bp.route() so that it can capture `request.path`. """ if 'login' not in conf: return func # inspired by <https://flask-login.readthedocs.org/en/latest/_modules/flask_login.html#login_required> @functools.wraps(func) def decorated_view(*args, **kwargs): if current_user.is_anonymous: print('unauthorized user visited {!r}'.format(request.path)) session['original_destination'] = request.path return redirect(url_for('.get_authorized')) print('{} visited {!r}'.format(current_user.email, request.path)) if 'whitelist' in conf.login: assert current_user.email.lower() in conf.login['whitelist'], current_user return func(*args, **kwargs) return decorated_view
Example #2
Source File: __init__.py From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 | 6 votes |
def on_api_command(self, command, data): """Route API requests to their implementations.""" if current_user.is_anonymous(): return "Insufficient rights", 403 self._logger.debug("API command received: %s", data) if (command == "deleteExcludeRegion"): return self._handleDeleteExcludeRegion(data.get("id")) else: regionType = data.get("type") if (regionType == "RectangularRegion"): region = RectangularRegion(**data) elif (regionType == "CircularRegion"): region = CircularRegion(**data) else: return "Invalid type", 400 if (command == "addExcludeRegion"): return self._handleAddExcludeRegion(region) elif (command == "updateExcludeRegion"): return self._handleUpdateExcludeRegion(region) return "Invalid command", 400
Example #3
Source File: oauth.py From evesrp with BSD 2-Clause "Simplified" License | 6 votes |
def session(self): if not hasattr(self, '_oauth_session'): if not current_user.is_anonymous: kwargs = { 'token': current_user.token, } if self.refresh_url is not None: kwargs['auto_refresh_url'] = self.refresh_url kwargs['token_updater'] = token_saver kwargs['auto_refresh_kwargs'] = { 'client_id': self.client_id, 'client_secret': self.client_secret, } current_app.logger.debug(u"Creating a new OAuth2Session for " u"'{}'".format(current_user)) self._oauth_session = OAuth2Session(self.client_id, **kwargs) return self._oauth_session
Example #4
Source File: views.py From dribdat with MIT License | 6 votes |
def project_edit(project_id): project = Project.query.filter_by(id=project_id).first_or_404() event = project.event starred = IsProjectStarred(project, current_user) allow_edit = starred or (not current_user.is_anonymous and current_user.is_admin) if not allow_edit: flash('You do not have access to edit this project.', 'warning') return project_action(project_id, None) form = ProjectForm(obj=project, next=request.args.get('next')) form.category_id.choices = [(c.id, c.name) for c in project.categories_all()] form.category_id.choices.insert(0, (-1, '')) if form.validate_on_submit(): del form.id form.populate_obj(project) project.update() db.session.add(project) db.session.commit() cache.clear() flash('Project updated.', 'success') project_action(project_id, 'update', False) return redirect(url_for('public.project', project_id=project.id)) return render_template('public/projectedit.html', current_event=event, project=project, form=form)
Example #5
Source File: views.py From dribdat with MIT License | 6 votes |
def project_post(project_id): project = Project.query.filter_by(id=project_id).first_or_404() event = project.event starred = IsProjectStarred(project, current_user) allow_edit = starred or (not current_user.is_anonymous and current_user.is_admin) if not allow_edit: flash('You do not have access to edit this project.', 'warning') return project_action(project_id, None) form = ProjectPost(obj=project, next=request.args.get('next')) form.progress.choices = projectProgressList(event.has_started or event.has_finished) if not form.note.data: form.note.data = "---\n`%s` " % datetime.utcnow().strftime("%d.%m.%Y %H:%M") if form.validate_on_submit(): del form.id form.populate_obj(project) project.longtext += "\n\n" + form.note.data project.update() db.session.add(project) db.session.commit() cache.clear() flash('Project updated.', 'success') project_action(project_id, 'update', False) return redirect(url_for('public.project', project_id=project.id)) return render_template('public/projectpost.html', current_event=event, project=project, form=form)
Example #6
Source File: views.py From dribdat with MIT License | 6 votes |
def project_action(project_id, of_type, as_view=True, then_redirect=False): project = Project.query.filter_by(id=project_id).first_or_404() event = project.event if of_type is not None: ProjectActivity(project, of_type, current_user) if not as_view: return True starred = IsProjectStarred(project, current_user) allow_edit = starred or (not current_user.is_anonymous and current_user.is_admin) allow_edit = allow_edit and not event.lock_editing project_stars = GetProjectTeam(project) latest_activity = project.latest_activity() if then_redirect: return redirect(url_for('public.project', project_id=project.id)) return render_template('public/project.html', current_event=event, project=project, project_starred=starred, project_stars=project_stars, allow_edit=allow_edit, latest_activity=latest_activity)
Example #7
Source File: __init__.py From AstroBox with GNU Affero General Public License v3.0 | 6 votes |
def getWsToken(): publicKey = None userLogged = settings().get(["cloudSlicer", "loggedUser"]) if userLogged: if current_user.is_anonymous or current_user.get_name() != userLogged: abort(401, "Unauthorized Access") user = userManager.findUser(userLogged) if user: publicKey = user.publicKey else: abort(403, 'Invalid Logged User') return Response( json.dumps({ 'ws_token': create_ws_token(publicKey) }), headers= { 'Access-Control-Allow-Origin': '*' } if settings().getBoolean(['api', 'allowCrossOrigin']) else None )
Example #8
Source File: backup.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get(self, server=None, name=None): """Tells if a 'backup' file is present **GET** method provided by the webservice. :param server: Which server to collect data from when in multi-agent mode :type server: str :param name: The client we are working on :type name: str :returns: True if the file is found """ if not name: self.abort(400, 'Missing options') # Manage ACL if not current_user.is_anonymous and \ not current_user.acl.is_admin() and \ not current_user.acl.is_client_allowed(name, server): self.abort(403, 'You are not allowed to access this client') try: return {'is_server_backup': bui.client.is_server_backup(name, server)} except BUIserverException as e: self.abort(500, str(e))
Example #9
Source File: prefs.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 6 votes |
def delete(self): """Make a client/server visible again **DELETE** method provided by the webservice. """ args = self.parser.parse_args() if bui.config['WITH_SQL'] and not bui.config['BUI_DEMO'] and not current_user.is_anonymous: from ..ext.sql import db from ..models import Hidden hide = Hidden.query.filter_by(client=(args.get('client') or None), server=(args.get('server') or None), user=current_user.name).first() if hide: db.session.delete(hide) try: db.session.commit() except: # pragma: no cover db.session.rollback() self.abort(500, 'Internal server error') return None, 204
Example #10
Source File: settings.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 6 votes |
def post(self, server=None, client=None, conf=None): """Saves a given client configuration""" if not current_user.is_anonymous and \ current_user.acl.is_moderator() and \ not current_user.acl.is_client_rw(client, server): self.abort(403, 'You don\'t have rights on this server') args = self.parser_post.parse_args() template = args.get('template', False) statictemplate = args.get('statictemplate', False) noti = bui.client.store_conf_cli(request.form, client, conf, template, statictemplate, server) # clear cache cache.clear() # clear client-side cache through the _extra META variable try: _extra = session.get('_extra', g.now) _extra = int(_extra) except ValueError: _extra = 0 session['_extra'] = '{}'.format(_extra + 1) bui.audit.logger.info(f'updated client configuration {client} ({conf})', server=server) return {'notif': noti}
Example #11
Source File: routes.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 6 votes |
def settings(server=None, conf=None): # Only the admin can edit the configuration if not current_user.is_anonymous and not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): abort(403) if not conf: try: conf = quote(request.args.get('conf'), safe='') if conf: return redirect(url_for('.settings', server=server, conf=conf)) except: pass server = server or request.args.get('serverName') return render_template( 'settings.html', settings=True, is_admin=current_user.acl.is_admin(), is_moderator=current_user.acl.is_moderator(), server=server, conf=conf, ng_controller='ConfigCtrl' )
Example #12
Source File: views.py From realms-wiki with GNU General Public License v2.0 | 6 votes |
def revert(): cname = to_canonical(request.form.get('name')) commit = request.form.get('commit') message = request.form.get('message', "Reverting %s" % cname) if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous: return dict(error=True, message="Anonymous posting not allowed"), 403 if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message="Page is locked"), 403 try: sha = g.current_wiki.get_page(cname).revert(commit, message=message, username=current_user.username, email=current_user.email) except PageNotFound as e: return dict(error=True, message=e.message), 404 if sha: flash("Page reverted") return dict(sha=sha.decode())
Example #13
Source File: views.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def reset_password_request(): """Respond to existing user's request to reset their password.""" badge_list = [] if not current_user.is_anonymous: return redirect(url_for('main.index')) form = RequestResetPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: token = user.generate_password_reset_token() reset_link = url_for( 'account.reset_password', token=token, _external=True) send_email( recipient=user.email, subject='Reset Your Password', template='account/email/reset_password', user=user, reset_link=reset_link, next=request.args.get('next')) flash( 'A password reset link has been sent to {}.'.format( form.email.data), 'warning') return redirect(url_for('account.login')) return render_template( 'account/reset_password.html', form=form, badge_list=badge_list)
Example #14
Source File: __init__.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_acl(func): """Custom decorator to check if the ACL are in use or not""" @wraps(func) def decorated_view(*args, **kwargs): if request.method in EXEMPT_METHODS: # pragma: no cover return func(*args, **kwargs) # 'func' is a Flask.view.MethodView so we have access to some special # params cls = func.view_class login_required = getattr(cls, 'login_required', True) if (bui.auth != 'none' and login_required and not bui.config.get('LOGIN_DISABLED', False)): if current_user.is_anonymous: abort(403) return func(*args, **kwargs) return decorated_view
Example #15
Source File: views.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def reset_password(token): """Reset an existing user's password.""" badge_list = [] if not current_user.is_anonymous: return redirect(url_for('main.index')) form = ResetPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is None: flash('Invalid email address.', 'form-error') return redirect(url_for('main.index')) if user.reset_password(token, form.new_password.data): flash('Your password has been updated.', 'form-success') return redirect(url_for('account.login')) else: flash('The password reset link is invalid or has expired.', 'form-error') return redirect(url_for('main.index')) return render_template( 'account/reset_password.html', form=form, badge_list=badge_list)
Example #16
Source File: opds.py From calibre-web with GNU General Public License v3.0 | 6 votes |
def feed_shelf(book_id): off = request.args.get("offset") or 0 if current_user.is_anonymous: shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.is_public == 1, ub.Shelf.id == book_id).first() else: shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id), ub.Shelf.id == book_id), and_(ub.Shelf.is_public == 1, ub.Shelf.id == book_id))).first() result = list() # user is allowed to access shelf if shelf: books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == book_id).order_by( ub.BookShelf.order.asc()).all() for book in books_in_shelf: cur_book = calibre_db.get_book(book.book_id) result.append(cur_book) pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(result)) return render_xml_template('feed.xml', entries=result, pagination=pagination)
Example #17
Source File: routes.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def admin_authentication(user): # Only the admin can access this page if not current_user.is_anonymous and not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): abort(403) backend = request.args.get('backend') if not backend: abort(400) return render_template('admin/authentication.html', admin=True, authentication=True, user=user, backend=backend, ng_controller='AdminCtrl')
Example #18
Source File: routes.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def admin_backend(backend): # Only the admin can access this page if not current_user.is_anonymous and not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): abort(403) return render_template('admin/backend.html', admin=True, onebackend=True, backend=backend, ng_controller='AdminCtrl')
Example #19
Source File: views.py From Flashcards with MIT License | 5 votes |
def password_reset(token): if not current_user.is_anonymous: return redirect(url_for('main.index')) form = PasswordResetForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is None: return redirect(url_for('main.index')) if user.reset_password(token, form.password.data): flash('Your password has been updated.') return redirect(url_for('auth.login')) else: flash('Could not Reset Password') return redirect(url_for('main.index')) return render_template('auth/reset_password.html', form=form)
Example #20
Source File: admin.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def delete(self, id=None): """Delete a given session Note: ``id`` is mandatory """ if not id: self.abort(400, 'Missing id') user = getattr(current_user, 'name', None) if not user: self.abort(404, 'User not found') store = session_manager.get_session_by_id(str(id)) if not store: self.abort('Session not found') if store.user != user: if not current_user.is_anonymous and \ not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): self.abort(403, 'Insufficient permissions') if current_user.acl.is_moderator() and \ meta_grants.is_admin(store.user): self.abort(403, 'Insufficient permissions') if session_manager.invalidate_session_by_id(store.uuid): session_manager.delete_session_by_id(store.uuid) bui.audit.logger.info(f'removed session {store.id} of {store.user}') return [NOTIF_OK, 'Session {} successfully revoked'.format(id)], 201
Example #21
Source File: clients.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _check_acl(self, server): # Manage ACL if (not bui.config['STANDALONE'] and not current_user.is_anonymous and (not current_user.acl.is_admin() and not current_user.acl.is_server_allowed(server))): self.abort(403, 'Sorry, you don\'t have any rights on this server')
Example #22
Source File: routes.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def admin_sessions(user): # Only the admin can access this page if not current_user.is_anonymous and not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): abort(403) return render_template('admin/sessions.html', admin=True, sessions=True, user=user, ng_controller='AdminCtrl')
Example #23
Source File: routes.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def admin_backends(): # Only the admin can access this page if not current_user.is_anonymous and not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): abort(403) return render_template('admin-backends.html', admin=True, backends=True, ng_controller='AdminCtrl')
Example #24
Source File: routes.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def admin_authorizations(): # Only the admin can access this page if not current_user.is_anonymous and not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): abort(403) return render_template('admin-authorizations.html', admin=True, authorizations=True, ng_controller='AdminCtrl')
Example #25
Source File: routes.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def admin_authentications(): # Only the admin can access this page if not current_user.is_anonymous and not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): abort(403) return render_template('admin-authentications.html', admin=True, authentications=True, ng_controller='AdminCtrl')
Example #26
Source File: routes.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cli_settings(server=None, client=None, conf=None): # Only the admin can edit the configuration if not current_user.is_anonymous and not current_user.acl.is_admin() and \ not current_user.acl.is_moderator(): abort(403) if not conf: try: conf = quote(request.args.get('conf'), safe='') if conf: return redirect( url_for( '.cli_settings', server=server, client=client, conf=conf ) ) except: pass client = client or request.args.get('client') server = server or request.args.get('serverName') template = request.args.get('template') or False statictemplate = request.args.get('statictemplate') or False return render_template( 'settings.html', settings=True, client_mode=True, template=template, statictemplate=statictemplate, client=client, server=server, conf=conf, ng_controller='ConfigCtrl' )
Example #27
Source File: i18n.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_locale(): locale = None if current_user and not current_user.is_anonymous: locale = getattr(current_user, 'language', None) elif 'language' in session: locale = session.get('language', None) if locale not in LANGUAGES: locale = None return locale or request.accept_languages.best_match(config['LANGUAGES'].keys())
Example #28
Source File: cookie.py From quay with Apache License 2.0 | 5 votes |
def validate_session_cookie(auth_header_unusued=None): """ Attempts to load a user from a session cookie. """ if current_user.is_anonymous: return ValidateResult(AuthKind.cookie, missing=True) try: # Attempt to parse the user uuid to make sure the cookie has the right value type UUID(current_user.get_id()) except ValueError: logger.debug("Got non-UUID for session cookie user: %s", current_user.get_id()) return ValidateResult(AuthKind.cookie, error_message="Invalid session cookie format") logger.debug("Loading user from cookie: %s", current_user.get_id()) db_user = current_user.db_user() if db_user is None: return ValidateResult(AuthKind.cookie, error_message="Could not find matching user") # Don't allow disabled users to login. if not db_user.enabled: logger.debug("User %s in session cookie is disabled", db_user.username) return ValidateResult(AuthKind.cookie, error_message="User account is disabled") # Don't allow organizations to "login". if db_user.organization: logger.debug("User %s in session cookie is in-fact organization", db_user.username) return ValidateResult(AuthKind.cookie, error_message="Cannot login to organization") return ValidateResult(AuthKind.cookie, user=db_user)
Example #29
Source File: views.py From realms-wiki with GNU General Public License v2.0 | 5 votes |
def compare(name, fsha, dots, lsha): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous: return current_app.login_manager.unauthorized() diff = g.current_wiki.get_page(name, sha=lsha).compare(fsha) return render_template('wiki/compare.html', name=name, diff=diff, old=fsha, new=lsha)
Example #30
Source File: views.py From realms-wiki with GNU General Public License v2.0 | 5 votes |
def commit(name, sha): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous: return current_app.login_manager.unauthorized() cname = to_canonical(name) data = g.current_wiki.get_page(cname, sha=sha.decode()) if not data: abort(404) partials = _partials(data.imports, sha=sha.decode()) return render_template('wiki/page.html', name=name, page=data, commit=sha, partials=partials)