Python flask_login.current_user.username() Examples
The following are 30
code examples of flask_login.current_user.username().
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 | 7 votes |
def portfolio_main(): transactions = Trades.query.filter_by(user_id=current_user.username) if transactions.count() == 0: return redirect(url_for("main.get_started")) # For now pass only static positions, will update prices and other # data through javascript after loaded. This improves load time # and refresh speed. # Get positions and prepare df for delivery df = positions() df.set_index('trade_asset_ticker', inplace=True) df = df[df['is_currency'] == 0].sort_index(ascending=True) df = df.to_dict(orient='index') if df is None: return redirect(url_for("main.get_started")) return render_template("portfolio.html", title="Portfolio Dashboard", portfolio_data=df)
Example #2
Source File: routes.py From thewarden with MIT License | 6 votes |
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 #3
Source File: decorators.py From open_dnsdb with Apache License 2.0 | 6 votes |
def add_web_opration_log(op_type, get_op_info): def _inner(func): @wraps(func) def _wrapper(*args, **kwargs): rtx_id = current_user.username try: ret = func(*args, **kwargs) op_domain, op_before, op_after = get_op_info(result=ret, *args, **kwargs) if op_domain is None: op_domain = op_type OperationLogDal.insert_operation_log_with_dict(rtx_id, op_domain, op_type, op_before, op_after, 'ok') except Exception as ex: raise return ret return _wrapper return _inner
Example #4
Source File: decorators.py From open_dnsdb with Apache License 2.0 | 6 votes |
def predicate_params(param_meta=None, need_username=False): _param_meta = [] if param_meta is None else param_meta def _inner(func): @wraps(func) def _wrapper(*args, **kwargs): params = ParamValidator(_param_meta) kwargs.update(params) if need_username: kwargs['username'] = current_user.username return func(*args, **kwargs) return _wrapper return _inner
Example #5
Source File: views.py From circleci-demo-python-flask with MIT License | 6 votes |
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user)
Example #6
Source File: forms.py From thewarden with MIT License | 6 votes |
def validate_account(self, account): # Only accept accounts already registered in trades or accountinfo found = False tradeaccounts = Trades.query.filter_by(user_id=current_user.username).group_by( Trades.trade_account ) accounts = AccountInfo.query.filter_by(user_id=current_user.username).group_by( AccountInfo.account_longname ) for item in tradeaccounts: if account.data.upper() in item.trade_account.upper(): found = True for item in accounts: if account.data.upper() in item.account_longname.upper(): found = True if not found: raise ValidationError( "Choose an existing account. If account is not registered, include first." )
Example #7
Source File: routes.py From thewarden with MIT License | 6 votes |
def delete_baccount(id): # type = account or address account = None type = request.args.get("type") if type == "account": account = AccountInfo.query.filter_by( user_id=current_user.username).filter_by(account_id=id) if type == "address": account = BitcoinAddresses.query.filter_by( user_id=current_user.username).filter_by(address_id=id) if (account is None) or (account.count() == 0): flash(f"{type.capitalize()} id: {id} not found. Nothing done.", "warning") return redirect(url_for("node.bitcoin_monitor")) if account.first().user_id != current_user.username: abort(403) account.delete() db.session.commit() flash(f"{type.capitalize()} deleted", "danger") return redirect(url_for("node.bitcoin_monitor"))
Example #8
Source File: generic.py From yeti with Apache License 2.0 | 6 votes |
def edit(self, id): obj = self.klass.objects.get(id=id) #ToDo Group admins support if hasattr(obj, 'created_by'): if current_user.username != obj.created_by and not current_user.has_role('admin'): abort(403) if request.method == "POST": return self.handle_form(id=id) form_class = obj.__class__.get_form() form = form_class(obj=obj) return render_template( "{}/edit.html".format(self.klass.__name__.lower()), form=form, obj_type=self.klass.__name__, obj=obj, groups=get_user_groups())
Example #9
Source File: routes.py From AUCR with GNU General Public License v3.0 | 6 votes |
def send_message(recipient): """AUCR auth plugin function sends a message to an input recipient.""" recipient_user = User.query.filter_by(username=recipient).first_or_404() form = MessageForm() if form.validate_on_submit(): msg = Message(author=current_user, recipient=recipient_user, body=form.message.data) db.session.add(msg) db.session.commit() recipient_user.add_notification('unread_message_count', recipient_user.new_messages()) db.session.commit() flash(_('Your message has been sent.')) return redirect(url_for('auth.user', username=recipient)) else: for error in form.errors: flash(str(form.errors[error][0]), 'error') return render_template('send_message.html', form=form, recipient=recipient)
Example #10
Source File: routes.py From AUCR with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: routes.py From thewarden with MIT License | 6 votes |
def delalltrades(): transactions = Trades.query.filter_by( user_id=current_user.username).order_by(Trades.trade_date) if transactions.count() == 0: return render_template("empty.html") if request.method == "GET": Trades.query.filter_by(user_id=current_user.username).delete() db.session.commit() regenerate_nav() flash("ALL TRANSACTIONS WERE DELETED", "danger") return redirect(url_for("main.home")) else: return redirect(url_for("main.home"))
Example #12
Source File: view_isp_acl.py From open_dnsdb with Apache License 2.0 | 6 votes |
def add_acl_subnet(subnet, acl, username): if not ViewIsps.query.filter_by(acl_name=acl).first(): raise BadParam('acl not in database: %s' % acl, msg_ch=u'ACL在dnsdb中无记录') subnet, is_ipv6, start_ip, end_ip = format_subnet(subnet) q1 = (ViewAclSubnet.query.filter_by(origin_acl=acl, is_ipv6=is_ipv6). filter(ViewAclSubnet.start_ip <= start_ip).filter(ViewAclSubnet.end_ip >= start_ip).first()) q2 = (ViewAclSubnet.query.filter_by(origin_acl=acl). filter(ViewAclSubnet.start_ip <= end_ip).filter(ViewAclSubnet.end_ip >= end_ip).first()) if q1 or q2: raise BadParam('subnet overlap with subnet in this acl', msg_ch=u'与运营商中已有网段交叉') with db.session.begin(subtransactions=True): db.session.add(ViewAclSubnet( subnet=subnet, start_ip=start_ip, end_ip=end_ip, origin_acl=acl, now_acl=acl, update_user=username, is_ipv6=is_ipv6 )) start_acl_deploy_job(username, [acl])
Example #13
Source File: utils.py From thewarden with MIT License | 6 votes |
def regenerate_nav(): # re-generates the NAV on the background - delete First # the local NAV file so it's not used. # Check if there any trades in the database. If not, skip. transactions = Trades.query.filter_by(user_id=current_user.username) if transactions.count() == 0: return print("Regenerating NAV. Please wait...") # Delete all pricing history filename = os.path.join(current_path(), 'thewarden/pricing_engine/pricing_data/*.*') aa_files = glob.glob(filename) [os.remove(x) for x in aa_files] filename = os.path.join(current_path(), 'thewarden/nav_data/*.*') nav_files = glob.glob(filename) [os.remove(x) for x in nav_files] # Clear cache MWT()._caches = {} MWT()._timeouts = {} generatenav(current_user.username, force=True) logging.info("Change to database - generated new NAV")
Example #14
Source File: investigation.py From yeti with Apache License 2.0 | 6 votes |
def run(self, target): results = ImportResults(import_method=self, status='pending') results.investigation = Investigation(created_by=current_user.username) if isinstance(target, AttachedFile): results.investigation.import_document = target target = target.filepath else: results.investigation.import_url = target results.investigation.save() results.save() celery_app.send_task( "core.investigation.import_task", [str(results.id), target]) return results
Example #15
Source File: app.py From fbctf-2019-challenges with MIT License | 6 votes |
def get_flag(): if not current_user.is_authenticated: return render_template("admin.html", text="You have to login first.") user_cookie_present = request.cookies.get("user") try: user = unsign(user_cookie_present) except Exception: return render_template("admin.html", text="I do not recognise this user.") if user != "admin": return render_template( "admin.html", text="You do not seem to be an admin, {}!".format(current_user.username), ) return render_template("admin.html", text=open("./flag").read())
Example #16
Source File: routes.py From thewarden with MIT License | 6 votes |
def aclst(): list = [] if request.method == "GET": tradeaccounts = Trades.query.filter_by( user_id=current_user.username).group_by( Trades.trade_account) accounts = AccountInfo.query.filter_by( user_id=current_user.username).group_by( AccountInfo.account_longname ) q = request.args.get("term") for item in tradeaccounts: if q.upper() in item.trade_account.upper(): list.append(item.trade_account) for item in accounts: if q.upper() in item.account_longname.upper(): list.append(item.account_longname) list = json.dumps(list) return list
Example #17
Source File: routes.py From thewarden with MIT License | 6 votes |
def tradedetails(): if request.method == "GET": id = request.args.get("id") # if tradesonly is true then only look for buy and sells tradesonly = request.args.get("trades") df = pd.read_sql_table("trades", db.engine) # Filter only the trades for current user df = df[(df.user_id == current_user.username)] df = df[(df.trade_reference_id == id)] # Filter only buy and sells, ignore deposit / withdraw if tradesonly: df = df[(df.trade_operation == "B") | (df.trade_operation == "S")] # df['trade_date'] = pd.to_datetime(df['trade_date']) df.set_index("trade_reference_id", inplace=True) df.drop("user_id", axis=1, inplace=True) details = df.to_json() return details
Example #18
Source File: keymanager.py From mini-key-server with MIT License | 6 votes |
def cut_key_unsafe(activations: int, app_id: int, active: bool = True, memo: str = "") -> str: """ Cuts a new key and returns the activation token. Cuts a new key with # `activations` allowed activations. -1 is considered unlimited activations. """ token = generate_token_unsafe() key = Key(token, activations, app_id, active, memo) key.cutdate = datetime.utcnow() db.session.add(key) db.session.commit() current_app.logger.info( f"cut new key {key} with {activations} activation(s), memo: {memo}") AuditLog.from_key(key, f"new key cut by {current_user.username} " f"({request.remote_addr})", Event.KeyCreated) return token
Example #19
Source File: routes.py From AUCR with GNU General Public License v3.0 | 6 votes |
def qrcode(): """Two factor auth qrcode page route.""" user_name = User.query.filter_by(username=current_user.username).first() if user_name is None: render_error_page_template(404) # for added security, remove username from session # render qrcode for FreeTOTP url = pyqrcode.create(user_name.get_totp_uri()) stream = BytesIO() url.svg(stream, scale=3) flash(user_name.otp_secret) return stream.getvalue(), 200, { 'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0'}
Example #20
Source File: user.py From open_dnsdb with Apache License 2.0 | 5 votes |
def get_user(username): user = UserDal.get_user_info(username=username) if user is None: return [] return [UserDal.get_user_info(username=username).json_serialize()]
Example #21
Source File: view_isp_acl.py From open_dnsdb with Apache License 2.0 | 5 votes |
def delete_acl_subnet(subnet_id, username): subnet = ViewAclSubnet.query.filter_by(id=subnet_id).first() if not subnet: raise BadParam('No such acl subnet record: %s' % subnet_id, msg_ch=u'没有对应的网段记录') with db.session.begin(subtransactions=True): db.session.delete(subnet) subnet_info = subnet.json_serialize(include=['subnet', 'origin_acl', 'now_acl']) origin = subnet_info['origin_acl'] now = subnet_info['now_acl'] start_acl_deploy_job(username, [now] if now == origin else [now, origin]) return subnet_info
Example #22
Source File: user.py From open_dnsdb with Apache License 2.0 | 5 votes |
def delete_user(username): if username == current_user.username: raise BadParam('cannot delete yourself') user = UserDal.get_user_info(username=username) if not user: raise BadParam('No such user with name: %s' % username) result = user.json_serialize(include=('username', 'email', 'role')) UserDal.delete_user(username) return result
Example #23
Source File: auth.py From open_dnsdb with Apache License 2.0 | 5 votes |
def login(): if request.method == 'POST': form = request.get_json(force=True) user = UserDal.get_user_info(username=form['username']) if user is not None and user.verify_password(form['password']): login_user(user, remember=True) return current_user.username raise DnsdbException('Invalid username or password.', msg_ch=u'账号或密码错误') else: raise Unauthorized()
Example #24
Source File: view_isp_acl.py From open_dnsdb with Apache License 2.0 | 5 votes |
def update_isp(name_in_english, update_data, username): update_data['username'] = username return ViewIsps.query.filter_by(name_in_english=name_in_english).update(update_data)
Example #25
Source File: decorators.py From open_dnsdb with Apache License 2.0 | 5 votes |
def parse_params(param_meta=None, need_username=False): parser = reqparse.RequestParser() param_meta = [] if param_meta is None else param_meta for kw in param_meta: parser.add_argument(**kw) def _inner(func): @wraps(func) def _wrapper(*args, **kwargs): params = parser.parse_args() for k in list(params.keys()): v = params[k] if v is None: params.pop(k) if isinstance(v, str): params[k] = v.strip() kwargs.update(params) if need_username: kwargs['username'] = current_user.username log.info('func: %s, args: %s' % (func.__name__, kwargs)) return func(*args, **kwargs) return _wrapper return _inner
Example #26
Source File: views.py From flask-todolist with MIT License | 5 votes |
def _get_user(): return current_user.username if current_user.is_authenticated else None
Example #27
Source File: user.py From open_dnsdb with Apache License 2.0 | 5 votes |
def get_delete_info(result, **kwargs): username = kwargs['username'] return username, result, {}
Example #28
Source File: views.py From helix-sandbox with GNU Affero General Public License v3.0 | 5 votes |
def dashboard(): user = User.query.filter_by(username=current_user.username).first() return render_template('home/dashboard.html', user=user,title="Dashboard")
Example #29
Source File: user.py From modern-paste with MIT License | 5 votes |
def create_new_user(): """ API endpoint for creating a new user. """ if not config.ENABLE_USER_REGISTRATION: return ( flask.jsonify(constants.api.USER_REGISTRATION_DISABLED_FAILURE), constants.api.USER_REGISTRATION_DISABLED_FAILURE_CODE, ) data = flask.request.get_json() try: new_user = database.user.create_new_user( username=data['username'], password=data['password'], signup_ip=flask.request.remote_addr, name=data.get('name'), email=data.get('email'), ) login_user(new_user) return flask.jsonify({ constants.api.RESULT: constants.api.RESULT_SUCCESS, constants.api.MESSAGE: None, 'username': new_user.username, 'name': new_user.name, 'email': new_user.email, }), constants.api.SUCCESS_CODE except UsernameNotAvailableException: return flask.jsonify({ constants.api.RESULT: constants.api.RESULT_FAULURE, constants.api.MESSAGE: 'Username is not available', constants.api.FAILURE: 'username_not_available_failure', }), constants.api.INCOMPLETE_PARAMS_FAILURE_CODE except InvalidEmailException: return flask.jsonify({ constants.api.RESULT: constants.api.RESULT_FAULURE, constants.api.MESSAGE: 'Email address {email_addr} is invalid'.format(email_addr=data.get('email')), constants.api.FAILURE: 'invalid_email_failure', }), constants.api.INCOMPLETE_PARAMS_FAILURE_CODE except: return flask.jsonify(constants.api.UNDEFINED_FAILURE), constants.api.UNDEFINED_FAILURE_CODE
Example #30
Source File: investigations.py From yeti with Apache License 2.0 | 5 votes |
def inv_import(self): if request.method == "GET": return render_template( "{}/import.html".format(self.klass.__name__.lower()), groups=get_user_groups()) else: text = request.form.get('text') url = request.form.get('url') sharing = request.form.get('sharing') if text: investigation = Investigation( created_by=current_user.username, import_text=text) # set sharing permissions investigation.save() investigation.sharing_permissions(sharing) return redirect( url_for( 'frontend.InvestigationView:import_from', id=investigation.id)) else: try: if url: import_method = ImportMethod.objects.get(acts_on="url") results = import_method.run(url) elif "file" in request.files: target = AttachedFile.from_upload(request.files['file']) import_method = ImportMethod.objects.get( acts_on=target.content_type) results = import_method.run(target) else: flash("You need to provide an input", "danger") return redirect(request.referrer) return redirect( url_for( 'frontend.InvestigationView:import_wait', id=results.id)) except DoesNotExist: flash("This file type is not supported.", "danger") return render_template( "{}/import.html".format(self.klass.__name__.lower()))