def testPostAdminSetupNonAdmin(self):
        """Test posting to admin setup without specifying an admin throws error."""
        form_data = {}

        resp = self.client.post(flask.url_for('setup_admin'), data=form_data)

        json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
        self.assertEquals(403, json_response['code'])
        self.assertEquals(ufo.get_json_message('noAdministratorError'),
                          json_response['message'])

        form_data = {}
        form_data['admin_email'] = FAKE_ADMIN_EMAIL

        resp = self.client.post(flask.url_for('setup_admin'), data=form_data)

        json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
        self.assertEquals(403, json_response['code'])
        self.assertEquals(ufo.get_json_message('noAdministratorError'),
                          json_response['message'])

        form_data = {}
        form_data['admin_password'] = FAKE_ADMIN_PASSWORD

        resp = self.client.post(flask.url_for('setup_admin'), data=form_data)

        json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
        self.assertEquals(403, json_response['code'])
        self.assertEquals(ufo.get_json_message('noAdministratorError'),
                          json_response['message'])
示例#2
0
def proxyserver_add():
  """Get the form for adding new proxy servers."""
  if flask.request.method == 'GET':
    return flask.render_template('proxy_server_form.html',
                                 proxy_server=None)

  server = models.ProxyServer(
      name=flask.request.form.get('name'),
      ip_address=flask.request.form.get('ip_address'))

  #TODO more robust validation here and in proxyserver_edit
  host_public_key_contents = flask.request.form.get('host_public_key')
  if host_public_key_contents is None:
    flask.abort(400)

  ssh_private_key_contents = flask.request.form.get('ssh_private_key')
  if ssh_private_key_contents is None:
    flask.abort(400)

  try:
    server.read_public_key_from_file_contents(host_public_key_contents)
  except:
    flask.abort(400, ufo.get_json_message('publicKeyReadError'))
  try:
    server.read_private_key_from_file_contents(ssh_private_key_contents)
  except:
    flask.abort(400, ufo.get_json_message('privateKeyReadError'))

  try:
    server.save()
  except custom_exceptions.UnableToSaveToDB as e:
    flask.abort(e.code, e.message)

  return flask.redirect(flask.url_for('proxyserver_list'))
示例#3
0
def setup_admin():
    """Create the first admin in the system from the setup page.

  Returns:
    A json message indicating a redirect to login if successful.
  """
    config = ufo.get_user_config()
    if config.isConfigured:
        flask.abort(403,
                    ufo.get_json_message('cantSetAdminAfterInitialSetupError'))

    admin_email = flask.request.form.get('admin_email', None)
    admin_password = flask.request.form.get('admin_password', None)

    if admin_email is None or admin_password is None:
        flask.abort(403, ufo.get_json_message('noAdministratorError'))

    admin_user = models.AdminUser(email=admin_email)
    admin_user.set_password(admin_password)
    admin_user.save()

    config.isConfigured = True
    config.should_show_recaptcha = False
    config.save()

    response_json = json.dumps(({'shouldRedirect': True}))
    return flask.Response(ufo.XSSI_PREFIX + response_json,
                          headers=ufo.JSON_HEADERS)
