Esempio n. 1
0
    def test_write2(self):
        res = Response()
        res.charset = None
        res.write(u'foo')

        self.assertEqual(res.body, u'foo')
        self.assertEqual(res.charset, 'utf-8')
Esempio n. 2
0
def establish_auth_session(request: webapp2.Request,
                           response: webapp2.Response) -> None:
    """Sets login cookies to maintain a user's sign-in session.

    Args:
        request: webapp2.Request. The request with the authorization to begin a
            new session.
        response: webapp2.Response. The response to establish the new session
            upon.
    """
    claims = _get_auth_claims_from_session_cookie(_get_session_cookie(request))

    # If the request already contains a valid session cookie, then there's no
    # action necessary; the session is already established.
    if claims is not None:
        return

    fresh_cookie = firebase_auth.create_session_cookie(
        _get_id_token(request), feconf.FIREBASE_SESSION_COOKIE_MAX_AGE)

    response.set_cookie(
        constants.FIREBASE_AUTH_SESSION_COOKIE_NAME,
        value=fresh_cookie,
        max_age=feconf.FIREBASE_SESSION_COOKIE_MAX_AGE,
        overwrite=True,
        # Toggles https vs http. The production server uses https, but the local
        # developement server uses http.
        secure=(not constants.EMULATOR_MODE),
        # Using the HttpOnly flag when generating a cookie helps mitigate the
        # risk of client side script accessing the protected cookie (if the
        # browser supports it).
        # Learn more: https://owasp.org/www-community/HttpOnly.
        httponly=True)
Esempio n. 3
0
def destroy_auth_session(response: webapp2.Response) -> None:
    """Clears login cookies from the given response headers.

    Args:
        response: webapp2.Response. Response to clear the cookies from.
    """
    response.delete_cookie(constants.FIREBASE_AUTH_SESSION_COOKIE_NAME)
Esempio n. 4
0
 def get(self, name, ip, password):
     if name == '' or ip == '' or password == '':
         return Response('Empty ... no information provided.')
     elif password != PASSWORD:
         return Response('Error ... Authentication error.')
     else:
         with open(os.path.join(ROOT, name), 'w') as fd:
             fd.write(ip + ' @ ' + strftime("%Y-%m-%d %H:%M:%S"))
         return Response('Success ... IP address stored: %s' % ip)
Esempio n. 5
0
 def _dispatcher(router, req, res):
     returned = router.default_dispatcher(req, res)
     if isinstance(returned, basestring):
         return Response(returned)
     elif isinstance(returned, Template):
         returned = router.tenv.get_template(
             returned.tfile).render(**returned.kwargs)
         return Response(returned)
     elif isinstance(returned, tuple):
         return Response(*returned)
     else:
         return dumps(returned)
Esempio n. 6
0
 def wrapper(parent, *args, **kwargs):
     logging.info("appIdSecurity: Checking security...")
     request = parent.request_state
     result = Response()
     try:
         checkCallerApplicationId(request, allowedAppIds)
         result = view_func(parent, *args, **kwargs)
         return result
     except SecurityError as se:
         result.status = 403
         result.body = se.value
         return result
Esempio n. 7
0
 def wrapper(parent, *args, **kwargs):
     logging.info("appIdSecurity: Checking security...")
     request = parent.request_state
     result = Response()
     try:
         checkCallerApplicationId(request, allowedAppIds)
         result = view_func(parent, *args, **kwargs)
         return result
     except SecurityError as se:
         result.status = 403
         result.body = se.value
         return result
Esempio n. 8
0
 def get(self):
     items = os.listdir(ROOT)
     items.sort()
     text = ''
     for item in items:
         if item in ['.gitignore', 'README']:
             continue
         item = os.path.join(ROOT, item)
         if not os.path.isfile(item):
             return Response("Error ... %s is not a file." % item)
         else:
             with open(item) as fd:
                 text = text + os.path.basename(item) + ' @ ' + fd.read() + '\n'
     res = Response(text)
     res.headers = [('Content-Type', 'text/plain; charset=utf8')]
     return res
Esempio n. 9
0
 def exec_handler(self, body=None):
     """Used by each test to execute the minimal Testhandler."""
     h = self.MyTestHandler()
     h.request = Request.blank('/test_rpc/')
     h.response = Response()
     h.request.body = body
     h.post()
     return (h.response.status_int, h.response.body)
