本文整理汇总了Python中flask.g.user方法的典型用法代码示例。如果您正苦于以下问题:Python g.user方法的具体用法?Python g.user怎么用?Python g.user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.g
的用法示例。
在下文中一共展示了g.user方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: mark_as_read
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def mark_as_read(notification_id):
"""
Mark a notification as read
Input:
notification_id: in url
Output:
200 if updated successfully
"""
user = g.user
notification = Notification.get(notification_id)
if not notification or notification.user_id != user.id:
return jsonify(error="Forbidden"), 403
notification.read = True
db.session.commit()
return jsonify(done=True), 200
示例2: create_api_key
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def create_api_key():
"""Used to create a new api key
Input:
- device
Output:
- api_key
"""
data = request.get_json()
if not data:
return jsonify(error="request body cannot be empty"), 400
device = data.get("device")
api_key = ApiKey.create(user_id=g.user.id, name=device)
db.session.commit()
return jsonify(api_key=api_key.code), 201
示例3: delete_mailbox
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def delete_mailbox(mailbox_id):
"""
Delete mailbox
Input:
mailbox_id: in url
Output:
200 if deleted successfully
"""
user = g.user
mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != user.id:
return jsonify(error="Forbidden"), 403
if mailbox.id == user.default_mailbox_id:
return jsonify(error="You cannot delete the default mailbox"), 400
Mailbox.delete(mailbox_id)
db.session.commit()
return jsonify(deleted=True), 200
示例4: delete_alias
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def delete_alias(alias_id):
"""
Delete alias
Input:
alias_id: in url
Output:
200 if deleted successfully
"""
user = g.user
alias = Alias.get(alias_id)
if not alias or alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
alias_utils.delete_alias(alias, user)
return jsonify(deleted=True), 200
示例5: toggle_alias
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def toggle_alias(alias_id):
"""
Enable/disable alias
Input:
alias_id: in url
Output:
200 along with new status:
- enabled
"""
user = g.user
alias: Alias = Alias.get(alias_id)
if alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
alias.enabled = not alias.enabled
db.session.commit()
return jsonify(enabled=alias.enabled), 200
示例6: get_alias
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def get_alias(alias_id):
"""
Get alias
Input:
alias_id: in url
Output:
Alias info, same as in get_aliases
"""
user = g.user
alias: Alias = Alias.get(alias_id)
if not alias:
return jsonify(error="Unknown error"), 400
if alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
return jsonify(**serialize_alias_info_v2(get_alias_info_v2(alias))), 200
示例7: delete_contact
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def delete_contact(contact_id):
"""
Delete contact
Input:
contact_id: in url
Output:
200
"""
user = g.user
contact = Contact.get(contact_id)
if not contact or contact.alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
Contact.delete(contact_id)
db.session.commit()
return jsonify(deleted=True), 200
示例8: require_api_auth
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
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
示例9: login
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def login():
if g.user is not None:
return redirect(url_for('index'))
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
user = users.User.query.filter_by(username=form.username.data).first()
if user is None:
flash(u'El usuario no existe')
elif not user.checkpassword(form.password.data):
flash(u'Contraseña incorrecta')
app.logger.info('[%s] login failed', user)
else:
flash(u'Bienvenido de nuevo, %s'%user.username)
session['user_id'] = user.id
g.user = user
app.logger.info('[%s] login succeeded', user)
return level.autosolve(app) or redirect(url_for('index'))
return redirect(url_for('index'))
示例10: skip
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def skip(self):
if g.user is None:
self.logger.info('[%s][%s] anonymous skip', g.user, self.name)
return redirect(url_for(self.name + '.index'))
g.user.lock()
if not self.can_skip():
g.user.unlock()
self.logger.warning('[%s][%s] skip() but can\'t skip', g.user, self.name)
return render_template('forbidden.html'), 403
g.user.setstate(self, 'skipped')
g.user.commit()
self.logger.info('[%s][%s] skipped', g.user, self.name)
flash(u"Te has saltado el nivel %d" % self.number)
try:
next = self.route_.levels[self.routeidx+1]
return redirect(url_for(next.name + '.index'))
except IndexError:
alldone = all([l.state() == 'solved' for r in routes for l in r.levels])
self.logger.info('[%s][%s] last level (alldone=%r)', g.user, self.name, alldone)
return render_template('alldone.html', alldone=alldone, level=self)
示例11: can_skip
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def can_skip(self):
if g.user is None:
return False
if self.state() == 'skipped':
return False
skipped = 0
for k,v in g.user.levels.items():
if v.state == 'skipped':
skipped += 1
if skipped > self.config['MAX_SKIP']:
self.logger.error('[%s][%s] User has %d skips, but max %d', skipped, self.config['MAX_SKIP'])
return False
elif skipped == self.config['MAX_SKIP']:
return False
else:
return True
示例12: state
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def state(self):
if datetime.utcnow() < self.config['START_TIME']:
return 'closed'
if g.user is None:
if self.routeidx == 0:
return 'open'
else:
return 'closed'
else:
userstate = g.user.getstate(self).state
if userstate == 'unsolved':
if self.routeidx == 0:
return 'open'
for prev in self.route_.levels[:self.routeidx]:
prevstate = g.user.getstate(prev).state
if prevstate not in ('solved','skipped'):
return 'closed'
else:
return 'open'
else:
return userstate
示例13: load_user_from_request
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def load_user_from_request(request):
if config.config_allow_reverse_proxy_header_login:
rp_header_name = config.config_reverse_proxy_login_header_name
if rp_header_name:
rp_header_username = request.headers.get(rp_header_name)
if rp_header_username:
user = _fetch_user_by_name(rp_header_username)
if user:
return user
auth_header = request.headers.get("Authorization")
if auth_header:
user = load_user_from_auth_header(auth_header)
if user:
return user
return
示例14: load_user_from_auth_header
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def load_user_from_auth_header(header_val):
if header_val.startswith('Basic '):
header_val = header_val.replace('Basic ', '', 1)
basic_username = basic_password = ''
try:
header_val = base64.b64decode(header_val).decode('utf-8')
basic_username = header_val.split(':')[0]
basic_password = header_val.split(':')[1]
except (TypeError, UnicodeDecodeError, binascii.Error):
pass
user = _fetch_user_by_name(basic_username)
if user and config.config_login_type == constants.LOGIN_LDAP and services.ldap:
if services.ldap.bind_user(str(user.password), basic_password):
return user
if user and check_password_hash(str(user.password), basic_password):
return user
return
示例15: login_required
# 需要导入模块: from flask import g [as 别名]
# 或者: from flask.g import user [as 别名]
def login_required(f):
'''
This decorator checks the header to ensure a valid token is set
'''
@wraps(f)
def func(*args, **kwargs):
try:
if 'authorization' not in request.headers:
abort(404, message="You need to be logged in to access this resource")
token = request.headers.get('authorization')
payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
user_id = payload['id']
g.user = User.find(user_id)
if g.user is None:
abort(404, message="The user id is invalid")
return f(*args, **kwargs)
except JWTError as e:
abort(400, message="There was a problem while trying to parse your token -> {}".format(e.message))
return func