示例#1
0
 def test_post_idle_timeout(self):
     mc = MinecraftDownload.create(
         '1.7.4',
         'https://s3.amazonaws.com/Minecraft.Download/versions/1.7.4/minecraft_server.1.7.4.jar'
     )
     self.server.key.delete()
     self.log_in_admin()
     self.assertEqual(0, Server.query().count())
     self.assertEqual(0, Client.query().count())
     response = self.post(
         params={
             'name': 'new server',
             'version': mc.version,
             'memory': '1G',
             'motd': 'Welcome',
             'white_list': True,
             'server_port': 25565,
             'idle_timeout': 0,
             'eula_agree': True
         })
     self.assertEqual(1, Server.query().count())
     self.assertEqual(1, Client.query().count())
     server = Server.query().get()
     self.assertEqual('new server', server.name)
     self.assertEqual(True, server.is_gce)
     self.assertEqual('1G', server.memory)
     self.assertEqual(0, server.idle_timeout)
     mc_properties = server.mc_properties
     self.assertEqual('Welcome', mc_properties.motd)
     self.assertEqual(True, mc_properties.white_list)
     self.assertEqual(25565, mc_properties.server_port)
     self.assertRedirects(response,
                          '/servers/{0}'.format(server.key.urlsafe()))
示例#2
0
 def test_post_non_unique_port(self):
     mc = MinecraftDownload.create(
         '1.7.4',
         'https://s3.amazonaws.com/Minecraft.Download/versions/1.7.4/minecraft_server.1.7.4.jar'
     )
     self.server.key.delete()
     self.log_in_admin()
     self.assertEqual(0, Server.query().count())
     self.assertEqual(0, Client.query().count())
     response = self.post(
         params={
             'name': 'new server',
             'version': mc.version,
             'memory': '1G',
             'motd': 'Welcome',
             'white_list': True,
             'server_port': 25565,
             'idle_timeout': 10,
             'eula_agree': True
         })
     response = self.post(
         params={
             'name': 'new server',
             'version': mc.version,
             'memory': '1G',
             'motd': 'Welcome',
             'white_list': True,
             'server_port': 25565,
             'idle_timeout': 10,
             'eula_agree': True
         })
     self.assertEqual(1, Server.query().count())
     self.assertEqual(1, Client.query().count())
     self.assertOK(response)
示例#3
0
 def test_post_deny_existing_client(self):
     Client.get_or_insert('test_client',
                          client_id=TEST_CLIENT_ID,
                          redirect_uris=[TEST_REDIRECT_URI])
     url = self.url
     query_params = {
         'client_id': TEST_CLIENT_ID,
         'redirect_uri': TEST_REDIRECT_URI,
         'response_type': 'code'
     }
     response = self.get(self.url, params=query_params)
     self.assertOK(response)
     csrf_string = 'name="csrf_token" type="hidden" value="'
     begin = response.body.find(csrf_string) + len(csrf_string)
     end = response.body.find('"', begin)
     csrf_token = response.body[begin:end]
     if query_params:
         query_params = urlencode(query_params, doseq=True)
         if '?' in url:
             url += '&'
         else:
             url += '?'
         url += query_params
     params = {'csrf_token': csrf_token, 'deny': 'Deny'}
     response = self.post(url, params)
     self.assertRedirects(response,
                          to=TEST_REDIRECT_URI + "?error=access_denied")
     self.assertEqual(1, Client.query().count())
示例#4
0
 def test_post_deny_existing_client(self):
     Client.get_or_insert('test_client', client_id=TEST_CLIENT_ID, redirect_uris=[TEST_REDIRECT_URI])
     url = self.url
     query_params = {
         'client_id': TEST_CLIENT_ID,
         'redirect_uri': TEST_REDIRECT_URI,
         'response_type': 'code'
     }
     response = self.get(self.url, params=query_params)
     self.assertOK(response)
     csrf_string = 'name="csrf_token" type="hidden" value="'
     begin = response.body.find(csrf_string) + len(csrf_string)
     end = response.body.find('"', begin)
     csrf_token = response.body[begin:end]
     if query_params:
         query_params = urlencode(query_params, doseq=True)
         if '?' in url:
             url += '&'
         else:
             url += '?'
         url += query_params
     params = {'csrf_token': csrf_token, 'deny': 'Deny'}
     response = self.post(url, params)
     self.assertRedirects(response, to=TEST_REDIRECT_URI+"?error=access_denied")
     self.assertEqual(1, Client.query().count())
