Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def reset_with_token():
json_data = request.json
token = json_data['token']
password = json_data['password']
ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
try:
hour = 86400
email = ts.loads(token, salt=RESET_PASSWORD_SALT, max_age=hour)
user = User.query.filter_by(email=email).first_or_404()
user.password = password
db.session.add(user)
db.session.commit()
except BadData as e:
logger.exception(e)
raise BadRequest('Token invalid')
except Exception as e:
logger.exception(e)
raise InternalServerError()
finally:
db.session.close()
return jsonify({'statusText': 'Password updated'})
state_token = request.args.get('state')
# Verify state parameter
try:
assert state_token
# Checks authenticity and integrity of state and decodes the value.
state = serializer.loads(state_token)
# Verify that state is for this session, app and that next parameter
# have not been modified.
if state['sid'] != session.sid:
current_app.logger.error('Error during oauth: wrong session id. Authorization will fail.')
assert state['sid'] == session.sid
assert state['app'] == remote_app
# Store next URL
set_session_next_url(remote_app, state['next'])
except (AssertionError, BadData):
if current_app.config.get('OAUTHCLIENT_STATE_ENABLED', True) or (
not(current_app.debug or current_app.testing)):
abort(403)
return handlers[remote_app]()
time_limit, 'WTF_CSRF_TIME_LIMIT', 3600, required=False
)
if not data:
raise ValidationError('The CSRF token is missing.')
if field_name not in session:
raise ValidationError('The CSRF session token is missing.')
s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')
try:
token = s.loads(data, max_age=time_limit)
except SignatureExpired:
raise ValidationError('The CSRF token has expired.')
except BadData:
raise ValidationError('The CSRF token is invalid.')
if not safe_str_cmp(session[field_name], token):
raise ValidationError('The CSRF tokens do not match.')
def confirm(self, token):
s = Serializer(current_app.config['SECRET_KEY'])
try:
data = s.loads(token)
except (BadSignature, BadData):
return False
if data.get('confirm') != self.id:
return False
self.confirmed = True
db.session.add(self)
return True
def _is_error_reportable(exc):
# error marked as not reportable
if isinstance(exc, NoReportError) or getattr(exc, '_disallow_report', False):
return False
elif isinstance(exc, BadData):
# itsdangerous stuff - should only fail if someone tampers with a link
return False
elif isinstance(exc, Forbidden):
# forbidden errors for guests are not reportable
# for other users: same logic as any other http exception
return _need_json_response() and session.user is not None
elif isinstance(exc, HTTPException):
# http exceptions can only be reported if they occur during
# an AJAX request - otherwise they are typically caused by
# users doing something wrong (typing a 404 URL, messing with
# data, etc)
return _need_json_response()
else:
return True
@errors_bp.app_errorhandler(BadData)
def handle_baddata(exc):
return render_error(exc, _('Invalid or expired token'), to_unicode(exc.message), 400)
When authentication is implemented we need to reply
the client if the join failed.
"""
if not is_binary:
message = json.loads(payload)
if message['action'] == 'JOIN_WORKSPACE':
if 'workspace' not in message or 'token' not in message:
logger.warning('Invalid join workspace message: '
'{}'.format(message))
self.sendClose()
return
signer = itsdangerous.TimestampSigner(app.config['SECRET_KEY'],
salt="websocket")
try:
workspace_id = signer.unsign(message['token'], max_age=60)
except itsdangerous.BadData as e:
self.sendClose()
logger.warning('Invalid websocket token for workspace '
'{}'.format(message['workspace']))
logger.exception(e)
else:
with app.app_context():
workspace = Workspace.query.get(int(workspace_id))
if workspace.name != message['workspace']:
logger.warning(
'Trying to join workspace {} with token of '
'workspace {}. Rejecting.'.format(
message['workspace'], workspace.name
))
self.sendClose()
else:
self.factory.join_workspace(
When authentication is implemented we need to reply
the client if the join failed.
"""
if not is_binary:
message = json.loads(payload)
if message['action'] == 'JOIN_WORKSPACE':
if 'workspace' not in message or 'token' not in message:
logger.warning('Invalid join workspace message: '
'{}'.format(message))
self.sendClose()
return
signer = itsdangerous.TimestampSigner(app.config['SECRET_KEY'],
salt="websocket")
try:
workspace_id = signer.unsign(message['token'], max_age=60)
except itsdangerous.BadData as e:
self.sendClose()
logger.warning('Invalid websocket token for workspace '
'{}'.format(message['workspace']))
logger.exception(e)
else:
with app.app_context():
workspace = Workspace.query.get(int(workspace_id))
if workspace.name != message['workspace']:
logger.warning(
'Trying to join workspace {} with token of '
'workspace {}. Rejecting.'.format(
message['workspace'], workspace.name
))
self.sendClose()
else:
self.factory.join_workspace(
def _get_auth_status(self, authuser, authpassword):
try:
val = self.serializer.loads(authpassword, max_age=self.LOGIN_EXPIRATION)
except itsdangerous.SignatureExpired:
return dict(status="expired")
except itsdangerous.BadData:
# check if we got user/password direct authentication
return self._validate(authuser, authpassword)
else:
if not isinstance(val, list) or len(val) != 2 or val[0] != authuser:
threadlog.debug("mismatch credential for user %r", authuser)
return dict(status="nouser")
return dict(status="ok", groups=val[1])
def str_to_claims(token_str):
try:
claims = current_app.tokenauth_serializer.loads(token_str)
except BadData:
logger.warning("Got invalid signature in token %r", token_str)
return None
except Exception:
logger.exception("Error processing signature in token %r", token_str)
return None
# convert v1 to ra2
if claims.get('v') == 1:
return {'iss': 'ra2', 'typ': 'prm', 'jti': 't%d' % claims['id']}
if claims.get('iss') != TOKENAUTH_ISSUER:
return None
return claims