示例#1
0
    def __call__(self, req, resp, project):
        file_path = os.path.abspath(BASE_PATH + "/" + project)

        index_path = file_path + "/index.html"
        index_path_alternate = file_path + "/index.htm"

        if not file_path.startswith(BASE_PATH):
            raise falcon.HTTPBadRequest(description="Invalid request")

        if os.path.isfile(index_path):
            raise falcon.HTTPMovedPermanently(req.uri + "/index.html")
        elif os.path.isfile(index_path_alternate):
            raise falcon.HTTPMovedPermanently(req.uri + "/index.htm")
        else:
            raise falcon.HTTPNotFound()
示例#2
0
    def on_get(self, req, res, kuis_id, user_id):
        if not "facebookexternalhit/1.1" in req.user_agent:
            raise falcon.HTTPMovedPermanently(
                "https://kuis.zannete.com/kuis/{}".format(kuis_id))

        try:
            cred = credentials.Certificate(
                os.path.join(os.getcwd(), "serviceAccountKey.json"))
            firebase_app = firebase_admin.initialize_app(
                cred, {"databaseURL": "https://kuis-zannete.firebaseio.com/"})
        except ValueError:
            print("Firebase has been initialized")

        jawaban_ref = db.reference("/jawaban/{}/{}".format(kuis_id, user_id))
        url_jawaban = jawaban_ref.get()

        kuis_ref = db.reference("/kuis/{}".format(kuis_id))
        judul_kuis = kuis_ref.child("judul").get()

        res.body = """
    <html>
      <head>
        <meta property="og:url" content="https://api.zannete.com/display/{kuis_id}/{user_id}" />
        <meta property="og:type" content="article" />
        <meta property="og:title" content="{judul}" />
        <meta property="og:description" content="Ayo bermain kuis di Zannete. Kunjungi websitenya, mainkan kuisnya, bagikan dengan teman Anda." />
        <meta property="og:image" content="{url_image}" />
        <meta property="og:image:width" content="1200"/>
        <meta property="og:image:height" content="800"/>
      </head>
    </html>
    """.format(kuis_id=kuis_id,
               user_id=user_id,
               judul=judul_kuis,
               url_image=url_jawaban)
示例#3
0
 def on_get(self, req, resp, shorturl):
     short = 's.edyd.cn/' + shorturl
     if shorturl:
         data = dbutils.redirect(short)
         raw = str(data['raw'])
         resp.status = falcon.HTTP_301
         raise falcon.HTTPMovedPermanently(raw)
示例#4
0
    def on_get(self, req, resp):
        data = req.get_param('data', required=True)
        version = req.get_param('version', required=False, default=1)
        resp_format = req.get_param('format', required=False)

        image = self.build_image(data, version=version)
        logging.debug(image)

        buf = StringIO.StringIO()
        image.save(buf, 'jpeg')
        buf.seek(0)

        if resp_format == 'image':
            resp.body = buf.getvalue()
            resp.content_type = 'image/jpeg'
            return

        url = self.upload_file('qrcodes/{}.jpeg'.format(data), buf,
                               'image/jpeg')

        if resp_format == 'json':
            resp.body = json.dumps({'url': url, 'content_type': 'jpeg'})
            resp.content_type = 'application/json'
            resp.status = falcon.HTTP_200

        else:
            raise falcon.HTTPMovedPermanently(location=url)
示例#5
0
    def on_get(self, req, resp):

        if self.https and req.scheme.lower() == 'http':
            raise falcon.HTTPMovedPermanently(
                req.url.replace('http', 'https', 1)
            )
        if req.params.get('key', None) not in self.keydict:
            raise falcon.HTTPUnauthorized()
示例#6
0
 def on_get(self, req, resp):
     feed_info = self.session.query(FeedInfo).first()
     fetched_at = ''
     if feed_info.feed_last_fetched_at:
         fetched_at = arrow.get(
             feed_info.feed_last_fetched_at).format('YYYY/MM/DD HH:MM')
     shield_url = BASE_SHIELD_URL.format(subject='Last fetch',
                                         title=fetched_at,
                                         color='yellow')
     raise falcon.HTTPMovedPermanently(shield_url)
示例#7
0
 def on_get(self, req, resp):
     try:
         data = create_signer.loads(req.params["token"])
         db.add_user(**data)
         req.context["user"] = data["username"]
         resp.body = pages.message.account_activated()
         resp.content_type = "text/html; charset=utf-8"
     except (BadSignature, SignatureExpired, KeyError):
         # TODO log secutiry issues
         falcon.HTTPMovedPermanently("/")  # TODO redirect to error page