示例#5
0
 def test_post_idle_timeout(self):
     mc = MinecraftDownload.create(
         '1.7.4',
         'https://s3.amazonaws.com/Minecraft.Download/versions/1.7.4/minecraft_server.1.7.4.jar'
     )
     self.server.key.delete()
     self.log_in_admin()
     self.assertEqual(0, Server.query().count())
     self.assertEqual(0, Client.query().count())
     response = self.post(params={
         'name': 'new server',
         'version': mc.version,
         'memory': '1G',
         'motd': 'Welcome',
         'white_list': True,
         'server_port': 25565,
         'idle_timeout': 0,
         'eula_agree': True
     })
     self.assertEqual(1, Server.query().count())
     self.assertEqual(1, Client.query().count())
     server = Server.query().get()
     self.assertEqual('new server', server.name)
     self.assertEqual(True, server.is_gce)
     self.assertEqual('1G', server.memory)
     self.assertEqual(0, server.idle_timeout)
     mc_properties = server.mc_properties
     self.assertEqual('Welcome', mc_properties.motd)
     self.assertEqual(True, mc_properties.white_list)
     self.assertEqual(25565, mc_properties.server_port)
     self.assertRedirects(response, '/servers/{0}'.format(server.key.urlsafe()))
示例#6
0
 def test_post_non_unique_port(self):
     mc = MinecraftDownload.create(
         '1.7.4',
         'https://s3.amazonaws.com/Minecraft.Download/versions/1.7.4/minecraft_server.1.7.4.jar'
     )
     self.server.key.delete()
     self.log_in_admin()
     self.assertEqual(0, Server.query().count())
     self.assertEqual(0, Client.query().count())
     response = self.post(params={
         'name': 'new server',
         'version': mc.version,
         'memory': '1G',
         'motd': 'Welcome',
         'white_list': True,
         'server_port': 25565,
         'idle_timeout': 10,
         'eula_agree': True
     })
     response = self.post(params={
         'name': 'new server',
         'version': mc.version,
         'memory': '1G',
         'motd': 'Welcome',
         'white_list': True,
         'server_port': 25565,
         'idle_timeout': 10,
         'eula_agree': True
     })
     self.assertEqual(1, Server.query().count())
     self.assertEqual(1, Client.query().count())
     self.assertOK(response)
示例#7
0
 def test_post_duplicate_client_id(self):
     params = {
         'client_id': TEST_CLIENT_ID,
         'redirect_uris': [TEST_REDIRECT_URI],
         'client_name': TEST_CLIENT_NAME,
         'client_uri': TEST_CLIENT_URI,
         'logo_uri': TEST_LOGO_URI
     }
     response = self.post_json(self.url, params=params)
     self.assertCreated(response)
     self.assertEqual(Client.query().count(), 2)
     client = Client.query().get()
     self.assertTrue(client.active)
     body = json.loads(response.body)
     self.assertEqual(len(body), NUM_CLIENT_FIELDS)
     self.assertTrue(body['client_id'].startswith(TEST_CLIENT_ID+'-'))
     client = Client.get_by_client_id(body['client_id'])
     self.assertEqual(body['redirect_uris'], [TEST_REDIRECT_URI])
     self.assertEqual(body['client_name'], TEST_CLIENT_NAME)
     self.assertEqual(body['client_uri'], TEST_CLIENT_URI)
     self.assertEqual(body['logo_uri'], TEST_LOGO_URI)
     self.assertEqual(body['registration_client_uri'], 'https://localhost:80/oauth/v1/clients/{0}'.format(client.client_id))
     self.assertEqual(body['registration_access_token'], client.registration_access_token)
     self.assertEqual(body['client_secret'], client.secret)
     self.assertEqual(body['client_secret_expires_at'], client.secret_expires_at)
示例#8
0
 def test_post_duplicate_client_id(self):
     params = {
         'client_id': TEST_CLIENT_ID,
         'redirect_uris': [TEST_REDIRECT_URI],
         'client_name': TEST_CLIENT_NAME,
         'client_uri': TEST_CLIENT_URI,
         'logo_uri': TEST_LOGO_URI
     }
     response = self.post_json(self.url, params=params)
     self.assertCreated(response)
     self.assertEqual(Client.query().count(), 2)
     client = Client.query().get()
     self.assertTrue(client.active)
     body = json.loads(response.body)
     self.assertEqual(len(body), NUM_CLIENT_FIELDS)
     self.assertTrue(body['client_id'].startswith(TEST_CLIENT_ID + '-'))
     client = Client.get_by_client_id(body['client_id'])
     self.assertEqual(body['redirect_uris'], [TEST_REDIRECT_URI])
     self.assertEqual(body['client_name'], TEST_CLIENT_NAME)
     self.assertEqual(body['client_uri'], TEST_CLIENT_URI)
     self.assertEqual(body['logo_uri'], TEST_LOGO_URI)
     self.assertEqual(
         body['registration_client_uri'],
         'https://localhost:80/oauth/v1/clients/{0}'.format(
             client.client_id))
     self.assertEqual(body['registration_access_token'],
                      client.registration_access_token)
     self.assertEqual(body['client_secret'], client.secret)
     self.assertEqual(body['client_secret_expires_at'],
                      client.secret_expires_at)
示例#9
0
 def create_for_redirect(cls, conf, redirect_url, state=None, approval_prompt='auto'):
     gclient = cls(conf, redirect_url)
     c = OauthClient(auth_endpoint='https://accounts.google.com/o/oauth2/auth',
                     client_id=gclient.google_client_id,
                     redirect_uri=gclient.redirect_url)
     loc = c.auth_uri(scope=gclient.google_scope.split(','), access_type='offline',
                      state=state or '/', approval_prompt=approval_prompt)
     gclient.redirect = loc
     return gclient
