Пример #1
0
    async def __process_request(self, full_url):
        try:
            request = pd.Series(data=[full_url], index=['request'])
            request.name = datetime.datetime.now()
            self.__timeline = self.__timeline.append(request)
            headers = {
                'Accept': ('text/html,application/xhtml+xml' +
                           ',application/xml;q=0.9,image/webp,' +
                           'image/apng,*/*;q=0.8'),
                'Accept-Encoding':
                'gzip, deflate, br',
                'Accept-Language':
                'en-US,en;q=0.9',
                'Cache-Control':
                'max-age=0',
                'Connection':
                'keep-alive',
                'Upgrade-Insecure-Requests':
                '1',
                'User-Agent': ('Mozilla/5.0 (Macintosh;' +
                               ' Intel Mac OS X 10_11_6) AppleWebKit/537.36 ' +
                               '(KHTML, like Gecko) Chrome/66.0.3359.139' +
                               ' Safari/537.36'),
            }

            async with aiohttp.ClientSession(headers=headers) as session:
                async with session.get(full_url) as resp:
                    text = await resp.text()
                    return utils.parse_data(text)
        except Exception as e:
            Logger.log_error(e)
Пример #2
0
def forgot_password(request: HttpRequest):
    """forgot password and reset

    [route]: /auth/forgot

    [method]: POST
    """
    user_info: dict = parse_data(request)
    if not user_info:
        return failed_api_response(StatusCode.BAD_REQUEST, "Bad request")
    username = user_info.get("username")
    password = user_info.get("password")
    email = user_info.get("email")
    captcha = user_info.get("captcha")
    verified_form = VerifiedUserForm({
        "username": username,
        "password": password,
        "email": email,
        "captcha": captcha
    })
    if not verified_form.is_valid():
        return failed_api_response(StatusCode.INVALID_REQUEST_ARGUMENT,
                                   "Bad information")
    verified_captcha = cache.get(email)
    delattr(cache, email)
    if captcha != verified_captcha:
        return failed_api_response(StatusCode.INVALID_CAPTCHA,
                                   "Captcha not matched")
    user = UserModel.objects.filter(username=username).first()
    if not user or user.email != email:
        return failed_api_response(StatusCode.ITEM_NOT_FOUND, "User not found")
    user.set_password(password)
    user.save()

    return success_api_response({"result": "Ok, password reset"})
Пример #3
0
def disable_user(request: HttpRequest):
    """disable user

    [route]: /auth/disable

    [method]: POST
    """
    user_info: dict = parse_data(request)
    if not user_info:
        return failed_api_response(StatusCode.BAD_REQUEST, "Bad request")
    username = user_info.get("username")
    password = user_info.get("password")
    if username is None or password is None:
        return failed_api_response(StatusCode.INVALID_REQUEST_ARGUMENT,
                                   "Bad user information")
    if not UserModel.objects.filter(username=username).exists():
        return failed_api_response(StatusCode.ITEM_NOT_FOUND,
                                   "User does not exist")

    user = UserModel.objects.get(username=username)

    if not user.check_password(password):
        return failed_api_response(StatusCode.INVALID_USERNAME_OR_PASSWORD,
                                   "User password is wrong")

    user.is_active = False
    user.save()

    return success_api_response({"result": "Ok, user has been diabled."})
Пример #4
0
def send_captcha(request: HttpRequest):
    """create captcha before registration or reset password

    [route]: /auth/captcha

    [method]: POST
    """
    email_info: dict = parse_data(request)
    if not email_info:
        return failed_api_response(StatusCode.BAD_REQUEST, "Bad request")
    email = email_info.get("email")
    verified_form = VerifiedEmail({"email": email})
    if not verified_form.is_valid():
        return failed_api_response(StatusCode.INVALID_REQUEST_ARGUMENT,
                                   "Bad email address")
    captcha = random_str(6)
    cache.set(email, captcha, 5 * 60)
    send_mail(
        "Nocode 验证",
        "验证码:" + captcha + "\n该验证码在五分钟内有效",
        settings.EMAIL_HOST_USER,
        [email],
    )
    return success_api_response(
        {"result": "Ok, confirmation email has been sent"})
Пример #5
0
    async def _resolve_message(self, message):
        payload = None

        try:
            message = utils.parse_data(message)
            if message.get('ticker', None) is not None:
                payload = self.__assume_tick(message)
        except Exception as e:
            Logger.log_error(e)

        finally:
            return payload
Пример #6
0
    async def __post(self, url, params=None):
        try:
            request = pd.Series(data=[url], index=['request'])
            request.name = datetime.datetime.now()
            self.__timeline = self.__timeline.append(request)

            async with aiohttp.ClientSession() as session:
                async with session.post(url, data=params) as resp:
                    text = await resp.text()
                    return utils.parse_data(text)
        except Exception as e:
            Logger.log_error(e)
Пример #7
0
    async def _resolve_message(self, message):
        reaction = None

        try:
            message = utils.parse_data(message)
            if message.get('type', None) == 'ticker':
                reaction = self.__assume_tick(message)
        except Exception as e:
            Logger.log_error(e)

        finally:
            return reaction
