def whoami(): hello = dict(app.current_request.headers) print hello['authorization'] if hello.has_key('authorization'): try: decoded = jwt.decode(str(hello['authorization']), HMAC_PASSWORD_2, algorithms=['HS256']) # print "decoded", decoded details = is_valid_jwt(decoded) if details[0].has_key('role'): if details[0]['role'] == 'admin': return { 'success': { 'user': details[0]['username'], 'email': details[0]['email'], 'role': details[0]['role'] } } elif details[0]['role'] == 'user': return { 'success': { 'user': details[0]['username'], 'email': details[0]['email'], 'role': details[0]['role'] } } else: return BadRequestError('Not able to verify user') else: return BadRequestError('Unable to verify user, based on token') except Exception as e: return UnauthorizedError(e) else: return UnauthorizedError('No Token')
def token_decoder(token): """ The ID token expires one hour after the user authenticates. You should not process the ID token in your client or web API after it has expired. https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html :param token: :return: """ set_cognito_data_global() token = remove_barer(token) headers = jwt.get_unverified_headers(token) kid = headers['kid'] result = {} for item in POOL_KEYS: result[item['kid']] = item public_key = jwk.construct(result.get(kid)) message, encoded_signature = str(token).rsplit('.', 1) decoded_signature = base64url_decode(encoded_signature.encode('utf-8')) if not public_key.verify(message.encode("utf8"), decoded_signature): raise UnauthorizedError('Invalid Token') claims = jwt.get_unverified_claims(token) if time.time() > claims['exp']: raise UnauthorizedError('Token in expired!') return claims
def mobicred_shopper_result(): """ https://support.peachpayments.com/hc/en-us/articles/360026704471-Mobicred-integration-guide mobicred_api_resource_path = str(blueprint.current_request.get_query_parameter('resourcePath') or '').strip() """ # Attention! All payment logic is done in webhooks! # Theoretically we can just get the last order by customer, # because currently it's hard for user to do some tricks here, # but event in this case user just gets info about his another order. user = blueprint.current_request.current_user if user.is_anyonimous: raise UnauthorizedError('Authentication is required!') order_storage = OrderStorageImplementation() last_order: Optional[Order] = None orders = order_storage.get_all_for_customer(Id(user.id)) for order in orders: if not last_order or order.created_at > last_order.created_at: last_order = order if not last_order: raise UnprocessableEntityError('No orders - something wrong!') return {'order_number': last_order.number.value}
def validate_params(jira_server_name, api_key): if not jira_server_name: raise BadRequestError("'jira_server_name' is required.") if not api_key: raise BadRequestError("'api_key' was not provided.") if not validate_api_key(api_key): raise UnauthorizedError("'api_key' is not valid")
def update_data_object(data_object_id): """ Updates a data object. The data object must exist. :param data_object_id: the id of the data object to update """ # Ensure that the user is authenticated first if not check_auth(): raise UnauthorizedError("You're not authorized to use this service. " "Did you set access_token in the request headers?") # Make sure that the data object to update exists try: source = azul_match_field(index=INDEXES['data_obj'], key='file_id', val=data_object_id) except LookupError: raise NotFoundError("Data object not found.") # Check that a data object was provided in the request body = app.current_request.json_body if not body or not body.get('data_object', None): raise BadRequestError("Please add a data_object to the body of your request.") # Now that we know everything is okay, do the actual update data = {'doc': obj_to_azul(body['data_object'])} es.update(index=INDEXES['data_obj'], doc_type=DOCTYPES['data_obj'], id=source['_id'], body=data) return model('UpdateDataObjectResponse', data_object_id=data_object_id).marshal()
def get_org(self): # todo: multiple orgs? try: org = Org.objects.get({}) except DoesNotExist: raise UnauthorizedError("Organization does not exist.") return org
def messages_list(): current_user = blue_print.current_request.current_user if current_user.is_anyonimous: raise UnauthorizedError('Authentication is required!') else: # Do something # Give R100 to user. pass
def insufficient_access(self, resource: str): scopes = ', '.join(self.oauth2_scopes()) return UnauthorizedError( f'The current user is not authorized to access {resource} or that ' f'resource does not exist. Make sure that it exists, that the user ' f'is registered with Terra, that the provided access token is not ' f'expired, and that the following access scopes were granted when ' f'authenticating: {scopes}.')
def check_permissions(self, model, actions): result = self.check_permissions_return(model, actions) if result == True: return True if result == False: id = self.get_current_user_id() raise UnauthorizedError( "User {} is not authorized to perform action {} on this resource." .format(id, actions))
def messages_list(): user = blueprint.current_request.current_user if user.is_anyonimous: raise UnauthorizedError('Authentication is required!') message_storage = MessageStorageImplementation() messages = message_storage.get_all_for_customer(user.email) return __response_list(messages)
def index(): r = utils.parse_request(app.current_request) if r['token'] != config.SLACK_VERIFICATION_TOKEN: raise UnauthorizedError( "You are not authorized to use this application") response = COMMANDS[r['command']](r) return response
def login(): try: jbody = app.current_request.json_body if 'email' in jbody and 'password' in jbody: table = dynamo.Table(CV_USR_TBL) response = table.get_item(Key = {'email': jbody['email']}) if 'Item' in response: if response['Item']['password'] == hashlib.md5(jbody['password'].encode()).hexdigest(): token = jwt.encode({'email': response['Item']['email'], 'username': response['Item']['username']}, HMAC_PASSWORD_2, algorithm='HS256') return {"token": token.decode('utf-8')} else: return UnauthorizedError("Invalid Credentials") else: return UnauthorizedError("Invalid Credentials") else: return BadRequestError("Inaccessible Fields") except Exception as e: return BadRequestError(str(e))
def dummy_auth(auth_request): if auth_request.token == 'yes': return AuthResponse(routes=[ '/builtin-auth', AuthRoute('/fake-profile', methods=['POST']) ], context={'foo': 'bar'}, principal_id='foo') else: raise UnauthorizedError('Authorization failed')
def login(): body = app.current_request.json_body try: record = get_users_db().get_item( Key={'username': body['username']})['Item'] jwt_token = auth.get_jwt_token(body['username'], body['password'], record) except KeyError as e: raise UnauthorizedError("Bad credentials") return {'token': jwt_token}
def get_jwt_token(username, password, record): actual = hashlib.pbkdf2_hmac(record['hash'], bytes(password, 'utf-8'), record['salt'].value, record['rounds']) expected = record['hashed'].value if hmac.compare_digest(actual, expected): now = datetime.datetime.utcnow() unique_id = str(uuid4()) payload = {'sub': username, 'iat': now, 'nbf': now, 'jti': unique_id} return jwt.encode(payload, _SECRET, algorithm='HS256') raise UnauthorizedError('Invalid password')
def delete_user(email): try: hello = dict(app.current_request.headers) if 'authorization' in hello: token = hello.get('authorization') if token == 'admin' or token == 'staff': table = dynamo.Table(CV_USR_TBL) resp = table.delete_item(Key={ 'email': email }) if 'Error' in resp: return BadRequestError("Unable to delete ") else: return {'success': 'User with email: {} deleted'.format(email)} else: return UnauthorizedError('You are not allowed to execute this function') else: return UnauthorizedError("There's not token in your Request") except Exception as e: return BadRequestError(e)
def predict(): if 'image' not in app.current_request.json_body: raise UnauthorizedError("The image attribute is required.") image = json.loads(app.current_request.json_body['image']) if len(image) != 64: raise BadRequestError("Image should be serialized 8x8 grayscale. It's {}.".format(len(image))) model = pickle.load(open('chalicelib/model.pkl', 'rb')) return {"class": model.predict([image]).tolist()}
def response_view(responseId): """View an individual response.""" from ..main import app try: response = Response.objects.get({"_id": ObjectId(responseId)}) if True: # if response.user == app.get_current_user_id() or app.check_permissions(response.select_related("form"), ["Responses_View", "Responses_CheckIn"]): return {"success": True, "res": serialize_model(response)} else: raise UnauthorizedError("Unauthorized to access this response.") except DoesNotExist: raise NotFoundError(f"Response with ID {responseId} not found")
def validate_signature(request): """Validate that the signature in the header matches the payload.""" if SECRET is None: return try: signature = request.headers['X-Hub-Signature'] _, sha1 = signature.split('=') except KeyError: raise BadRequestError() digest = hmac.new(SECRET, request.raw_body, hashlib.sha1).hexdigest() if not hmac.compare_digest(digest, sha1.encode('utf-8')): raise UnauthorizedError()
def validate_signature(request): """Validate that the signature in the header matches the payload.""" if CONFIG['SECRET'] is None: return try: signature = request.headers['X-Hub-Signature'] _, sha1 = signature.split('=') except (KeyError, ValueError): raise BadRequestError() digest = hmac.new(CONFIG['SECRET'].encode(), request.raw_body.encode(), hashlib.sha1) \ .hexdigest() if not hmac.compare_digest(digest.encode(), sha1.encode()): raise UnauthorizedError()
def get_jwt_token(username, password, expected): actual = '{}:{}'.format(username, password) if hmac.compare_digest(actual, expected): now = datetime.datetime.utcnow() unique_id = str(uuid4()) payload = { 'sub': username, 'iat': now, 'nbf': now, 'jti': unique_id, # NOTE: We can also add 'exp' if we want tokens to expire. } return jwt.encode(payload, _SECRET, algorithm='HS256') raise UnauthorizedError('Invalid password')
def protected_view(): try: hello = dict(app.current_request.headers) if hello.has_key('authorization'): token = hello.get('authorization') if token == 'admin' or token == 'staff': return {'success': 'you are an administrator'} elif token == 'user': return {'less-success': 'You are just a user'} else: return BadRequestError('Unrecognized') else: return UnauthorizedError("No Authorization Token") except Exception as e: return BadRequestError(e)
def login(): try: dynamo = boto3.resource('dynamodb', region_name='us-east-1') jbody = app.current_request.json_body if 'email' in jbody and 'password' in jbody: user_table = dynamo.Table('ctf_users') resp = user_table.get_item(Key={'email': jbody['email']}) if 'Item' in resp: if resp['Item']['password'] == hashlib.md5( jbody['password']).hexdigest(): token = jwt.encode({'username': resp['Item']['username']}, key=HMAC_PASSWORD, algorithm='HS256') return {'success': True, 'token': token} else: return UnauthorizedError( 'Unable to verify user credentials') else: return UnauthorizedError('Unable to find user') else: return BadRequestError( 'Mandatory fields email and password not present') except Exception as e: return BadRequestError(e)
def get_jwt_token(email, password, record): actual = hashlib.pbkdf2_hmac(record['hash'], password.encode(), record['salt'].value, record['rounds']) expected = record['hashed'].value if hmac.compare_digest(actual, expected): now = str(datetime.datetime.utcnow()) unique_id = str(uuid4()) payload = { 'sub': email, 'iat': now, 'nbf': now, 'jti': unique_id, # NOTE: We can also add 'exp' if we want tokens to expire. } return jwt.encode(payload, _SECRET, algorithm='HS256') raise UnauthorizedError('Invalid password')
def keys(access_key_id, plugin): """Takes an access key ID and plugin based on plugin will run disable STS""" try: post = app.current_request.json_body c = credential.Credential(post['sort_key']) compromised_resource = { 'access_key_id': access_key_id, 'compromise_type': 'KeyCompromise' } aws_credential = c.get_write() client = c.aws_client( 'iam', aws_credential, 'us-west-2' ) if plugin == 'disable': plugin_client = disableaccess_key.Disableaccess( client=client, compromised_resource=compromised_resource, dry_run=False ) elif plugin == 'revoke_sts': plugin_client = revokests_key.RevokeSTS( client=client, compromised_resource=compromised_resource, dry_run=False ) return {plugin: plugin_client.validate()} except KeyError: raise BadRequestError("Route takes an access_key_id and plugin.") except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == 'AccessDenied': raise UnauthorizedError(e) else: raise Exception(e) except Exception as e: logging.exception("Exception in {}:".format(plugin)) raise BadRequestError("{} failed - {}".format(plugin, e))
def validate_signature(request): """Validate that the signature in the header matches the payload.""" if CONFIG["SECRET"] is None: return try: signature = request.headers["X-Hub-Signature"] hashname, hashval = signature.split("=") except (KeyError, ValueError): raise BadRequestError() if (hashname in CONFIG["HASHLIB_BLACKLIST"]) or ( hashname not in hashlib.algorithms_available): raise BadRequestError("X-Hub-Signature hash algorithm unavailable") digest = hmac.new(CONFIG["SECRET"].encode(), request.raw_body.encode(), hashname).hexdigest() if not hmac.compare_digest(digest.encode(), hashval.encode("utf-8")): raise UnauthorizedError("X-Hub-Signature mismatch")
def login(): body = app.current_request.json_body expected = '{}:{}'.format(env.get('username'), env.get('password')) actual = '{}:{}'.format(body['username'], body['password']) if hmac.compare_digest(actual, expected): now = datetime.datetime.utcnow() unique_id = str(uuid4()) payload = { 'sub': body['username'], 'iat': now, 'nbf': now, 'jti': unique_id, # NOTE: We can also add 'exp' if we want tokens to expire. } jwt_token = jwt.encode(payload, env.get('secret'), 'HS256').decode('utf-8') return {'token': jwt_token} raise UnauthorizedError('Invalid password')
def user_info(access_token): """ Retrieve user information in the Cognito user pool. :param access_token: :return: """ client = boto3.client('cognito-idp') try: cognito_user = client.get_user(AccessToken=access_token) user_info = {} for attr in cognito_user['UserAttributes']: key = attr['Name'] if key == 'sub': key = 'user_id' val = attr['Value'] user_info[key] = val return user_info except Exception as e: raise UnauthorizedError('Token is invalid!')
def get_jwt_token(user_obj, password): actual = hashlib.pbkdf2_hmac( user_obj.hash, str.encode(password), user_obj.salt.value, user_obj.rounds ) expected = user_obj.hashed.value if hmac.compare_digest(actual, expected): now = datetime.datetime.utcnow() print(now) unique_id = str(uuid4()) payload = { 'sub': user_obj.username, 'iat': now, 'nbf': now, 'jti': unique_id # NOTE: We can also add 'exp' if we want tokens to expire. } return jwt.encode(payload, _SECRET, 'HS256').decode('utf-8') raise UnauthorizedError('Invalid password')
def upload_resume(): try: dynamo = boto3.resource('dynamodb', region_name='us-east-1') hello = dict(app.current_request.headers) if hello.has_key('authorization'): decoded = jwt.decode(str(hello['authorization']), algorithms=['HS256'], verify=False) details = is_valid_jwt(decoded) else: return UnauthorizedError('No Authorization Header Found') rfile = BytesIO(app.current_request.raw_body) content_type = app.current_request.headers['content-type'] _, parameters = cgi.parse_header(content_type) parameters['boundary'] = parameters['boundary'].encode('utf-8') files = cgi.parse_multipart(rfile, parameters) try: for k, v in files.items(): file_key = '{}-{}.docx'.format(details[0]['username'], str(uuid4())) docx_stream = BytesIO(v[0]) docx_stream.seek(0) s3.upload_fileobj(docx_stream, 'sls-ctf-resumes', file_key) table = dynamo.Table('ctf_resumes') table.put_item( Item={ 'filename': file_key, 'email': details[0]['email'], 'username': details[0]['username'] }) return {'uploaded': True} except Exception as s3_e: return BadRequestError("S3 Error: {}".format(s3_e)) except Exception as e: return BadRequestError(e)