示例#10
0
 def create_for_refresh(cls, conf, redirect_url, rtoken):
     gclient = cls(conf, redirect_url)
     c = OauthClient(token_endpoint='https://accounts.google.com/o/oauth2/token',
                     resource_endpoint='https://www.googleapis.com/oauth2/v1',
                     client_id=gclient.google_client_id,
                     client_secret=gclient.google_client_secret)
     error = c.request_token(grant_type='refresh_token',
                             refresh_token=rtoken)
     if not error:
         gclient.access_token = c.access_token
         gclient.expires_in = c.expires_in
     return gclient
示例#11
0
 def test_post(self):
     self.server.key.delete()
     self.log_in_admin()
     self.assertEqual(0, Server.query().count())
     self.assertEqual(0, Client.query().count())
     response = self.post(params={'name': 'new server'})
     self.assertEqual(1, Server.query().count())
     self.assertEqual(1, Client.query().count())
     server = Server.query().get()
     self.assertEqual('new server', server.name)
     self.assertEqual(False, server.is_gce)
     self.assertRedirects(response, '/servers/{0}'.format(server.key.urlsafe()))
示例#12
0
 def create_for_redirect(cls, conf, state=None, approval_prompt='auto'):
     gclient = cls(conf)
     c = OauthClient(
         auth_endpoint='https://accounts.google.com/o/oauth2/auth',
         client_id=gclient.google_client_id,
         redirect_uri=gclient.google_redirect_url)
     loc = c.auth_uri(scope=gclient.google_scope.split(','),
                      access_type='offline',
                      state=state or '/',
                      approval_prompt=approval_prompt)
     gclient.redirect = loc
     return gclient
示例#13
0
 def create_for_refresh(cls, conf, rtoken):
     gclient = cls(conf)
     c = OauthClient(
         token_endpoint='https://accounts.google.com/o/oauth2/token',
         resource_endpoint='https://www.googleapis.com/oauth2/v1',
         client_id=gclient.google_client_id,
         client_secret=gclient.google_client_secret)
     error = c.request_token(grant_type='refresh_token',
                             refresh_token=rtoken)
     if not error:
         gclient.access_token = c.access_token
         gclient.expires_in = c.expires_in
     return gclient
示例#14
0
 def test_post(self):
     self.server.key.delete()
     self.log_in_admin()
     self.assertEqual(0, Server.query().count())
     self.assertEqual(0, Client.query().count())
     response = self.post(params={'name': 'new server'})
     self.assertEqual(1, Server.query().count())
     self.assertEqual(1, Client.query().count())
     server = Server.query().get()
     self.assertEqual('new server', server.name)
     self.assertEqual(False, server.is_gce)
     self.assertRedirects(response,
                          '/servers/{0}'.format(server.key.urlsafe()))
示例#15
0
 def test_post_duplicate_none_port(self):
     self.server.mc_properties.server_port = 25565
     self.server.mc_properties.put()
     self.log_in_admin()
     self.mc = MinecraftDownload.create(
         '1.7.4', 'https://s3.amazonaws.com/Minecraft.Download/versions/1.7.4/minecraft_server.1.7.4.jar'
     )
     self.server.version = self.mc.version
     self.server.put()
     response = self.post(
         params={
             'name': self.server.name,
             'version': self.server.version,
             'memory': '1G',
             'server_port': '',
             'idle_timeout': 10,
             'eula_agree': True
         }
     )
     self.assertEqual(1, Server.query().count())
     self.assertEqual(1, Client.query().count())
     server = self.server.key.get()
     server = self.server.key.get()
     self.assertIsNone(server.mc_properties.server_port)
     self.assertRedirects(response, '/servers/{0}'.format(server.key.urlsafe()))
示例#16
0
 def test_post_authorize(self):
     url = self.url
     query_params = {
         'client_id': TEST_CLIENT_ID,
         'redirect_uri': TEST_REDIRECT_URI,
         'response_type': 'code',
         'scope': 'data'
     }
     response = self.get(self.url, params=query_params)
     self.assertOK(response)
     csrf_string = 'name="csrf_token" type="hidden" value="'
     begin = response.body.find(csrf_string) + len(csrf_string)
     end = response.body.find('"', begin)
     csrf_token = response.body[begin:end]
     if query_params:
         query_params = urlencode(query_params, doseq=True)
         if '?' in url:
             url += '&'
         else:
             url += '?'
         url += query_params
     params = {'csrf_token': csrf_token, 'grant': 'Grant'}
     response = self.post(url, params)
     self.assertRedirects(response)
     self.assertRegexpMatches(response.headers['Location'],
                              ur"https://localhost/\?code=.+")
     self.assertEqual(1, Client.query().count())