示例#8
0
 def on_get(self, req, resp):
     if "user" not in req.context or not req.context["user"]:
         try:
             db.delete_user(
                 db.get_user_token("deletions", req.params["token"]))
             resp.body = pages.message.account_deleted()
         except (BadSignature, SignatureExpired, KeyError):
             raise falcon.HTTPMovedPermanently("/")
     else:
         resp.body = pages.message.cannot_delete_when_logged_in()
     resp.content_type = "text/html; charset=utf-8"
示例#9
0
 def on_get(self, req, resp):
     if "user" in req.context and req.context["user"]:
         user = req.context["user"]
         send.link(db.get_user_email(user), "Delete Account Link",
                   "Click the link to permanently delete your account",
                   "/account/delete/finish",
                   str(db.add_token("deletions", user)))
         req.context["user"] = ""  # Log user out
         resp.body = pages.message.deletion_link_sent(user)
         resp.content_type = "text/html; charset=utf-8"
     else:
         raise falcon.HTTPMovedPermanently("/")
示例#10
0
 def process_resource(self, req, resp, resource, params):
     super(CommonMiddleware, self).process_resource(
         req, resp, resource, params)
     # Avoid pylint error.
     system_config = dict(self.config)[ConfigKey.CONF_KEY_SYSTEM]
     # API Check.
     if re.match('/api/', req.path) != None:
         return
     # Login check.
     try:
         session_id = req.get_cookie_values('session_id')[0]
         self.logger.debug("Session ID:{0}".format(session_id))
     except:
         cookie_max_age = system_config[ConfigKey.CONF_KEY_SYSTEM_COOKIE][ConfigKey.CONF_KEY_SYSTEM_COOKIE_MAX_AGE]
         session_id = str(uuid.uuid4())
         resp.set_cookie('session_id', session_id,
                         max_age=cookie_max_age, path='/', secure=False)
         resp.status = falcon.HTTP_200
         self.logger.debug(
             "Set cookie, Session ID:{0}".format(session_id))
         raise falcon.HTTPMovedPermanently('/login')
     try:
         session_service = SessionUtility.get_session_service()
         session_config = session_service.get_config()
         session = session_service.get_session(session_id)
         diff = (datetime.now() -
                 session[SessionKey.SESSION_KEY_TIMESTAMP]).seconds
         if session_config[ConfigKey.CONF_KEY_SYSTEM_SESSION_TIMEOUT] - diff < 0:
             self.logger.debug("session timeout: {0}".format(session_id))
             session_service.remove_session(session_id)
             raise falcon.HTTPMovedPermanently('/login')
     except KeyError:
         self.logger.debug("session error.")
         raise falcon.HTTPMovedPermanently('/login')
     except TypeError:
         self.logger.debug("request path: {0}".format(req.path))
         if req.path != '/login':
             raise falcon.HTTPMovedPermanently('/login')
示例#11
0
文件: handler.py 项目: shitara/core
    def on_request(self, method, request, response, **kwargs):
        try:
            locale = Locale(
                request.headers.get('Accept-Language'.upper()) or 'en')

            request.params.update(kwargs)

            request, user, session = validator.authenticate(
                self.session, request, response)
            request = validator.parameters(self.meta['request'], request,
                                           method)

            data = LuaRuntime(_=locale.gettext).execute(
                create_path(self.path, 'main.lua'),
                modules=[create_path(v) for v in self.meta['dependency']],
                properties=dict(
                    models=models,
                    errors={
                        i: errors[i]
                        for i in (self.meta.get('errors') or [])
                    } if 'errors' in self.meta else errors,
                ),
                request=type(
                    '', (object, ),
                    dict(
                        __getattr__=lambda self, name: getattr(request, name),
                        meta=self.meta,
                        user=user,
                        session=session,
                    ))(),
                response=type(
                    '', (object, ),
                    dict(
                        __getattr__=lambda self, name: getattr(response, name),
                        redirect=lambda self, location: (
                            (_ for _ in
                             ()).throw(falcon.HTTPMovedPermanently(location))),
                        broadcast=lambda self, name, value, option=dict():
                        (plugin.responses['broadcast']
                         (renderer.render(locale, self.meta['broadcast'][name],
                                          value), option)),
                        meta=self.meta,
                    ))(),
            )
            renderer.response(request, response, locale, self.meta['response'],
                              dict(data))
        except falcon.HTTPStatus as e:
            raise e
        except Exception as e:
            return self.on_exception(e, request, response)