Esempio n. 10
0
 def get(self):
     items = os.listdir(ROOT)
     items.sort()
     text = ''
     for item in items:
         if item in ['.gitignore', 'README']:
             continue
         item = os.path.join(ROOT, item)
         if not os.path.isfile(item):
             return Response("Error ... %s is not a file." % item)
         else:
             with open(item) as fd:
                 text = text + os.path.basename(
                     item) + ' @ ' + fd.read() + '\n'
     res = Response(text)
     res.headers = [('Content-Type', 'text/plain; charset=utf8')]
     return res
Esempio n. 11
0
def getResponse(text, chat_id):
    return Response(status_int=200,
                    body={
                        'method': 'sendMessage',
                        'chat_id': chat_id,
                        'text': "I need a number or a photo",
                        content_type: 'application/json'
                    })
Esempio n. 12
0
 def setUp(self):
     super(TemplateRequestHandlerTest, self).setUp()
     self.request = Request.blank('/',
                                  environ={
                                      'CONTENT_TYPE':
                                      'text/html; charset=ISO-8859-4',
                                  })
     self.response = Response()
     self.testapp.app.set_globals(app=self.testapp.app,
                                  request=self.request)
    def request_handler_wrapper(request, *args, **kwargs):
        from webapp2 import Request, Response, WSGIApplication
        from django.http import HttpResponse

        class Route:
            handler_method = request.method.lower()

        req = Request(request.environ)
        req.route = Route()
        req.route_args = args
        req.route_kwargs = kwargs
        req.app = WSGIApplication()
        response = Response()
        view_func = request_handler(req, response)
        view_func.dispatch()

        django_response = HttpResponse(response.body, status=int(str(response.status).split(" ")[0]))
        for header, value in response.headers.iteritems():
            django_response[header] = value

        return django_response
Esempio n. 14
0
def messagehandler(request, *args, **kwargs):
	update = telegram.Update.de_json(json.loads(request.body))
	chat_id = update.message.chat.id
	text = update.message.text.encode('utf-8')

	logging.info("Received {} from {}".format(text, chat_id))
	try:
		answer = json.loads(urlfetch.fetch(url = PLATFORM_URL.format(chat_id, text), method = "GET").content)
	except:
		return ""
	answer_text = answer.get('response')
	answer_buttons = answer.get('buttons')
	logging.info("Got {}".format(answer))
	if answer_text:
		body = {'method': 'sendMessage', 'chat_id' : chat_id, 'text' : answer_text}
		if answer_buttons:
			body['reply_markup'] = {'keyboard' : [[str(button) for button in json.loads(answer_buttons)]], 'resize_keyboard' : True}
		body = json.dumps(body)
	else:
		body = None
	logging.info('Body is {}'.format(body))
	return Response(status_int = 200, body = body, content_type = 'application/json')
Esempio n. 15
0
 def process(self, handler, result):
     handler._clear_redirect()
     handler.response = Response(result)
     return handler.response