示例#17
0
 def test_post_authorize(self):
     url = self.url
     query_params = {
         'client_id': TEST_CLIENT_ID,
         'redirect_uri': TEST_REDIRECT_URI,
         'response_type': 'code',
         'scope': 'data'
     }
     response = self.get(self.url, params=query_params)
     self.assertOK(response)
     csrf_string = 'name="csrf_token" type="hidden" value="'
     begin = response.body.find(csrf_string) + len(csrf_string)
     end = response.body.find('"', begin)
     csrf_token = response.body[begin:end]
     if query_params:
         query_params = urlencode(query_params, doseq=True)
         if '?' in url:
             url += '&'
         else:
             url += '?'
         url += query_params
     params = {'csrf_token': csrf_token, 'grant': 'Grant'}
     response = self.post(url, params)
     self.assertRedirects(response)
     self.assertRegexpMatches(response.headers['Location'], ur"https://localhost/\?code=.+")
     self.assertEqual(1, Client.query().count())
示例#18
0
文件: api.py 项目: RubyCoin/mc-coal
 def post(self):
     client = Client.get_by_client_id(self.request.authentication.client_id)
     instance = client.instance
     if instance is not None:
         form = self.request.form
         try:
             server_key = ndb.Key(urlsafe=form.server_key.data)
             server = server_key.get()
         except Exception:
             server = None
         if server:
             event = form.event.data
             completed = form.completed.data
             status = None
             if event == START_EVENT:
                 if completed < 100:
                     status = SERVER_LOADING
                 else:
                     status = SERVER_LOADED
             if event == STOP_EVENT:
                 if completed < 100:
                     status = SERVER_SAVING
                 else:
                     status = SERVER_SAVED
             if status:
                 server.update_status(status=status, completed=completed)
     response = {}
     self.json_response(response, status_code=200)
示例#19
0
 def setUp(self):
     super(OauthTest, self).setUp()
     key = ndb.Key(Client, TEST_CLIENT_ID)
     data = {
         'client_id': TEST_CLIENT_ID,
         'redirect_uris': [TEST_REDIRECT_URI],
         'name': TEST_CLIENT_NAME,
         'uri': TEST_CLIENT_URI,
         'logo_uri': TEST_LOGO_URI,
         'scope': ['data'],
         'secret': TEST_CLIENT_SECRET,
         'secret_expires_at': 0,
         'registration_access_token': TEST_REGISTRATION_ACCESS_TOKEN
     }
     self.client = Client(key=key, **data)
     self.client.put()
示例#20
0
 def test_post_duplicate_none_port(self):
     self.server.mc_properties.server_port = 25565
     self.server.mc_properties.put()
     self.log_in_admin()
     self.mc = MinecraftDownload.create(
         '1.7.4',
         'https://s3.amazonaws.com/Minecraft.Download/versions/1.7.4/minecraft_server.1.7.4.jar'
     )
     self.server.version = self.mc.version
     self.server.put()
     response = self.post(
         params={
             'name': self.server.name,
             'version': self.server.version,
             'memory': '1G',
             'server_port': '',
             'idle_timeout': 10,
             'eula_agree': True
         })
     self.assertEqual(1, Server.query().count())
     self.assertEqual(1, Client.query().count())
     server = self.server.key.get()
     server = self.server.key.get()
     self.assertIsNone(server.mc_properties.server_port)
     self.assertRedirects(response,
                          '/servers/{0}'.format(server.key.urlsafe()))
示例#21
0
 def create_for_token(cls, conf, redirect_url, code):
     gclient = cls(conf, redirect_url)
     c = OauthClient(token_endpoint='https://accounts.google.com/o/oauth2/token',
                     resource_endpoint='https://www.googleapis.com/oauth2/v1',
                     redirect_uri=gclient.redirect_url,
                     client_id=gclient.google_client_id,
                     client_secret=gclient.google_client_secret)
     c.request_token(code=code)
     gclient.access_token = c.access_token
     gclient.expires_in = c.expires_in
     if hasattr(c, 'refresh_token'):
         gclient.refresh_token = c.refresh_token
         new_client = cls.create_for_refresh(conf, c.refresh_token)
         gclient.access_token = new_client.access_token
         gclient.expires_in = new_client.expires_in
     gclient.userinfo = c.request('/userinfo')
     return gclient
示例#22
0
 def create_for_token(cls, conf, code):
     gclient = cls(conf)
     c = OauthClient(
         token_endpoint='https://accounts.google.com/o/oauth2/token',
         resource_endpoint='https://www.googleapis.com/oauth2/v1',
         redirect_uri=gclient.google_redirect_url,
         client_id=gclient.google_client_id,
         client_secret=gclient.google_client_secret)
     c.request_token(code=code)
     gclient.access_token = c.access_token
     gclient.expires_in = c.expires_in
     if hasattr(c, 'refresh_token'):
         gclient.refresh_token = c.refresh_token
         new_client = cls.create_for_refresh(conf, c.refresh_token)
         gclient.access_token = new_client.access_token
         gclient.expires_in = new_client.expires_in
     gclient.userinfo = c.request('/userinfo')
     return gclient