def setup_admin():
  """Create the first admin in the system from the setup page.

  Returns:
    A json message indicating a redirect to login if successful.
  """
  config = ufo.get_user_config()
  if config.isConfigured:
    flask.abort(403,
                ufo.get_json_message('cantSetAdminAfterInitialSetupError'))

  admin_email = flask.request.form.get('admin_email', None)
  admin_password = flask.request.form.get('admin_password', None)

  if admin_email is None or admin_password is None:
    flask.abort(403, ufo.get_json_message('noAdministratorError'))

  admin_user = models.AdminUser(email=admin_email)
  admin_user.set_password(admin_password)
  admin_user.save()

  config.isConfigured = True
  config.should_show_recaptcha = False
  config.save()

  response_json = json.dumps(({'shouldRedirect': True}))
  return flask.Response(ufo.XSSI_PREFIX + response_json,
                        headers=ufo.JSON_HEADERS)
  def testPostAdminSetupNonAdmin(self):
    """Test posting to admin setup without specifying an admin throws error."""
    form_data = {}

    resp = self.client.post(flask.url_for('setup_admin'), data=form_data)

    json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
    self.assertEquals(403, json_response['code'])
    self.assertEquals(ufo.get_json_message('noAdministratorError'),
                      json_response['message'])

    form_data = {}
    form_data['admin_email'] = FAKE_ADMIN_EMAIL

    resp = self.client.post(flask.url_for('setup_admin'), data=form_data)

    json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
    self.assertEquals(403, json_response['code'])
    self.assertEquals(ufo.get_json_message('noAdministratorError'),
                      json_response['message'])

    form_data = {}
    form_data['admin_password'] = FAKE_ADMIN_PASSWORD

    resp = self.client.post(flask.url_for('setup_admin'), data=form_data)

    json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
    self.assertEquals(403, json_response['code'])
    self.assertEquals(ufo.get_json_message('noAdministratorError'),
                      json_response['message'])
示例#6
0
def setup_oauth():
    """Setup oauth for the apps domain.

  Returns:
    A json message indicating success or a flask abort with 403 for oauth
    exceptions.
  """
    oauth_code = flask.request.form.get('oauth_code', None)
    if oauth_code is None:
        flask.abort(403, ufo.get_json_message('noOauthCodeError'))

    config = ufo.get_user_config()
    flow = oauth.getOauthFlow()
    credentials = None
    domain = flask.request.form.get('domain', None)

    try:
        credentials = flow.step2_exchange(oauth_code)
    except oauth2client.client.FlowExchangeError as e:
        flask.abort(403, e.message)

    apiClient = credentials.authorize(httplib2.Http())
    plusApi = discovery.build(serviceName='plus', version='v1', http=apiClient)
    adminApi = discovery.build(serviceName='admin',
                               version='directory_v1',
                               http=apiClient)

    profileResult = None
    try:
        profileResult = plusApi.people().get(userId='me').execute()
    except Exception as e:
        ufo.app.logger.error(e, exc_info=True)
        flask.abort(403, ufo.get_json_message('domainInvalidError'))

    if domain is None or domain != profileResult.get('domain', None):
        flask.abort(403, ufo.get_json_message('domainInvalidError'))

    user_id = profileResult['id']
    userResult = None
    try:
        userResult = adminApi.users().get(userKey=user_id).execute()
    except Exception as e:
        ufo.app.logger.error(e, exc_info=True)
        flask.abort(403, ufo.get_json_message('nonAdminAccessError'))

    if not userResult.get('isAdmin', False):
        flask.abort(403, ufo.get_json_message('nonAdminAccessError'))

    config.credentials = credentials.to_json()
    config.domain = domain
    flask.session['domain'] = domain
    config.save()

    response_dict = {'domain': domain, 'credentials': config.credentials}
    response_json = json.dumps((response_dict))
    return flask.Response(ufo.XSSI_PREFIX + response_json,
                          headers=ufo.JSON_HEADERS)
