|
| 1 | +import json |
| 2 | + |
| 3 | +from aioamqp import AmqpClosedConnection |
| 4 | +from marshmallow import ValidationError |
| 5 | +from sanic_amqp_ext import AmqpWorker |
| 6 | +from sage_utils.constants import VALIDATION_ERROR, NOT_FOUND_ERROR |
| 7 | +from sage_utils.wrappers import Response |
| 8 | + |
| 9 | + |
| 10 | +from app.token.json_web_token import build_payload, generate_token_pair |
| 11 | + |
| 12 | + |
| 13 | +class GenerateTokenWorker(AmqpWorker): |
| 14 | + QUEUE_NAME = 'auth.token.new' |
| 15 | + REQUEST_EXCHANGE_NAME = 'open-matchmaking.auth.token.new.direct' |
| 16 | + RESPONSE_EXCHANGE_NAME = 'open-matchmaking.responses.direct' |
| 17 | + CONTENT_TYPE = 'application/json' |
| 18 | + |
| 19 | + def __init__(self, app, *args, **kwargs): |
| 20 | + super(GenerateTokenWorker, self).__init__(app, *args, **kwargs) |
| 21 | + from app.users.documents import User |
| 22 | + from app.token.api.schemas import LoginSchema |
| 23 | + self.user_document = User |
| 24 | + self.schema = LoginSchema |
| 25 | + |
| 26 | + def validate_data(self, raw_data): |
| 27 | + try: |
| 28 | + data = json.loads(raw_data.strip()) |
| 29 | + except json.decoder.JSONDecodeError: |
| 30 | + data = {} |
| 31 | + |
| 32 | + deserializer = self.schema() |
| 33 | + result = deserializer.load(data) |
| 34 | + if result.errors: |
| 35 | + raise ValidationError(result.errors) |
| 36 | + |
| 37 | + return result.data |
| 38 | + |
| 39 | + async def generate_token(self, raw_data): |
| 40 | + try: |
| 41 | + data = self.validate_data(raw_data) |
| 42 | + except ValidationError as exc: |
| 43 | + return Response.from_error(VALIDATION_ERROR, exc.normalized_messages()) |
| 44 | + |
| 45 | + user = await self.user_document.find_one({"username": data["username"]}) |
| 46 | + if not user or (user and not user.verify_password(data["password"])): |
| 47 | + return Response.from_error( |
| 48 | + NOT_FOUND_ERROR, "User wasn't found or specified an invalid password." |
| 49 | + ) |
| 50 | + |
| 51 | + payload = build_payload(self.app, extra_data={"user_id": str(user.pk)}) |
| 52 | + response = await generate_token_pair(self.app, payload, user.username) |
| 53 | + return Response.with_content(response) |
| 54 | + |
| 55 | + async def process_request(self, channel, body, envelope, properties): |
| 56 | + response = await self.generate_token(body) |
| 57 | + response.data[Response.EVENT_FIELD_NAME] = properties.correlation_id |
| 58 | + |
| 59 | + if properties.reply_to: |
| 60 | + await channel.publish( |
| 61 | + json.dumps(response.data), |
| 62 | + exchange_name=self.RESPONSE_EXCHANGE_NAME, |
| 63 | + routing_key=properties.reply_to, |
| 64 | + properties={ |
| 65 | + 'content_type': self.CONTENT_TYPE, |
| 66 | + 'delivery_mode': 2, |
| 67 | + 'correlation_id': properties.correlation_id |
| 68 | + }, |
| 69 | + mandatory=True |
| 70 | + ) |
| 71 | + |
| 72 | + await channel.basic_client_ack(delivery_tag=envelope.delivery_tag) |
| 73 | + |
| 74 | + async def consume_callback(self, channel, body, envelope, properties): |
| 75 | + self.app.loop.create_task(self.process_request(channel, body, envelope, properties)) |
| 76 | + |
| 77 | + async def run(self, *args, **kwargs): |
| 78 | + try: |
| 79 | + _transport, protocol = await self.connect() |
| 80 | + except AmqpClosedConnection as exc: |
| 81 | + print(exc) |
| 82 | + return |
| 83 | + |
| 84 | + channel = await protocol.channel() |
| 85 | + await channel.queue_declare( |
| 86 | + queue_name=self.QUEUE_NAME, |
| 87 | + durable=True, |
| 88 | + passive=False, |
| 89 | + auto_delete=False |
| 90 | + ) |
| 91 | + await channel.queue_bind( |
| 92 | + queue_name=self.QUEUE_NAME, |
| 93 | + exchange_name=self.REQUEST_EXCHANGE_NAME, |
| 94 | + routing_key=self.QUEUE_NAME |
| 95 | + ) |
| 96 | + await channel.basic_qos(prefetch_count=1, prefetch_size=0, connection_global=False) |
| 97 | + await channel.basic_consume(self.consume_callback, queue_name=self.QUEUE_NAME) |
0 commit comments