示例#12
0
    def process_request(self, req, resp):
        if self.skips(req) or self.is_secure(req):
            return

        xfp = req.get_header('X-FORWARDED-PROTO')
        if xfp and xfp.lower() == 'https':
            return

        if req.url.startswith('http://'):
            url = req.url.replace('http://', 'https://', 1)
            if self.permanent:
                raise falcon.HTTPMovedPermanently(url)
            else:
                raise falcon.HTTPFound(url)
示例#13
0
 def _handle_no_time_left(self, name, res, suffix, in_round1, account):
     c = self.conn.cursor()
     c.execute(
         'UPDATE testers SET round{}_solved={}, round{}=1 WHERE name="{}"'.
         format(suffix, account['idx'], suffix, name))
     self.conn.commit()
     if in_round1:
         # go to round 2
         raise falcon.HTTPMovedPermanently('%s:%s/mode?name=%s' %
                                           (LOCATION, PORT, name))
     else:
         # say thanks
         res.body = message_body.format(
             'You finished the test. Thanks! Your balance is %.2f' %
             account['earned'])
示例#14
0
    def on_get(self, req, rep, alias):
        """

        Parameters:
          req (Request): HTTP Request Object
          rep (Response): HTTP Response Object
          alias (str): Alias of Well-Known OOBI

        """

        p = Path(self.oobiDir, alias)
        if not p.exists():
            raise falcon.HTTPBadRequest(title="Unknown well known")

        url = p.open().read()
        raise falcon.HTTPMovedPermanently(location=url)
示例#15
0
 def on_get_redirect(self, req, resp, encoded_id):
     self.refresh()
     if encoded_id not in ShortenedURL.id2url:
         # Bad request
         resp.status = falcon.HTTP_400
         resp.content_type = 'text/html'
         resp.body = f'''
         {HTML_PAGE_HEADER}
         <p> Bad Request: {encoded_id} does not exist </p>
         {HTML_PAGE_FOOTER}
         '''
     else:
         ShortenedURL.id2url[encoded_id]['views'] += 1
         ShortenedURL.id2url[encoded_id]['accessed_time'] = datetime.now(
         ).isoformat()
         # write the change to disk
         self.sync2disk()
         raise falcon.HTTPMovedPermanently(
             ShortenedURL.id2url[encoded_id]['url'])
示例#16
0
    def process_request(self, request, response):
        if request.host in ["localhost", "127.0.0.1"]:
            return

        if request.scheme.lower() == 'https':
            return

        xfp = request.get_header('X-FORWARDED-PROTO')
        if xfp and xfp.lower() == 'https':
            return

        forwarded = request.get_header('FORWARDED')
        if forwarded:
            first, __, __ = forwarded.partition(',')

            match = _FORWARDED_PROTO_RE.search(first)
            if match and match.group(1).lower() == 'https':
                return

        site_https = request.uri.replace("http://", "https://", 1)
        raise falcon.HTTPMovedPermanently(site_https)
示例#17
0
 def on_get(self, req, resp, user_id):
     """Fetch and serve avatar for requested user."""
     if not settings.user.allow_avatar_capability:
         raise ResourceNotAvailableError()
     user = get_user(user_id)
     if user.avatar_href:
         # redirect to source
         raise falcon.HTTPMovedPermanently(user.avatar_href)
     elif user.avatar_binary:
         # serve binary
         resp.content_type = user.avatar_binary.content_type
         avatar_stream = user.avatar_binary.gridout.read()
         resp.stream = io.BytesIO(avatar_stream)
         resp.stream_len = len(avatar_stream)
     else:
         # serve default avatar image
         resp.content_type = 'image/png'
         avatar_path = os.path.abspath(
             os.path.join(os.path.dirname(os.path.abspath(__file__)), '..',
                          'static/default-avatar.png'))
         resp.stream = open(avatar_path, 'rb')
         resp.stream_len = os.path.getsize(avatar_path)
示例#18
0
    def __call__(self, req, resp):
        req_path = req.path
        file_path = req_path.replace(self.api_url, "", 1)
        """ add index.html """
        if not file_path:
            """ redirect process """
            redirect_path = req_path + "/index.html"
            raise falcon.HTTPMovedPermanently(redirect_path)

        filepath = self.src_path + file_path
        if self.api_url == "/":
            filepath = self.src_path + "/" + file_path

        if os.path.isfile(filepath):

            content_type = mimetypes.guess_type(filepath)[0]
            resp.status = falcon.HTTP_200

            file_type = ""
            if content_type:
                content_type_list = content_type.split('/')
                file_type = content_type_list[0]
                resp.content_type = content_type

            if file_type == 'image':
                resp.stream = open(filepath, 'rb')
                resp.stream_len = os.path.getsize(filepath)
            elif file_type == 'text':
                with open(filepath, 'r') as text_file:
                    text_html = text_file.read()
                    text_html = self.replace_static_tag(text_html)
                    resp.body = text_html
            else:
                with open(filepath, 'r') as text_file:
                    text_html = text_file.read()
                    resp.body = text_html
        else:
            resp.status = falcon.HTTP_404