示例#23
0
 def test_post_minimum(self):
     self.client.key.delete()
     self.client = None
     params = {
         'redirect_uris': [TEST_REDIRECT_URI]
     }
     response = self.post_json(self.url, params=params)
     self.assertCreated(response)
     self.assertEqual(Client.query().count(), 1)
     client = Client.query().get()
     self.assertTrue(client.active)
     body = json.loads(response.body)
     self.assertEqual(len(body), NUM_CLIENT_FIELDS-3)
     self.assertEqual(body['client_id'], client.client_id)
     self.assertEqual(body['redirect_uris'], [TEST_REDIRECT_URI])
     self.assertEqual(body['registration_client_uri'], 'https://localhost:80/oauth/v1/clients/{0}'.format(client.client_id))
     self.assertEqual(body['registration_access_token'], client.registration_access_token)
     self.assertEqual(body['client_secret'], client.secret)
     self.assertEqual(body['client_secret_expires_at'], client.secret_expires_at)
示例#24
0
文件: api.py 项目: RubyCoin/mc-coal
 def get(self):
     client = Client.get_by_client_id(self.request.authentication.client_id)
     server = client.server
     if not server.active:
         self.abort(404)
     last_log_line = LogLine.get_last_line_with_timestamp(server.key)
     response = {
         'lastline': last_log_line.line if last_log_line is not None else None,
     }
     self.json_response(response, status_code=200)
示例#25
0
 def test_post_minimum(self):
     self.client.key.delete()
     self.client = None
     params = {'redirect_uris': [TEST_REDIRECT_URI]}
     response = self.post_json(self.url, params=params)
     self.assertCreated(response)
     self.assertEqual(Client.query().count(), 1)
     client = Client.query().get()
     self.assertTrue(client.active)
     body = json.loads(response.body)
     self.assertEqual(len(body), NUM_CLIENT_FIELDS - 3)
     self.assertEqual(body['client_id'], client.client_id)
     self.assertEqual(body['redirect_uris'], [TEST_REDIRECT_URI])
     self.assertEqual(
         body['registration_client_uri'],
         'https://localhost:80/oauth/v1/clients/{0}'.format(
             client.client_id))
     self.assertEqual(body['registration_access_token'],
                      client.registration_access_token)
     self.assertEqual(body['client_secret'], client.secret)
     self.assertEqual(body['client_secret_expires_at'],
                      client.secret_expires_at)
示例#26
0
文件: gce.py 项目: RubyCoin/mc-coal
 def get_or_create_client(self):
     client = self.client
     if client is None:
         from oauth import Client, authorization_provider
         existing_client = True
         while existing_client:
             random_int = ''.join([random.choice(UNICODE_ASCII_DIGITS) for x in xrange(5)])
             client_id = Client.get_key_name("{0}-{1}".format(CONTROLLER_CLIENT_ID, random_int))
             client_key = Client.get_key(client_id)
             existing_client = client_key.get()
         client = Client(
             key=client_key,
             client_id=client_id,
             instance_key=self.key,
             redirect_uris=['/'],
             scope=['controller'],
             secret=authorization_provider.generate_client_secret()
         )
         client.put()
         self.client_key = client.key
         self.put()
     return client
示例#27
0
文件: api.py 项目: RubyCoin/mc-coal
 def post(self):
     client = Client.get_by_client_id(self.request.authentication.client_id)
     server = client.server
     if not server.active:
         self.abort(404)
     status_code = 200
     line = self.request.form.line.data
     zone = self.request.form.zone.data
     existing_line = LogLine.lookup_line(server.key, line)
     if existing_line is None:
         log_line = LogLine.create(server, line, zone)
         if log_line is not None:
             status_code = 201
     self.json_response({}, status_code=status_code)
示例#28
0
 def create(cls, **kwargs):
     instance = cls(**kwargs)
     instance.put()
     if instance.agent_key is None:
         from oauth import Client, authorization_provider
         existing_agent_client = True
         while existing_agent_client:
             random_int = ''.join([random.choice(UNICODE_ASCII_DIGITS) for x in xrange(5)])
             client_id = Client.get_key_name("{0}-{1}".format(AGENT_CLIENT_ID, random_int))
             agent_client_key = Client.get_key(client_id)
             existing_agent_client = agent_client_key.get()
         agent_client = Client(
             key=agent_client_key,
             client_id=client_id,
             server_key=instance.key,
             redirect_uris=['/'],
             scope=['agent'],
             secret=authorization_provider.generate_client_secret()
         )
         agent_client.put()
         instance.agent_key = agent_client.key
         instance.put()
     return instance
示例#29
0
def fetch_event(url):
    consumer = Consumer(consumer_key, consumer_secret)
    client = Client(consumer)
    resp, content = client.request(url)
    event = Event()
    event.status = int(resp['status'])

    if event.status == 200:
        xml_document = minidom.parseString(content)
        event_xml = EventXml(xml_document)
        event.raw = event_xml.pretty_print

        try:
            event.type = int(EventTypes(event_xml.eventType))
        except ValueError:
            event.type = int(EventTypes.UNKNOWN)

        event.save()
        return handle_event(event_xml)
    else:
        message = "HTTP response %d" % event.status
        log.error(message)
        event.save()
        return message_template % ('false', "UNKNOWN_ERROR", message)