def setup_oauth():
  """Setup oauth for the apps domain.

  Returns:
    A json message indicating success or a flask abort with 403 for oauth
    exceptions.
  """
  oauth_code = flask.request.form.get('oauth_code', None)
  if oauth_code is None:
    flask.abort(403, ufo.get_json_message('noOauthCodeError'))

  config = ufo.get_user_config()
  flow = oauth.getOauthFlow()
  credentials = None
  domain = flask.request.form.get('domain', None)

  try:
    credentials = flow.step2_exchange(oauth_code)
  except oauth2client.client.FlowExchangeError as e:
    flask.abort(403, e.message)

  apiClient = credentials.authorize(httplib2.Http())
  plusApi = discovery.build(serviceName='plus', version='v1', http=apiClient)
  adminApi = discovery.build(serviceName='admin', version='directory_v1',
                             http = apiClient)

  profileResult = None
  try:
    profileResult = plusApi.people().get(userId='me').execute()
  except Exception as e:
    ufo.app.logger.error(e, exc_info=True)
    flask.abort(403, ufo.get_json_message('domainInvalidError'))

  if domain is None or domain != profileResult.get('domain', None):
    flask.abort(403, ufo.get_json_message('domainInvalidError'))

  user_id = profileResult['id']
  userResult = None
  try:
    userResult = adminApi.users().get(userKey=user_id).execute()
  except Exception as e:
    ufo.app.logger.error(e, exc_info=True)
    flask.abort(403, ufo.get_json_message('nonAdminAccessError'))

  if not userResult.get('isAdmin', False):
    flask.abort(403, ufo.get_json_message('nonAdminAccessError'))

  config.credentials = credentials.to_json()
  config.domain = domain
  flask.session['domain'] = domain
  config.save()

  response_dict = {'domain': domain, 'credentials': config.credentials}
  response_json = json.dumps((response_dict))
  return flask.Response(ufo.XSSI_PREFIX + response_json,
                        headers=ufo.JSON_HEADERS)
    def testPostOauthSetupNonDomainAdmin(self, mock_oauth_flow, mock_build):
        """Test posting to setup as a non-admin domain user generates an error."""
        fake_id = '*****@*****.**'
        # This weird looking structure is to mock out a call buried behind several
        # objects which requires going through the method's return_value for each
        # method down the chain, starting from the discovery module.
        build_object = mock_build.return_value
        people_object = build_object.people.return_value
        get_object = people_object.get.return_value
        get_object.execute.return_value = {
            'domain': FAKE_DOMAIN,
            'id': fake_id
        }
        users_object = build_object.users.return_value
        users_object.get.return_value.execute.return_value = {'isAdmin': False}
        returned_mock = mock_oauth_flow.return_value
        returned_mock.step2_exchange.return_value = MOCK_CREDENTIALS
        returned_mock.step1_get_authorize_url.return_value = FAKE_OAUTH_URL

        form_data = {}
        form_data['oauth_code'] = FAKE_OAUTH_CODE
        form_data['domain'] = FAKE_DOMAIN

        resp = self.client.post(flask.url_for('setup_oauth'), data=form_data)

        json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
        self.assertEquals(403, json_response['code'])
        self.assertEquals(ufo.get_json_message('nonAdminAccessError'),
                          json_response['message'])
  def testPostOauthSetupNonDomainAdmin(self, mock_oauth_flow, mock_build):
    """Test posting to setup as a non-admin domain user generates an error."""
    fake_id = '*****@*****.**'
    # This weird looking structure is to mock out a call buried behind several
    # objects which requires going through the method's return_value for each
    # method down the chain, starting from the discovery module.
    build_object = mock_build.return_value
    people_object = build_object.people.return_value
    get_object = people_object.get.return_value
    get_object.execute.return_value = {'domain': FAKE_DOMAIN, 'id': fake_id}
    users_object = build_object.users.return_value
    users_object.get.return_value.execute.return_value = {'isAdmin': False}
    returned_mock = mock_oauth_flow.return_value
    returned_mock.step2_exchange.return_value = MOCK_CREDENTIALS
    returned_mock.step1_get_authorize_url.return_value = FAKE_OAUTH_URL

    form_data = {}
    form_data['oauth_code'] = FAKE_OAUTH_CODE
    form_data['domain'] = FAKE_DOMAIN

    resp = self.client.post(flask.url_for('setup_oauth'), data=form_data)

    json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
    self.assertEquals(403, json_response['code'])
    self.assertEquals(ufo.get_json_message('nonAdminAccessError'),
                      json_response['message'])
    def testPostOauthSetupNoOauthCode(self):
        """Test posting to setup without an oauth code generates an error."""
        form_data = {}
        form_data['domain'] = FAKE_DOMAIN

        resp = self.client.post(flask.url_for('setup_oauth'), data=form_data)

        json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
        self.assertEquals(403, json_response['code'])
        self.assertEquals(ufo.get_json_message('noOauthCodeError'),
                          json_response['message'])
  def testPostOauthSetupNoOauthCode(self):
    """Test posting to setup without an oauth code generates an error."""
    form_data = {}
    form_data['domain'] = FAKE_DOMAIN

    resp = self.client.post(flask.url_for('setup_oauth'), data=form_data)

    json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
    self.assertEquals(403, json_response['code'])
    self.assertEquals(ufo.get_json_message('noOauthCodeError'),
                      json_response['message'])
    def testPostAdminSetupAlreadySet(self):
        """Test posting to admin setup after initial setup throws an error."""
        super(SetupTest, self).setup_config()

        form_data = {}
        form_data['admin_email'] = FAKE_ADMIN_EMAIL
        form_data['admin_password'] = FAKE_ADMIN_PASSWORD

        resp = self.client.post(flask.url_for('setup_admin'), data=form_data)

        json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
        self.assertEquals(403, json_response['code'])
        self.assertEquals(
            ufo.get_json_message('cantSetAdminAfterInitialSetupError'),
            json_response['message'])
  def testPostAdminSetupAlreadySet(self):
    """Test posting to admin setup after initial setup throws an error."""
    super(SetupTest, self).setup_config()

    form_data = {}
    form_data['admin_email'] = FAKE_ADMIN_EMAIL
    form_data['admin_password'] = FAKE_ADMIN_PASSWORD

    resp = self.client.post(flask.url_for('setup_admin'), data=form_data)

    json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
    self.assertEquals(403, json_response['code'])
    self.assertEquals(
        ufo.get_json_message('cantSetAdminAfterInitialSetupError'),
        json_response['message'])
    def testPostOauthSetupIncorrectDomain(self, mock_oauth_flow, mock_build):
        """Test posting to setup with an incorrect domain generates an error."""
        domain_that_doesnt_match = 'google.com'
        # This weird looking structure is to mock out a call buried behind several
        # objects which requires going through the method's return_value for each
        # method down the chain, starting from the discovery module.
        build_object = mock_build.return_value
        people_object = build_object.people.return_value
        get_object = people_object.get.return_value
        get_object.execute.return_value = {'domain': domain_that_doesnt_match}
        returned_mock = mock_oauth_flow.return_value
        returned_mock.step2_exchange.return_value = MOCK_CREDENTIALS
        returned_mock.step1_get_authorize_url.return_value = FAKE_OAUTH_URL

        form_data = {}
        form_data['oauth_code'] = FAKE_OAUTH_CODE
        form_data['domain'] = FAKE_DOMAIN

        resp = self.client.post(flask.url_for('setup_oauth'), data=form_data)

        json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
        self.assertEquals(403, json_response['code'])
        self.assertEquals(ufo.get_json_message('domainInvalidError'),
                          json_response['message'])
  def testPostOauthSetupIncorrectDomain(self, mock_oauth_flow, mock_build):
    """Test posting to setup with an incorrect domain generates an error."""
    domain_that_doesnt_match = 'google.com'
    # This weird looking structure is to mock out a call buried behind several
    # objects which requires going through the method's return_value for each
    # method down the chain, starting from the discovery module.
    build_object = mock_build.return_value
    people_object = build_object.people.return_value
    get_object = people_object.get.return_value
    get_object.execute.return_value = {'domain': domain_that_doesnt_match}
    returned_mock = mock_oauth_flow.return_value
    returned_mock.step2_exchange.return_value = MOCK_CREDENTIALS
    returned_mock.step1_get_authorize_url.return_value = FAKE_OAUTH_URL

    form_data = {}
    form_data['oauth_code'] = FAKE_OAUTH_CODE
    form_data['domain'] = FAKE_DOMAIN

    resp = self.client.post(flask.url_for('setup_oauth'), data=form_data)

    json_response = json.loads(resp.data[len(ufo.XSSI_PREFIX):])
    self.assertEquals(403, json_response['code'])
    self.assertEquals(ufo.get_json_message('domainInvalidError'),
                      json_response['message'])