示例#19
0
 def on_get(self, req, resp):
     try:
         resp.body = pages.confirm_delete_account()
         resp.content_type = "text/html; charset=utf-8"
     except KeyError:
         raise falcon.HTTPMovedPermanently("/")
示例#20
0
 def on_get(self, req, resp):
     raise falcon.HTTPMovedPermanently('/moved/perm')
示例#21
0
 def on_get(self, req, resp):
     raise falcon.HTTPMovedPermanently('/moved/perm',
                                       headers={'foo': 'bar'})
示例#22
0
 def on_get(self, req, resp):
     raise falcon.HTTPMovedPermanently(self.u)
示例#23
0
 def on_get(self, req, resp):
     """Redirect to '/index.html'."""
     raise falcon.HTTPMovedPermanently('/index.html')
示例#24
0
 def on_get(self, req, resp):
     feed_info = self.session.query(FeedInfo).first()
     shield_url = BASE_SHIELD_URL.format(subject='GTFS',
                                         title=feed_info.feed_version,
                                         color='green')
     raise falcon.HTTPMovedPermanently(shield_url)
示例#25
0
	def on_get_forgot(self, req, resp):
		# set_html_template(resp, falcon.HTTP_400, "weak_passwd/forgot.html")
		# def on_post_forgot(self, req, resp):
		# form_data = req.get_media()

		roll_no = None
		dob = None
		otp = None
		new_passwd = None

		if "roll_no" in req.params:
			roll_no = req.params["roll_no"]
		
		if "dob" in req.params:
			dob = req.params["dob"]

		if "otp" in req.params:
			otp = req.params["otp"]

		if "new_password" in req.params:
			new_passwd = req.params["new_password"]

		# print ("roll_no:", roll_no)
		# print ("dob:", dob)
		# print ("otp:", otp)
		# print ("new_passwd:", new_passwd)

		chall = "ch06"

		if is_integer(otp) and new_passwd:
			if is_integer(roll_no) and is_date(dob):
				if verify_otp(roll_no, otp, chall):
					if reset_passwd(roll_no, new_passwd, chall):
						raise falcon.HTTPMovedPermanently(location = "/challenges/06?reset=success")

					else:
						set_html_template(resp, falcon.HTTP_200, "weak_passwd/login.html", {
							"message": "Password reset failed! Please try again in some time...",
							"color": "red"
						})

				else:
					set_html_template(resp, falcon.HTTP_200, "weak_passwd/forgot.html", {
						"message": "Incorrect OTP"
					})

			else:
				set_html_template(resp, falcon.HTTP_200, "weak_passwd/forgot.html", {
					"message": "Missing/Invalid roll_no/dob"
				})

		else:
			if is_integer(roll_no) and is_date(dob):
				# Validate the DOB and set the OTP
				if validate_dob(roll_no, dob, "ch01") and set_otp(roll_no, chall):
					set_html_template(resp, falcon.HTTP_200, "weak_passwd/forgot.html", {
						"otp": True,
						"roll_no": roll_no,
						"dob": dob
					})

				else:
					set_html_template(resp, falcon.HTTP_200, "weak_passwd/forgot.html", {
						"message": "Invalid DOB",
						"color": "red"
					})

			elif (roll_no and not dob) or (not roll_no and dob):
				set_html_template(resp, falcon.HTTP_200, "weak_passwd/forgot.html", {
					"message": "Missing/Invalid roll_no/dob"
				})

			else:
				set_html_template(resp, falcon.HTTP_200, "weak_passwd/forgot.html")
示例#26
0
 def on_get(self, req, resp):
     raise falcon.HTTPMovedPermanently('/index.html')
示例#27
0
 def on_get_index(self, req: falcon.Request, resp: falcon.Response) -> None:
     raise falcon.HTTPMovedPermanently("/index.html")
示例#28
0
 def on_get(self, req, resp, token):
     req.context["user"] = db.get_token_user("logins", token)
     # TODO log security red flags, or at least display to user
     raise falcon.HTTPMovedPermanently("/")