示例#30
0
 def setUp(self):
     super(OauthTest, self).setUp()
     key = ndb.Key(Client, TEST_CLIENT_ID)
     data = {
         'client_id': TEST_CLIENT_ID,
         'redirect_uris': [TEST_REDIRECT_URI],
         'name': TEST_CLIENT_NAME,
         'uri': TEST_CLIENT_URI,
         'logo_uri': TEST_LOGO_URI,
         'scope': ['data'],
         'secret': TEST_CLIENT_SECRET,
         'secret_expires_at': 0,
         'registration_access_token': TEST_REGISTRATION_ACCESS_TOKEN
     }
     self.client = Client(key=key, **data)
     self.client.put()
示例#31
0
文件: api.py 项目: RubyCoin/mc-coal
 def post(self):
     form = self.request.form
     is_server_running = form.is_server_running.data
     server_day = form.server_day.data
     server_time = form.server_time.data
     is_raining = form.is_raining.data
     is_thundering = form.is_thundering.data
     num_overloads = form.num_overloads.data
     ms_behind = form.ms_behind.data
     skipped_ticks = form.skipped_ticks.data
     address = form.address.data
     timestamp = form.timestamp.data
     client = Client.get_by_client_id(self.request.authentication.client_id)
     server = client.server
     if not server.active:
         self.abort(404)
     status = SERVER_UNKNOWN
     if is_server_running:
         status = SERVER_RUNNING
     elif is_server_running is False:
         status = SERVER_STOPPED
     server.update_status(
         status=status,
         last_ping=datetime.datetime.utcnow(),
         server_day=server_day,
         server_time=server_time,
         is_raining=is_raining,
         is_thundering=is_thundering,
         num_overloads=num_overloads,
         ms_behind=ms_behind,
         skipped_ticks=skipped_ticks,
         address=address,
         timestamp=timestamp
     )
     commands = []
     if is_server_running:
         commands = Command.pop_all(server.key)
     response = {
         'commands': commands
     }
     self.json_response(response, status_code=200)
示例#32
0
 def get_or_create_client(self):
     client = self.client
     if client is None:
         from oauth import Client, authorization_provider
         existing_client = True
         while existing_client:
             random_int = ''.join(
                 [random.choice(UNICODE_ASCII_DIGITS) for x in xrange(5)])
             client_id = Client.get_key_name("{0}-{1}".format(
                 CONTROLLER_CLIENT_ID, random_int))
             client_key = Client.get_key(client_id)
             existing_client = client_key.get()
         client = Client(
             key=client_key,
             client_id=client_id,
             instance_key=self.key,
             redirect_uris=['/'],
             scope=['controller'],
             secret=authorization_provider.generate_client_secret())
         client.put()
         self.client_key = client.key
         self.put()
     return client
示例#33
0
 def create(cls, **kwargs):
     instance = cls(**kwargs)
     instance.put()
     if instance.agent_key is None:
         from oauth import Client, authorization_provider
         existing_agent_client = True
         while existing_agent_client:
             random_int = ''.join(
                 [random.choice(UNICODE_ASCII_DIGITS) for x in xrange(5)])
             client_id = Client.get_key_name("{0}-{1}".format(
                 AGENT_CLIENT_ID, random_int))
             agent_client_key = Client.get_key(client_id)
             existing_agent_client = agent_client_key.get()
         agent_client = Client(
             key=agent_client_key,
             client_id=client_id,
             server_key=instance.key,
             redirect_uris=['/'],
             scope=['agent'],
             secret=authorization_provider.generate_client_secret())
         agent_client.put()
         instance.agent_key = agent_client.key
         instance.put()
     return instance
