예제 #1
0
    def post(self, action):
        """POST is used when authenticating via the mobile application."""
        if not ServerEnvironment.IsDevBox():
            raise web.HTTPError(403, _FAKE_AUTHORIZATION_FORBIDDEN)

        user_dict, ident_dict, device_dict = yield gen.Task(
            self._StartAuthViewfinder, action)

        # Finish user authentication.
        self._AuthUser(user_dict, ident_dict, device_dict)
예제 #2
0
def StartServer(serve_webapp=True, serve_static_web=True, serve_admin=True):
    """Initialize the datastore and operation manager with the viewfinder schema. This typically
  verifies the schema. If the schema does not yet exist, it is created.

  Defines settings dictionary and sets up main application with list of handlers.
  """
    client = db_client.DBClient.Instance()

    settings = {
        'gzip':
        True,
        'login_url':
        '/',
        'admin_login_url':
        '/admin/otp',
        'domain':
        options.options.domain,
        'server_version':
        options.options.server_version,
        'cookie_secret':
        secrets.GetSecret('cookie_secret'),
        'facebook_api_key':
        secrets.GetSecret('facebook_api_key'),
        'facebook_secret':
        secrets.GetSecret('facebook_secret'),
        'google_client_id':
        secrets.GetSecret('google_client_id'),
        'google_client_secret':
        secrets.GetSecret('google_client_secret'),
        'google_client_mobile_id':
        secrets.GetSecret('google_client_mobile_id'),
        'google_client_mobile_secret':
        secrets.GetSecret('google_client_mobile_secret'),
        'template_path':
        ResourcesManager.Instance().template_path,
        'ui_modules':
        uimodules,
        'xsrf_cookies':
        options.options.enable_xsrf,
        'debug':
        options.options.server_debug,
        'static_path':
        ResourcesManager.Instance().static_path,
    }

    if options.options.log_file_prefix:
        settings['logs_dir'] = os.path.dirname(options.options.log_file_prefix)

    # Configure metrics uploading.
    if options.options.upload_metrics:
        for interval in metric.METRIC_INTERVALS:
            metric.Metric.StartMetricUpload(client,
                                            metric.DEFAULT_CLUSTER_NAME,
                                            interval)

    # Setup application and SSL HTTP server.
    handlers = deepcopy(COMMON_HANDLERS)
    if serve_webapp:
        # Configure web application handlers.
        webapp_handlers = deepcopy(WEBAPP_HANDLERS)

        # Initialize the file object store if specified.
        obj_store = ObjectStore.GetInstance(ObjectStore.PHOTO)
        settings['obj_store'] = obj_store
        if options.options.fileobjstore:
            for store_name, content_type in ((ObjectStore.PHOTO,
                                              r'image/jpeg'),
                                             (ObjectStore.USER_LOG,
                                              r'text/plain'),
                                             (ObjectStore.USER_ZIPS,
                                              r'application/zip')):
                webapp_handlers.append(
                    (r'/fileobjstore/%s/(.*)' % store_name,
                     file_object_store.FileObjectStoreHandler, {
                         'storename': store_name,
                         'contenttype': content_type
                     }))

        if ServerEnvironment.IsDevBox():
            webapp_handlers.append((r'/(link|login|register)/fakeviewfinder',
                                    auth_viewfinder.FakeAuthViewfinderHandler))
            # Set the testing directories.
            if options.options.testing_path is not None:
                webapp_handlers.append(
                    (r'/testing/hook/(.*)', test_hook.TestHookHandler))
                webapp_handlers.append(
                    (r'/testing/static/(.*)', web.StaticFileHandler, {
                        'path': '%s' % options.options.testing_path
                    }))

        handlers.extend(webapp_handlers)

    if serve_static_web:
        # Configure static web handlers.
        static_web_handlers = deepcopy(STATIC_WEB_HANDLERS)
        handlers.extend(static_web_handlers)

    if serve_admin:
        # Configure and verify admin handlers.
        admin_handlers = deepcopy(ADMIN_HANDLERS)
        for path, handler in admin_handlers:
            if not issubclass(handler, basic_auth.BasicAuthHandler):
                raise TypeError('Administration handlers must '
                                'subclass BasicAuthHandler')
        handlers.extend(admin_handlers)

    # Catch-all handler for 404 pages.
    handlers.extend([(r'/.*', base.PageNotFoundHandler)])

    # Create application and separately add handlers for the short domain and the
    # regular domain.
    #
    # Note that, although the short-domain handlers are added after the initial construction
    # of the Application, those routes will take priority over the routes in the handlers
    # array.
    application = web.Application(handlers, **settings)
    application.add_handlers(re.escape(options.options.short_domain),
                             SHORT_DOMAIN_HANDLERS)

    # Start the HTTP server.
    http_server = httpserver.HTTPServer(
        application,
        xheaders=options.options.xheaders,
        ssl_options={
            'certfile': secrets.GetSecretFile('%s.crt' % settings['domain']),
            'keyfile': secrets.GetSecretFile('%s.key' % settings['domain']),
        } if options.options.ssl else None)
    with stack_context.NullContext():
        http_server.listen(options.options.port)

    # Setup redirect server for HTTP -> HTTPS.
    if options.options.ssl:
        http_settings = {
            'host': ServerEnvironment.GetHost(),
            'redirect_port': options.options.redirect_port,
            'xheaders': options.options.xheaders,
        }

        redirect_handlers = [
            (r'/(.*)', index.RedirectHandler),
        ]
        redirect_server = httpserver.HTTPServer(
            web.Application(redirect_handlers, **http_settings))
        with stack_context.NullContext():
            redirect_server.listen(options.options.insecure_port)

    # Ensure that system users have been created if running with a local db (needs server to be running).
    if options.options.localdb:
        yield CreateSystemUsers(client)

    # Run the server until it hits an exception or stop signal.
    yield gen.Task(lambda callback: None)
