def test_slack_signature(mock_env_slack): timestamp = int(time()) Config.init_config() SLACK_SIGNING_SECRET = Config.get_or_else('SLACK', 'SIGNING_SECRET',None) signature = create_slack_signature(SLACK_SIGNING_SECRET, timestamp, "test_data") assert True==validate_slack_signature(SLACK_SIGNING_SECRET, "test_data", timestamp, signature ) assert False==validate_slack_signature(SLACK_SIGNING_SECRET, "test_data_err", timestamp, signature )
def __init__(self,event:BaseModel): self.event_in=event self.logger = logger self.CHANNEL_TGX_ANNOUNCEMENTS = Config.get_or_else('SLACK', 'CHANNEL_TGX_ANNOUNCEMENTS',None) self.CHANNEL_ALL_ANNOUNCEMENTS = Config.get_or_else('SLACK', 'CHANNEL_ALL_ANNOUNCEMENTS',None) self.web_client = slack.WebClient(token=Config.get_or_else('SLACK', 'BOT_TOKEN',None), run_async=True) self.http_gql_client = HttpGql(url=Config.get_or_else('TRAVELGATEX', 'GRAPHQL_API_URL',None), api_key=Config.get_or_else('TRAVELGATEX', 'GRAPHQL_API_KEY',None))
def _send_data(data): data_json = json.dumps(data) timestamp = int(time()) SLACK_SIGNING_SECRET = Config.get_or_else('SLACK', 'SIGNING_SECRET', None) signature = create_slack_signature(SLACK_SIGNING_SECRET, timestamp, data_json) response = client.post("slack/events", headers={ 'X-Slack-Request-Timestamp': str(timestamp), 'X-Slack-Signature': signature }, json=data) print(f"response:[{response}], content:[{response.content}]") return response
async def is_valid_slack_signature(request: Request): logger.info("Validating slack signature...") # Each request comes with request timestamp and request signature # emit an error if the timestamp is out of range req_timestamp = request.headers.get('X-Slack-Request-Timestamp') if ( (not req_timestamp) or (abs(time() - int(req_timestamp)) > 60 * 5) ): logger.error("Bad X-Slack-Request-Timestamp") raise HTTPException( status_code=403, detail="Request header X-Slack-Request-Timestamp out of range") req_signature = request.headers.get('X-Slack-Signature') if (not req_signature): logger.error("Bad X-Slack-Signature") raise HTTPException( status_code=403, detail="Bad X-Slack-Signature") body = await request.body() data_str = body.decode() SLACK_SIGNING_SECRET = Config.get_or_else('SLACK','SIGNING_SECRET',None) signature_ok = validate_slack_signature( signing_secret=SLACK_SIGNING_SECRET, data=data_str, timestamp=req_timestamp, signature=req_signature) logger.debug(f"validate signature data: [{data_str}], signature_ok:[{signature_ok}]") if (not signature_ok): logger.error("Bad request signature") raise HTTPException( status_code=403, detail="Bad request signature")
position_book = response.get("positionBook", 200) t = position_book.time position_bucket = position_book.buckets long_percentage_total = sum( map(lambda element: element.longCountPercent, position_bucket)) short_percentage_total = sum( map(lambda element: element.shortCountPercent, position_bucket)) print(f"TIME: {t}") print("LONG PERCENTAGE TOTAL") print(long_percentage_total) print("SHORT PERCENTAGE TOTAL") print(short_percentage_total) """ "price": "80.900", "longCountPercent": "0.0106", "shortCountPercent": "0.0000" """ if __name__ == "__main__": os.environ["TESTING"] = "TRUE" ctx = Config() ctx.load() ctx.validate() api = ctx.create_context() rpb = ReadPositionBook(api) rpb.fetch_position_book()
import logging import os import json from pydantic import BaseModel from app.common.jira_models import WebHookModelIn, WebHookModelOut import app.common.util from app.common.config import Config from abc import ABC, abstractmethod Config.init_config() logger = logging.getLogger(__name__) logger.info("tasks start") class Task(ABC): def __init__(self, event: BaseModel): self.event_in = event self.logger = logger #self.CHANNEL_TGX_ANNOUNCEMENTS = Config.get_or_else('SLACK', 'CHANNEL_TGX_ANNOUNCEMENTS',None) #self.CHANNEL_ALL_ANNOUNCEMENTS = Config.get_or_else('SLACK', 'CHANNEL_ALL_ANNOUNCEMENTS',None) #self.web_client = slack.WebClient(token=Config.get_or_else('SLACK', 'BOT_TOKEN',None), run_async=True) @abstractmethod async def execute(self): pass class Command(Task): @abstractmethod async def execute(self): pass
import json from time import time from fastapi import Security, Depends, FastAPI, Header, HTTPException from fastapi.security.api_key import APIKeyQuery, APIKeyCookie, APIKeyHeader, APIKey from starlette.status import HTTP_403_FORBIDDEN from starlette.requests import Request from starlette.responses import JSONResponse from starlette.applications import Starlette from starlette_exporter import PrometheusMiddleware, handle_metrics from app.routers import (jira_events) from app.common.config import Config Config.init_config() logger = logging.getLogger(__name__) logger.info("main start") API_KEY = Config.get_or_else('APP', 'API_KEY_NAME', None) API_KEY_NAME = Config.get_or_else('APP', 'API_KEY_NAME', None) api_key_query = APIKeyQuery(name=API_KEY_NAME, auto_error=False) api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False) async def get_api_key(api_key_query: str = Security(api_key_query), api_key_header: str = Security(api_key_header)): if api_key_query == API_KEY: return api_key_query elif api_key_header == API_KEY: return api_key_header