示例#34
0
class OauthTest(BaseTest, WebTest):
    APPLICATION = main.application
    URL = None
    ALLOWED = []

    @property
    def url(self):
        return self.URL

    def setUp(self):
        super(OauthTest, self).setUp()
        key = ndb.Key(Client, TEST_CLIENT_ID)
        data = {
            'client_id': TEST_CLIENT_ID,
            'redirect_uris': [TEST_REDIRECT_URI],
            'name': TEST_CLIENT_NAME,
            'uri': TEST_CLIENT_URI,
            'logo_uri': TEST_LOGO_URI,
            'scope': ['data'],
            'secret': TEST_CLIENT_SECRET,
            'secret_expires_at': 0,
            'registration_access_token': TEST_REGISTRATION_ACCESS_TOKEN
        }
        self.client = Client(key=key, **data)
        self.client.put()

    def tearDown(self):
        super(OauthTest, self).tearDown()

    def log_in_user(self, email=None, is_active=True, is_admin=False):
        email = email or TEST_USER_EMAIL
        super(OauthTest, self).log_in_user(email, is_admin=is_admin)
        response = self.app.get('/gae_login_callback')
        cookies = response.headers.get('Set-Cookie')
        self.auth_cookie = cookies[0:cookies.find(';')] if cookies else None
        self.assertRedirects(response)
        self.current_user = models.User.lookup(email=email)
        self.current_user.active = is_active
        self.current_user.put()
        return self.current_user

    def log_in_admin(self, email=TEST_USER_EMAIL):
        return self.log_in_user(email=email, is_admin=True)

    def log_out_user(self):
        response = self.get('/logout')
        self.assertRedirects(response)
        self.auth_cookie = None
        try:
            del os.environ['USER_EMAIL']
        except KeyError:
            pass
        try:
            del os.environ['USER_ID']
        except KeyError:
            pass
        try:
            del os.environ['USER_IS_ADMIN']
        except KeyError:
            pass

    def get_authorization_code(self, email=None):
        self.user = self.log_in_user(email=email)
        url = '/oauth/v1/auth'
        query_params = {
            'client_id': TEST_CLIENT_ID,
            'redirect_uri': TEST_REDIRECT_URI,
            'response_type': 'code',
            'scope': 'data'
        }
        response = self.get(url, params=query_params)
        if response.status_int == 200:
            self.assertOK(response)
            csrf_string = 'name="csrf_token" type="hidden" value="'
            begin = response.body.find(csrf_string) + len(csrf_string)
            end = response.body.find('"', begin)
            csrf_token = response.body[begin:end]
            if query_params:
                query_params = urlencode(query_params, doseq=True)
                if '?' in url:
                    url += '&'
                else:
                    url += '?'
                url += query_params
            params = {'csrf_token': csrf_token, 'grant': 'Grant'}
            response = self.post(url, params)
        self.assertRedirects(response)
        self.assertRegexpMatches(response.headers['Location'], ur"https://localhost/\?code=.+")
        start = response.headers['Location'].find('=')
        code = response.headers['Location'][start+1:]
        self.log_out_user()
        return code

    def get_tokens(self, email=None):
        url = '/oauth/v1/token'
        code = self.get_authorization_code(email=email)
        params = {
            'code': code,
            'grant_type': 'authorization_code',
            'client_id': TEST_CLIENT_ID,
            'client_secret': TEST_CLIENT_SECRET,
            'redirect_uri': TEST_REDIRECT_URI,
            'scope': 'data'
        }
        response = self.post(url, params)
        self.assertOK(response)
        body = json.loads(response.body)
        self.assertLength(4, body)
        return (body['access_token'], body['refresh_token'])

    def assertMethodNotAllowed(self, response):
        error = u'Response did not return a 405 METHOD NOT ALLOWED (status code was {0})\nBody: {1}'.format(response.status_int, response.body)
        self.assertEqual(response.status_int, 405, error)

    def assertCreated(self, response):
        error = u'Response did not return a 201 CREATED (status code was {0})\nBody: {1}'.format(response.status_int, response.body)
        self.assertEqual(response.status_int, 201, error)

    def assertNoContent(self, response):
        error = u'Response did not return a 204 NO CONTENT (status code was {0})\nBody: {1}'.format(response.status_int, response.body)
        self.assertEqual(response.status_int, 204, error)

    def get(self, url, params=None, headers=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).get(url, params=params, headers=headers)

    def post(self, url, params='', headers=None, upload_files=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).post(url, params=params, headers=headers, upload_files=upload_files)

    def delete(self, url, headers=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).delete(url, headers=headers)

    def post_json(self, url, params, headers=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).post_json(url, params, headers=headers)

    def put_json(self, url, params='', headers=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).put_json(url, params, headers=headers)
