def __init__(self, namespace, config, sio): super().__init__(namespace) self.chat_service = ChatService(config) self.chat_room_service = ChatRoomService(config) self.linkedin_login = LinkedInLogin(config) self.user_service = UserService(config) self.offer_service = OfferService(config) self.config = config
def wrapper(*args, **kwargs): user_id = None auth_headers = request.headers.get("Authorization", "").split() try: if len(auth_headers) != 2: raise errors.HTTPTokenRequired token = auth_headers[1] data = jwt.decode(token, verify=False) cognito_id = data["sub"] email = data["email"] groups = data.get("cognito:groups") or [] if SystemGroupName.USER_GROUP_NAME in groups or SystemGroupName.ADMIN_GROUP_NAME in groups: user_svc = UserService(ProductionFactory()) user = user_svc.get_user_by_cognito_id(cognito_id) if not user: raise errors.HTTPInvalidTokenError else: user_id = user["id"] else: raise errors.HTTPPermissionDenied auth_data = { "email": email, "user_id": user_id, "cognito_id": cognito_id, "groups": groups, "permissions": user["permissions"] } return func(auth_data, *args, **kwargs) except jwt.ExpiredSignatureError as e: raise errors.HTTPExpiredSignatureError except jwt.InvalidTokenError as e: raise errors.HTTPInvalidTokenError except HTTPException as e: traceback.print_exc() raise e except ValidationError as e: traceback.print_exc() raise errors.HTTPBadRequest(custom_message=json.dumps(str(e))) except Exception as e: traceback.print_exc() raise errors.HTTPServerError
sentry_sdk.init( dsn="https://[email protected]/1800796", integrations=[SanicIntegration(), SqlalchemyIntegration()], before_send=sentry_before_send, ) app = Sanic(load_env=False) app.config.update(APP_CONFIG) sio = socketio.AsyncServer( async_mode="sanic", cors_allowed_origins=[], json=AcquityJson ) sio.attach(app) sio.register_namespace(ChatSocketService("/v1/chat", app.config)) app.user_service = UserService(app.config) app.sell_order_service = SellOrderService(app.config) app.buy_order_service = BuyOrderService(app.config) app.security_service = SecurityService(app.config) app.round_service = RoundService(app.config) app.match_service = MatchService(app.config) app.banned_pair_service = BannedPairService(app.config) app.chat_room_service = ChatRoomService(app.config) app.chat_service = ChatService(app.config) app.linkedin_login = LinkedInLogin(app.config) app.user_request_service = UserRequestService(app.config) initialize_cors(app) app.blueprint(blueprint)
from unittest.mock import patch from src.config import APP_CONFIG from src.database import User, UserRequest, session_scope from src.services import UserService from tests.fixtures import create_user from tests.utils import assert_dict_in user_service = UserService(config=APP_CONFIG) def test_create__is_buy(): user_params = { "email": "*****@*****.**", "full_name": "Ben", "provider_user_id": "testing", "display_image_url": "http://blah", "is_buy": True, "auth_token": None, } committee_email = create_user(is_committee=True)["email"] with patch("src.services.EmailService.send_email") as mock: user_service.create_if_not_exists(**user_params) mock.assert_any_call(emails=[user_params["email"]], template="register_buyer") mock.assert_any_call(emails=[committee_email], template="new_user_review") with session_scope() as session:
import jwt from flask_pymongo import PyMongo from googlesearch import search from flask_expects_json import expects_json from src.services import UserService, TextService app = Flask(__name__, static_folder='static') JWT_SECRET = os.getenv('JWT_SECRET') assert JWT_SECRET ADMIN_EMAIL = os.getenv('ADMIN_EMAIL') assert ADMIN_EMAIL ADMIN_PASS = os.getenv('ADMIN_PASS') assert ADMIN_PASS app.config["MONGO_URI"] = os.getenv('MONGO_URI') mongo = PyMongo(app) # TODO: may be some issues in multiple threads user_service = UserService(mongo.db.users) text_service = TextService(mongo.db.texts) @app.before_first_request def ensure_admin(): user_service.ensure_admin_user(ADMIN_EMAIL, ADMIN_PASS) def allow_without_auth(func): func._allow_without_auth = True return func def allow_for_roles(roles): def _allow_for_roles(func): def __allow_for_roles(*args, **kwargs): if g.decoded is None or g.decoded['role'] not in roles: abort(403)