Esempio n. 16
0
def messagehandler(dbSession, request, *args, **kwargs):
    update = telegram.Update.de_json(json.loads(request.body))
    chat_id = update.message.chat.id
    text = update.message.text.encode('utf-8')
    photos = update.message.photo
    user = dbSession.query(User).filter(User.userid == chat_id).first()
    if not user:
        user = User(userid=chat_id)
        dbSession.add(user)

    n_clusters = None

    if photos:
        photo_id = max(photos, lambda x: x.width).photo_id
        if user.n_clusters:
            # give photo
            photo_path = json.loads(
                urlfetch.fetch(url="https://api.telegram.org/getFile",
                               payload=json.dumps({'file_id': photo_id}),
                               method='POST',
                               headers={
                                   "Content-Type": "application/json"
                               }).content)['file_path']
            photo = open("https://api.telegram.org/file/bot{}/{}".format(
                TELEGRAM_API_TOKEN, photo_path))
            orig_n_colors, reduced_photo = reduce_colors(photo, n_clusters)
            body = {'method' : 'sendPhoto',
              'chat_id' : chat_id,
              'photo' : "".join(multipart_encode(reduced_photo)[0]),
              'caption' : "The photo had {} colors, but I reduced it to just {}, and it looks almost the same. Amazing me!"\
               .format(orig_n_colors, n_clusters)}
            return Response(status_int=200, body=body, headers=to_post[1])
        else:
            # update photo
            # get number
            user.photolink = photo_id
            return getResponse("Give a number", chat_id)
    elif text:
        if not set(text).issubset('1234567890'):
            # not recognized
            return getResponse("Give me a number or a photo", chat_id)
        elif int(text) < 2:
            # not recognized
            return getResponse("Give me a number or a photo", chat_id)
        else:
            n_clusters = int(text)
            if user.photolink:
                # give photo
                photo_path = json.loads(
                    urlfetch.fetch(url="https://api.telegram.org/getFile",
                                   payload=json.dumps({'file_id': photo_id}),
                                   method='POST',
                                   headers={
                                       "Content-Type": "application/json"
                                   }).content)['file_path']
                photo = open("https://api.telegram.org/file/bot{}/{}".format(
                    TELEGRAM_API_TOKEN, photo_path))
                orig_n_colors, reduced_photo = reduce_colors(photo, n_clusters)
                encoded, headers = multipart_encode(reduced_photo)[0]
                body = {'method' : 'sendPhoto',
                 'chat_id' : chat_id,
                 'photo' : "".join(encoded),
                 'caption' : "The photo had {} colors, but I reduced it to just {}, and it looks almost the same. Amazing me!"\
                  .format(orig_n_colors, n_clusters)}
                return Response(status_int=200,
                                body=body,
                                headers=headers,
                                content_type='multipart/form-data')
            else:
                # update n_clusters
                # get photo
                user.n_clusters = n_clusters
                return getResponse("Give me a number", chat_id)
    else:
        # not recognized
        return getResponse("Give me a number or a photo", chat_id)
Esempio n. 17
0
 def get(self):
     return Response(str(self.request.remote_addr))
Esempio n. 18
0
 def test_http_status_message(self):
     self.assertEqual(Response.http_status_message(404), 'Not Found')
     self.assertEqual(Response.http_status_message(500), 'Internal Server Error')
     self.assertRaises(KeyError, Response.http_status_message, 9999)
Esempio n. 19
0
 def get(self):
     return Response("Not Found")
Esempio n. 20
0
    def test_write(self):
        var_1 = NoStringOrUnicodeConversion()
        var_2 = StringConversion()
        var_3 = UnicodeConversion()

        res = Response()
        res.write(var_1)
        res.write(var_2)
        res.write(var_3)
        self.assertEqual(res.body, '%rfoobar' % var_1)

        res = Response()
        res.write(var_1)
        res.write(var_3)
        res.write(var_2)
        self.assertEqual(res.body, '%rbarfoo' % var_1)

        res = Response()
        res.write(var_2)
        res.write(var_1)
        res.write(var_3)
        self.assertEqual(res.body, 'foo%rbar' % var_1)

        res = Response()
        res.write(var_2)
        res.write(var_3)
        res.write(var_1)
        self.assertEqual(res.body, 'foobar%r' % var_1)

        res = Response()
        res.write(var_3)
        res.write(var_1)
        res.write(var_2)
        self.assertEqual(res.body, 'bar%rfoo' % var_1)

        res = Response()
        res.write(var_3)
        res.write(var_2)
        res.write(var_1)
        self.assertEqual(res.body, 'barfoo%r' % var_1)
Esempio n. 21
0
 def setUp(self):
     """Set up the test with a simple TestHandler."""
     h = self.MyTestHandler()
     h.request = Request.blank('/rpc/')
     h.response = Response()
     self.handler = h
Esempio n. 22
0
                                      controller.global_views[rv.state])

        except:
            logging.info('Mako Render Error.', exc_info=True)
            c.error = "Oops! There's an error."
            rv = formatted_render(_format, '503_generic.mako')
            # rv = exceptions.html_error_template().render()
            resp.set_status(503)

        rv = resp.write(rv)

    elif isinstance(rv, (dict, list)):
        rv = resp.write(json.dumps(rv))

    elif isinstance(rv, tuple):
        rv = Response(*rv)

    else:
        rv = resp.write(rv)

    return rv


def redirect(uri, permanent=False, code=None):
    """Issues an HTTP redirect to the given relative URI.

    This won't stop code execution unless **abort** is True. A common
    practice is to return when calling this method::

        return redirect('/some-path')