示例#35
0
class OauthTest(BaseTest, WebTest):
    APPLICATION = main.application
    URL = None
    ALLOWED = []

    @property
    def url(self):
        return self.URL

    def setUp(self):
        super(OauthTest, self).setUp()
        key = ndb.Key(Client, TEST_CLIENT_ID)
        data = {
            'client_id': TEST_CLIENT_ID,
            'redirect_uris': [TEST_REDIRECT_URI],
            'name': TEST_CLIENT_NAME,
            'uri': TEST_CLIENT_URI,
            'logo_uri': TEST_LOGO_URI,
            'scope': ['data'],
            'secret': TEST_CLIENT_SECRET,
            'secret_expires_at': 0,
            'registration_access_token': TEST_REGISTRATION_ACCESS_TOKEN
        }
        self.client = Client(key=key, **data)
        self.client.put()

    def tearDown(self):
        super(OauthTest, self).tearDown()

    def log_in_user(self, email=None, is_active=True, is_admin=False):
        email = email or TEST_USER_EMAIL
        super(OauthTest, self).log_in_user(email, is_admin=is_admin)
        response = self.app.get('/gae_login_callback')
        cookies = response.headers.get('Set-Cookie')
        self.auth_cookie = cookies[0:cookies.find(';')] if cookies else None
        self.assertRedirects(response)
        self.current_user = models.User.lookup(email=email)
        self.current_user.active = is_active
        self.current_user.put()
        return self.current_user

    def log_in_admin(self, email=TEST_USER_EMAIL):
        return self.log_in_user(email=email, is_admin=True)

    def log_out_user(self):
        response = self.get('/logout')
        self.assertRedirects(response)
        self.auth_cookie = None
        try:
            del os.environ['USER_EMAIL']
        except KeyError:
            pass
        try:
            del os.environ['USER_ID']
        except KeyError:
            pass
        try:
            del os.environ['USER_IS_ADMIN']
        except KeyError:
            pass

    def get_authorization_code(self, email=None):
        self.user = self.log_in_user(email=email)
        url = '/oauth/v1/auth'
        query_params = {
            'client_id': TEST_CLIENT_ID,
            'redirect_uri': TEST_REDIRECT_URI,
            'response_type': 'code',
            'scope': 'data'
        }
        response = self.get(url, params=query_params)
        if response.status_int == 200:
            self.assertOK(response)
            csrf_string = 'name="csrf_token" type="hidden" value="'
            begin = response.body.find(csrf_string) + len(csrf_string)
            end = response.body.find('"', begin)
            csrf_token = response.body[begin:end]
            if query_params:
                query_params = urlencode(query_params, doseq=True)
                if '?' in url:
                    url += '&'
                else:
                    url += '?'
                url += query_params
            params = {'csrf_token': csrf_token, 'grant': 'Grant'}
            response = self.post(url, params)
        self.assertRedirects(response)
        self.assertRegexpMatches(response.headers['Location'],
                                 ur"https://localhost/\?code=.+")
        start = response.headers['Location'].find('=')
        code = response.headers['Location'][start + 1:]
        self.log_out_user()
        return code

    def get_tokens(self, email=None):
        url = '/oauth/v1/token'
        code = self.get_authorization_code(email=email)
        params = {
            'code': code,
            'grant_type': 'authorization_code',
            'client_id': TEST_CLIENT_ID,
            'client_secret': TEST_CLIENT_SECRET,
            'redirect_uri': TEST_REDIRECT_URI,
            'scope': 'data'
        }
        response = self.post(url, params)
        self.assertOK(response)
        body = json.loads(response.body)
        self.assertLength(4, body)
        return (body['access_token'], body['refresh_token'])

    def assertMethodNotAllowed(self, response):
        error = u'Response did not return a 405 METHOD NOT ALLOWED (status code was {0})\nBody: {1}'.format(
            response.status_int, response.body)
        self.assertEqual(response.status_int, 405, error)

    def assertCreated(self, response):
        error = u'Response did not return a 201 CREATED (status code was {0})\nBody: {1}'.format(
            response.status_int, response.body)
        self.assertEqual(response.status_int, 201, error)

    def assertNoContent(self, response):
        error = u'Response did not return a 204 NO CONTENT (status code was {0})\nBody: {1}'.format(
            response.status_int, response.body)
        self.assertEqual(response.status_int, 204, error)

    def get(self, url, params=None, headers=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).get(url, params=params, headers=headers)

    def post(self,
             url,
             params='',
             headers=None,
             upload_files=None,
             bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).post(url,
                                           params=params,
                                           headers=headers,
                                           upload_files=upload_files)

    def delete(self, url, headers=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).delete(url, headers=headers)

    def post_json(self, url, params, headers=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).post_json(url, params, headers=headers)

    def put_json(self, url, params='', headers=None, bearer_token=None):
        if bearer_token is not None:
            if headers is None:
                headers = {}
            headers.update({'Authorization': 'Bearer ' + str(bearer_token)})
        return super(OauthTest, self).put_json(url, params, headers=headers)
示例#36
0
 def test_delete(self):
     response = self.delete(
         self.url, bearer_token=self.client.registration_access_token)
     self.assertNoContent(response)
     self.assertEqual(Client.query().count(), 0)
示例#37
0
 def test_delete_no_auth(self):
     response = self.delete(self.url)
     self.assertUnauthorized(response)
     self.assertEqual(Client.query().count(), 1)
示例#38
0
 def test_delete_invalid_client_id(self):
     response = self.delete(
         self.URL.format('invalid_client_id'),
         bearer_token=self.client.registration_access_token)
     self.assertUnauthorized(response)
     self.assertEqual(Client.query().count(), 1)
示例#39
0
 def test_delete(self):
     response = self.delete(self.url, bearer_token=self.client.registration_access_token)
     self.assertNoContent(response)
     self.assertEqual(Client.query().count(), 0)
示例#40
0
 def test_delete_no_auth(self):
     response = self.delete(self.url)
     self.assertUnauthorized(response)
     self.assertEqual(Client.query().count(), 1)
示例#41
0
 def test_delete_invalid_client_id(self):
     response = self.delete(self.URL.format('invalid_client_id'), bearer_token=self.client.registration_access_token)
     self.assertUnauthorized(response)
     self.assertEqual(Client.query().count(), 1)