예제 #3
0
  def post(self, action):

    if not ServerEnvironment.IsDevBox():
      raise web.HTTPError(403, _TEST_HOOKS_NOT_SUPPORTED)

    from PIL import Image, ImageChops

    if action == 'copy':
      logging.info('Updating baseline image')
      urls = {}
      body = json.loads(self.request.body)
      testname = body['testname']
      imagename = body['imagename']
      scheme = body['scheme']

      _FULL_RESULTS_BASELINE = '%s/results/baseline/%s' % (options.options.testing_path, scheme)
      _FULL_RESULTS_CURRENT = '%s/results/current/%s' % (options.options.testing_path, scheme)

      # Overwrite the 'baseline' image for the test with the 'current' image.
      baseline_image = r'%s/%s/%s' % (_FULL_RESULTS_BASELINE, testname, imagename)
      current_image = r'%s/%s/Run 1/%s' % (_FULL_RESULTS_CURRENT, testname, imagename)

      yield self._UpdateImageMaskConfig(testname, imagename, scheme)

      if os.path.exists(current_image):
        shutil.copy(current_image, baseline_image)
        logging.info('Updated baseline image for %s' % testname)

      baseline_web_image = r'%s/%s/%s/%s' % (_STATIC_RESULTS_BASELINE, scheme, testname, imagename)
      current_web_image = r'%s/%s/%s/Run 1/%s' % (_STATIC_RESULTS_CURRENT, scheme, testname, imagename)

      urls['baseline'] = baseline_web_image
      urls['current'] = current_web_image

      # Return JSON result.
      self.write(urls)
      self.finish()
      return

    if action == 'delete':
      body = json.loads(self.request.body)
      testname = body['testname']
      imagename = body['imagename']

      current_image = r'%s/%s/Run 1/%s' % (_FULL_RESULTS_CURRENT, testname, imagename)
      if os.path.exists(current_image) is True:
        os.remove(current_image)
        logging.info('Deleted current capture image for %s' % testname)
      self.finish()
      return

    if action == 'token':
      body = json.loads(self.request.body)
      identity_key = body['auth_info']['identity'];

      identity = yield gen.Task(Identity.Query, self._client, identity_key, None, must_exist=False)
      if identity is None:
        raise web.HTTPError(400, 'Identity does not exist.')

      self.write(identity.access_token)
      self.finish()
      return

    if action == 'image':
      body = json.loads(self.request.body)
      test_name = body['testname']
      image_name = body['imagename']
      scheme = body['scheme']
      _FULL_RESULTS_BASELINE = '%s/results/baseline/%s' % (options.options.testing_path, scheme)
      _FULL_RESULTS_CURRENT = '%s/results/current/%s' % (options.options.testing_path, scheme)

      # get image base name
      tmp = image_name[:-4]
      base, num = tmp.split('|', 1)
      image_base_name = '%s.png' % base

      image1 = r'%s/%s/%s' % (_FULL_RESULTS_BASELINE, test_name, image_base_name)
      image2 = r'%s/%s/Run 1/%s' % (_FULL_RESULTS_CURRENT, test_name, image_name)

      if os.path.exists(image1) and os.path.exists(image2):
        self.set_header('Content-Type', 'application/json; charset=UTF-8')
        im1 = Image.open(image1)
        im2 = Image.open(image2)

        diff = ImageChops.difference(im2, im1)
        result = diff.getbbox() is None
        response = { 'response': result, 'bbox': diff.getbbox() }
        self.write(response)
      self.finish()
      return

    raise web.HTTPError(400, _TEST_ACTION_NOT_SUPPORTED)