Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if is_in_scope(scope):
return f(*args, **kwargs)
else:
return authenticate('Missing required scope: %s' % scope, 403)
auth_header = request.headers.get('Authorization', '')
m = re.match('Bearer (\S+)', auth_header)
token = m.group(1) if m else None
if token:
try:
payload = parse_token(token)
except DecodeError:
return authenticate('Token is invalid')
except ExpiredSignature:
return authenticate('Token has expired')
except InvalidAudience:
return authenticate('Invalid audience')
g.user = payload['login']
g.customer = payload.get('customer', None)
g.scopes = payload.get('scope', '').split(' ')
if is_in_scope(scope):
return f(*args, **kwargs)
else:
return authenticate('Missing required scope: %s' % scope, 403)
if not app.config['AUTH_REQUIRED']:
return f(*args, **kwargs)
return authenticate('Missing authorization API Key or Bearer Token')
jwt_header_json = base64url_decode(id_token.split('.')[0])
jwt_header = json.loads(jwt_header_json.decode('ascii'))
# `kid` is short for key id
key = self.get_public_key(jwt_header['kid'])
try:
return jwt_decode(
id_token,
key=key,
algorithms=jwt_header['alg'],
audience=self.setting('KEY'),
leeway=self.setting('JWT_LEEWAY', default=0),
)
except (DecodeError, ExpiredSignature) as error:
raise AuthTokenError(self, error)
def user_info():
if not request.headers.get('Authorization'):
return jsonify(error='Authorization header missing'), 401
token = request.headers.get('Authorization').split()[1]
try:
payload = jwt.decode(token, app.config['TOKEN_SECRET'])
except DecodeError:
return jsonify(error='Invalid token'), 401
except ExpiredSignature:
return jsonify(error='Expired token'), 401
else:
user_id = payload['sub']
user = User.query.filter_by(id=user_id).first()
if user is None:
return jsonify(error='Should not happen ...'), 500
return jsonify(id=user.id, email=user.email), 200
return jsonify(error="never reach here..."), 500
return False, 'Missing HTTP X-Api-Token header'
try:
data = jwt.decode(token, settings.SECRET_KEY)
data = json.loads(CRYPTO.decrypt(str(data['data'])))
user = User.objects.get(id=data['id'])
g.user = user
if user.last_login == datetime.fromtimestamp(0):
return False, 'You need to login first'
if user is not None and user.is_active:
user.last_login = datetime.now()
user.save()
return True, None
except (utils.CryptoException, jwt.ExpiredSignature, jwt.DecodeError, User.DoesNotExist, KeyError):
return False, 'Unable to authenticate'
g.user_id = None
g.login = receiver.parsed_header.get('id')
g.customers = []
g.scopes = ADMIN_SCOPES
# Bearer Token
auth_header = request.headers.get('Authorization', '')
m = re.match(r'Bearer (\S+)', auth_header)
token = m.group(1) if m else None
if token:
try:
jwt = Jwt.parse(token)
except DecodeError:
raise ApiError('Token is invalid', 401)
except ExpiredSignature:
raise ApiError('Token has expired', 401)
except InvalidAudience:
raise ApiError('Invalid audience', 401)
g.user_id = jwt.subject
g.login = jwt.preferred_username
g.customers = jwt.customers
g.scopes = jwt.scopes # type: List[Scope]
if not Permission.is_in_scope(scope, have_scopes=g.scopes):
raise ApiError('Missing required scope: %s' % scope.value, 403)
else:
return f(*args, **kwargs)
# Basic Auth
auth_header = request.headers.get('Authorization', '')
m = re.match(r'Basic (\S+)', auth_header)
del request.session['jws']
django_logout(request)
raise PermissionDenied
user = auth_service.get_or_create_user(user_args)
if user is not None:
user.backend = 'django.contrib.auth.backends.ModelBackend'
djauth.login(request, user)
return redirect('/')
else:
del request.session['attributes']
del request.session['jwt']
del request.session['jws']
django_logout(request)
raise PermissionDenied # Error: Not for this audience
except jwt.ExpiredSignature:
del request.session['attributes']
del request.session['jwt']
del request.session['jws']
django_logout(request)
raise PermissionDenied # Error: Security cookie has expired
raise PermissionDenied
if parts[0].lower() != 'bearer':
return {'code': 'invalid_header', 'description': 'Authorization header must start with Bearer'}
elif len(parts) == 1:
return {'code': 'invalid_header', 'description': 'Token not found'}
elif len(parts) > 2:
return {'code': 'invalid_header', 'description': 'Authorization header must be Bearer + \s + token'}
token = parts[1]
try:
payload = jwt.decode(
token,
base64.b64decode(client_secret.replace("_","/").replace("-","+")),
audience=client_id
)
except jwt.ExpiredSignature:
return authenticate({'code': 'token_expired', 'description': 'token is expired'})
except jwt.InvalidAudienceError:
return authenticate({'code': 'invalid_audience', 'description': 'incorrect audience, expected: ' + client_id})
except jwt.DecodeError:
return authenticate({'code': 'token_invalid_signature', 'description': 'token signature is invalid'})
_request_ctx_stack.top.current_user = user = payload
return f(*args, **kwargs)
def get(self, request, *args, **kwargs):
token = kwargs.pop('token')
try:
payload = jwt_decode_handler(token)
except jwt.ExpiredSignature:
msg = _('Signature has expired.')
raise exceptions.AuthenticationFailed(msg)
except jwt.DecodeError:
msg = _('Error decoding signature.')
raise exceptions.AuthenticationFailed(msg)
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed()
user_to_activate = User.objects.get(id=payload.get('user_id'))
user_to_activate.is_active = True
user_to_activate.save()
return Response(
{'User Activated'},
status=status.HTTP_200_OK
)
def parse(cls, token: str, key: str=None, verify: bool=True, algorithm: str='HS256') -> 'Jwt':
try:
json = jwt.decode(
token,
key=key or current_app.config['SECRET_KEY'],
verify=verify,
algorithms=algorithm,
audience=current_app.config['OAUTH2_CLIENT_ID'] or request.url_root
)
except (DecodeError, ExpiredSignature, InvalidAudience):
raise
return Jwt(
iss=json.get('iss', None),
sub=json.get('sub', None),
aud=json.get('aud', None),
exp=json.get('exp', None),
nbf=json.get('nbf', None),
iat=json.get('iat', None),
jti=json.get('jti', None),
name=json.get('name', None),
preferred_username=json.get('preferred_username', None),
email=json.get('email', None),
provider=json.get('provider', None),
orgs=json.get('orgs', list()),
groups=json.get('groups', list()),
def verify_token(token):
try:
payload = jwt.decode(
token,
settings.JWT_SECRET_KEY,
True, # verify
options={'verify_exp': True},
algorithms=[settings.JWT_ALGORITHM])
except jwt.ExpiredSignature:
raise serializers.ValidationError(
_("Signature has expired."))
except jwt.DecodeError:
raise serializers.ValidationError(
_("Error decoding signature."))
username = payload.get('username', None)
if not username:
raise serializers.ValidationError(
_("Missing username in payload"))
# Make sure user exists
user_model = get_user_model()
try:
user = user_model.objects.get(username=username)
except user_model.DoesNotExist:
raise serializers.ValidationError(_("User does not exist."))
return user