Пример #8
0
    async def _resolve_message(self, message):
        payload = None

        try:
            message = utils.parse_data(message)
            if type(message) == dict:
                self.__assume_channel(message)
            elif type(message) == list:
                payload = self.__assume_tick(message)
        except Exception as e:
            Logger.log_error(e)

        finally:
            return payload
Пример #9
0
    async def _resolve_message(self, message):
        reaction = None

        try:
            message = utils.parse_data(message)
            if message.get('e', None) == 'ping':
                await self.ws_send({'e': 'pong'})
            elif message.get('e', None) == 'tick':
                reaction = self.__assume_tick(message)

        except Exception as e:
            Logger.log_error(e)

        finally:
            return reaction
Пример #10
0
def login(request: HttpRequest):
    """Handle requests which are to obtain jwt token

    [route]: /auth/

    [method]: POST
    """
    data: dict = parse_data(request)
    if not data or data.get("username") is None or data.get(
            "password") is None:
        return failed_api_response(StatusCode.INVALID_REQUEST_ARGUMENT,
                                   "Bad login info")
    user = authenticate(username=data["username"], password=data["password"])
    if not user:
        return failed_api_response(StatusCode.INVALID_USERNAME_OR_PASSWORD,
                                   "The username or password is incorrect")
    return success_api_response(
        {"access_token": generate_access_token(user.id)})
Пример #11
0
    async def _resolve_message(self, message):
        payload = None

        try:
            message = utils.parse_data(gzip.decompress(message).decode('utf8'))

            if message is not None:
                if 'ping' in message:
                    await self.ws_send({'pong': message['ping']})
                elif 'subbed' in message:
                    self.__assume_channel(message)
                elif 'tick' in message:
                    payload = self.__assume_tick(message)
        except Exception as e:
            Logger.log_error(e)

        finally:
            return payload
Пример #12
0
    async def _resolve_message(self, message):
        payload = None

        try:
            message = utils.parse_data(message)

            if message.get('I', None) in self.__callbacks:
                await self.__callbacks[message['I']](message)
                del self.__callbacks[message['I']]
            elif len(message.get('M', [])) > 0:
                if message['M'][0]['M'] == 'uE':
                    await self.__assume_order_book_update(message['M'][0])
                elif message['M'][0]['M'] == 'uL':
                    payload = await self.__assume_tick_package(message['M'][0])
        except Exception as e:
            Logger.log_error(e)

        finally:
            return payload
Пример #13
0
    async def listen(self):
        try:
            async for message in self.__websocket:
                if isinstance(self.__websocket, web.WebSocketResponse):
                    if message.type == WSMsgType.TEXT:
                        if message.data == 'close':
                            message = None
                        else:
                            message = message.data
                    elif msg.type == WSMsgType.ERROR:
                        message = None

                if message is not None:
                    message = utils.parse_data(message)
                    if message.get('type', None) is not None:
                        Logger.log_info('message')
                        Logger.log_info(message)

                    if (message.get('type', None) == 'service'
                            and message.get('action', None) is not None):
                        Logger.log_info('action accepted, trying to pass')
                        result = await self.execute(
                                message.get('action', None),
                                *message.get('args', []),
                                **message.get('kwargs', {}),)
                        response = {
                                'type':'service',
                                'id':message['id'],
                                'action_result':utils.pandas_to_dict(result),}
                        Logger.log_info('action resolved, trying to response')
                        await self.on_data(response)
                    else:
                        await self.push(message)
        except Exception as e:
            Logger.log_error(e)

        finally:
            await self.close()
Пример #14
0
def create_user(request: HttpRequest):
    """create user

    [route]: /auth/create

    [method]: POST
    """
    user_info: dict = parse_data(request)
    if not user_info:
        return failed_api_response(StatusCode.BAD_REQUEST, "Bad request")
    username = user_info.get("username")
    password = user_info.get("password")
    email = user_info.get("email")
    captcha = user_info.get("captcha")
    verified_form = VerifiedUserForm({
        "username": username,
        "password": password,
        "email": email,
        "captcha": captcha
    })
    if not verified_form.is_valid():
        return failed_api_response(StatusCode.INVALID_REQUEST_ARGUMENT,
                                   "Bad information")
    verified_captcha = cache.get(email)
    delattr(cache, email)
    if captcha != verified_captcha:
        return failed_api_response(StatusCode.INVALID_CAPTCHA,
                                   "Captcha not matched")
    if UserModel.objects.filter(username=username).exists():
        return failed_api_response(StatusCode.ITEM_ALREADY_EXISTS,
                                   "Username conflicted")

    new_user = UserModel.objects.create_user(username=username,
                                             password=password,
                                             email=email)

    return success_api_response({"id": new_user.id})
Пример #15
0
 def __decompress_data(self, data):
     return utils.parse_data(zlib.decompress(
         base64.b64decode(data),
         wbits=-15,).decode('utf8'))
Пример #16
0
 async def _resolve_message(self, message):
     try:
         return self.__assume_tick(utils.parse_data(message))
     except Exception as e:
         Logger.log_error(e)