Esempio n. 1
0
    def test_random_str(self):
        result = random_str()
        print result
        self.assertEqual(len(result), 8)

        result = random_str(32)
        print result
        self.assertEqual(len(result), 32)
Esempio n. 2
0
 def generate_new(cls):
     user_key = UserKey()
     while True:
         user_key.display_id = utils.random_str(8)
         if cls.query(cls.display_id == user_key.display_id).count() == 0:
             break
     user_key.private_key = utils.random_str(128)
     user_key.expiry_date = cls.get_expiry_date()
     user_key.put()
     return user_key
Esempio n. 3
0
    def test_random_str(self):
        result = random_str()
        self.assertEqual(len(result), 8)

        result1 = random_str(32)
        self.assertEqual(len(result1), 32)

        result2 = random_str(32)
        self.assertEqual(len(result2), 32)

        self.assertNotEqual(result1, result2)
Esempio n. 4
0
    def test_random_str(self):
        result = random_str()
        self.assertEqual(len(result), 8)

        result1 = random_str(32)
        self.assertEqual(len(result1), 32)

        result2 = random_str(32)
        self.assertEqual(len(result2), 32)

        self.assertNotEqual(result1, result2)
Esempio n. 5
0
    def test_negative_auth_post_saml_invalid_saml(self):
        """
        Check exception raised while posting saml with invalid saml, and verify the exception contains correct error messages.
        """
        # get auth first
        head, content = utils.auth_get_auth()
        # get cookie
        cookie = head['set-cookie']
        logging.info("The retrieved cookie from Auth server is '%s'" % str(cookie))
        header = utils.headers
        header['cookie'] = cookie
        logging.debug("The requested headers are '%s'" % str(header))

        http = httplib2.Http()
        # construct invalid responses
        invalid_saml = [utils.random_str()]
        for isa in invalid_saml:
            logging.info("The invalid saml to be tested is '%s'" % str(isa))
            url = 'http://' + utils.auth_server + '/' + utils.auth_partner + '/saml'
            logging.info("The requested url is '%s'" % url)
            saml = {'SAMLResponse': isa}
            h, c = http.request(url, 'POST', headers = header, body = urlencode(saml))
            # assert response head status is 400
            self.assertEqual(int(h['status']), 400)
            # assert error msg is correct
            utils.verify_rest_requetfailed_exception(c, utils.get_exception("InvalidSAML", "AuthPostSamlGrantExceptions"), self)
def gen_machine_list_4_deploy_action(complementary_file_name, config):
    """based on info from config.yaml, generate the expected machine names etc."""
    cc = {}
    cc["machines"] = {}
    for spec in config["azure_cluster"]["virtual_machines"]:
        validate_machine_spec(config, spec)
        for i in range(spec["number_of_instance"]):
            # if explicitly specified a name, we use it
            if "name" in spec:
                vmname = spec["name"]
            else:
                vmname_pref = spec[
                    "prefix"] if "prefix" in spec else "{}-{}".format(
                        config["cluster_name"], spec["role"][0])
                vmname = vmname_pref + '-' + random_str(6)
            vmname = vmname.lower()
            cc["machines"][vmname] = {'role': spec["role"]}
            for k, v in spec.items():
                if k == "number_of_instance":
                    continue
                cc["machines"][vmname][k] = v
            if "kube_label_groups" not in spec:
                cc["machines"][vmname]["kube_label_groups"] = []
                for role in spec["role"]:
                    if role in config["default_kube_labels_by_node_role"]:
                        cc["machines"][vmname]["kube_label_groups"].append(
                            role)
    if complementary_file_name is not None:
        complementary_file_name = ACTION_YAML if complementary_file_name == '' else complementary_file_name
        with open(complementary_file_name, 'w') as outfile:
            yaml.safe_dump(cc, outfile, default_flow_style=False)
    return cc
Esempio n. 7
0
def route_login(request):
    """
    登录页面的路由函数
    """
    headers = {
        'Content-Type': 'text/html',
        # 'Set-Cookie': 'height=169; gua=1; pwd=2; Path=/',
    }
    # log('login, headers', request.headers)
    log('login, cookies', request.cookies)
    username = current_user(request)
    log('先前用户', username)
    if request.method == 'POST':
        form = request.form()
        u = User.new(form)
        if u.validate_login():
            # 设置一个随机字符串来当令牌使用
            session_id = random_str()
            session[session_id] = u.username
            log('当前用户', u.username)
            headers['Set-Cookie'] = f'user={session_id}'
            # 下面是把用户名存入 cookie 中
            # headers['Set-Cookie'] = 'user={}'.format(u.username)
            result = '登录成功'
        else:
            result = '用户名或者密码错误'
    else:
        result = ''
    body = template('login.html')
    body = body.replace('{{result}}', result)
    body = body.replace('{{username}}', username)
    header = response_with_headers(headers)
    r = header + '\r\n' + body
    # log('login 的响应', r)
    return r.encode(encoding='utf-8')
    def _input_user_name(self):
        time.sleep(2)
        #随机生成用户名和密码
        user_name = utils.get_one_letters() + utils.random_str(11)
        print("生成用户名: " + user_name)
        #填入用户名
        self._input_text(user_name)
        #点击下一步
        # d.screen.on()
        d(text="下一步").click()
        time.sleep(2)
        #检查用户名是否已被占用
        # d.screen.on()
        um_is_has = d(text="该邮箱地址已被注册")
        # print(um_is_has)
        # 邮箱已被注册
        if um_is_has.exists:
            #点击确定
            d(text="确定").click()
            #清空用户名
            for num in range(0, 20):
                d.press("delete")

            #重新执行注册逻辑
            self._input_user_name()

        else:
            #邮箱可以被注册
            self.user_name = user_name
            #点击下一步
            d(text="下一步").click()
Esempio n. 9
0
def route_login(request):
    """
    登录页面的路由函数
    """
    headers = {
        'Content-Type': 'text/html',
        # 'Set-Cookie': 'a=b; c=d'
    }
    # username 默认是有课, session_id 默认是 ''
    username = current_user(request)

    if request.method == 'POST':
        # 得到 post 过来的 body 数据
        # 说明是第一次登录
        form = request.form()
        # 根据发送来的数据创建一个对象, 和数据库里面的对象比较
        u = User(form)
        if u.validate_login():
            session_id = random_str()
            session[session_id] = u.username
            # session 变为 {'fdsafeaf1213': '游客注册的用户名'}
            headers['Set-Cookie'] = f'user={session_id}'
            result = '登录成功'
        else:
            result = '用户名或者密码错误'
    else:
        # Get 请求, 打开这个页面的时候的处理
        result = ''
    body = j_template('login.html', username=username, result=result)
    # 拼接 header
    return http_response(body, headers=headers)
Esempio n. 10
0
def invite_member(project_id):
    user_id = get_jwt_identity()
    user = User.query.filter_by(user_id=user_id).first_or_404()
    project = Project.query.filter_by(project_id=project_id).first_or_404()
    if user not in project.members:
        return jsonify({'error': 'You dont have rights.'}), 401

    # Create invite
    body = request.get_json()
    token = random_str()
    invite = ProjectInvite(
        sender_id=user_id,
        project_id=project_id,
        token=token,
        email=body['email'],
        message=body['message'],
        role=body['role'],
    )
    db.session.add(invite)
    db.session.commit()

    # Send email
    send_invite_member(user, body['email'], token, body['message'])

    # Construct response
    return jsonify(project_invite_schema.dump(invite))
Esempio n. 11
0
def api_nova():
    try_nova = get_nova(request, 'nova-pool')
    if try_nova['status'] != 200:
        return return_json(None, try_nova['error'], try_nova['status'])
    nova = try_nova['data']
    ncfg = dict(cfg.items('nova-pool'))
    response = return_json(None, 'Method Not Allowed (%s): %s'%(request.method, request.url), 405)
    # list all VMs in nova-pool
    if request.method == 'GET':
        res = nova.server()
        response = return_json(res['data']) if res['status'] == 200 else return_json(None, res['error'], res['status'])
    # launch VM in nova pool - add to DB
    elif request.method == 'POST':
        try_ipydb = get_ipydb(request, False)
        if try_ipydb['status'] != 200:
            return return_json(None, try_ipydb['error'], try_ipydb['status'])
        ipydb = try_ipydb['data']
        name  = request.args['name'] if 'name' in request.args else 'ipynb_'+utils.random_str()
        res   = nova.create(name, ncfg["image"], ncfg["flavor"], ncfg["security"], ncfg["vm_key"])
        if res['status'] == 200:
            vmid = res['data']['id']
            while len(res['data']['addresses']) == 0:
                time.sleep(30)
                res = nova.server(vmid)
            ipydb.insert(vmid, name, res['data']['addresses'][0], ncfg["vm_key"], res['status'])
            response = return_json(res['data'])
        else:
            response = return_json(None, res['error'], res['status'])
        ipydb.exit()
    return response
Esempio n. 12
0
def route_login(request):
    """
    登录页面的路由函数
    """
    headers = {
        'Content-Type': 'text/html',
        # 'Set-Cookie': 'height=169; gua=1; pwd=2; Path=/',
    }
    if request.method == 'POST':
        form = request.form()
        u = User.new(form)
        if u.validate_login():
            user = User.find_by(username=u.username)
            # 设置 session
            # 设置一个随机字符串来当令牌使用
            session_id = random_str()
            session[session_id] = user.id
            headers['Set-Cookie'] = f'user={session_id}'
            # 下面是把用户名存入 cookie 中
            # headers['Set-Cookie'] = 'user={}'.format(u.username)
            # log('headers response', headers)
            # 登录后重定向到 /
            return redirect('/', headers)
    # 显示登录页面
    body = template('login.html')
    return http_response(body, headers=headers)
Esempio n. 13
0
 def put(self, resource, status, expires=DEFAULT_EXPIRES, priority=0, tag=None, type=None):
     debug(
         "PUT | %s:%s | Received put request: resource %r, status %r, expires %r, priority %r, tag %r, type %r"
         % (resource, tag, resource, status, expires, priority, tag, type)
     )
     self.stats_put += 1
     if not tag:
         tag = utils.random_str(10)
         debug("PUT | %s:%s | Generate tag for presence: %r." % (resource, tag, tag))
     if expires > self.MAX_EXPIRES:
         debug(
             "PUT | %s:%s | Max expires time exceeded. Requested %r, allowed %r. Raise exception."
             % (resource, tag, expires, self.MAX_EXPIRES)
         )
         raise PresenceError("Expire limit exeeded")
     if status not in self.allowed_statuses:
         debug(
             "PUT | %s:%s | Unknown status value: %r. Allowed statuses: %r. Raise exception."
             % (resource, tag, status, self.allowed_statuses)
         )
         raise PresenceError("Unknown status value: %r. Allowed: %r" % (status, self.allowed_statuses))
     presence = {
         "resource": resource,
         "tag": tag,
         "status": status,
         "expires": expires,
         "priority": priority,
         "type": type,
     }
     yield self._storePresence(resource, tag, presence)
     self._setExpireTimer(resource, tag, expires)
     self._notifyWatchers(resource)
     debug("PUT | %s:%s | Put presence for resource %r with tag %r: %r" % (resource, tag, resource, tag, presence))
     defer.returnValue(tag)
Esempio n. 14
0
def route_login(request):
    """
    登录页面的路由函数
    """
    headers = {
        'Content-Type': 'text/html',
        # 'Set-Cookie': 'a=b; c=d'
    }
    # username 默认是有课, session_id 默认是 ''
    username = current_user(request)

    if request.method == 'POST':
        # 得到 post 过来的 body 数据
        # 说明是第一次登录
        form = request.form()
        # 根据发送来的数据创建一个对象, 和数据库里面的对象比较
        u = User(form)
        if u.validate_login():
            session_id = random_str()
            session[session_id] = u.username
            # session 变为 {'fdsafeaf1213': '游客注册的用户名'}
            headers['Set-Cookie'] = f'user={session_id}'
            result = '登录成功'
        else:
            result = '用户名或者密码错误'
    else:
        # Get 请求, 打开这个页面的时候的处理
        result = ''
    body = template('login.html')
    body = body.replace('{{result}}', result)
    body = body.replace('{{username}}', username)
    # 拼接 header
    header = response_with_headers(headers)
    response = header + '\r\n' + body
    return response.encode(encoding='utf-8')
Esempio n. 15
0
    def set_params(self, **kwargs):
        self.params = {}
        for (k, v) in kwargs.items():
            self.params[k] = smart_str(v)

        self.params["nonce_str"] = random_str(32)
        self.params["trade_type"] = self.trade_type
        self.params.update(self.common_params)
Esempio n. 16
0
    def set_params(self, **kwargs):
        self.params = {}
        for (k, v) in kwargs.items():
            self.params[k] = smart_str(v)

        self.params["nonce_str"] = random_str(32)
        if self.trade_type:
            self.params["trade_type"] = self.trade_type
        self.params.update(self.common_params)
Esempio n. 17
0
 def _get_json_js_api_params(self, prepay_id):
     js_params = {
         "appId": self.appid,
         "timeStamp": "%d" % time.time(),
         "nonceStr": random_str(32),
         "package": "prepay_id=%s" % prepay_id,
         "signType": "MD5",
     }
     js_params["paySign"] = calculate_sign(js_params, self.api_key)
     return js_params
Esempio n. 18
0
 def _get_json_js_api_params(self, prepay_id):
     js_params = {
                  "appId": self.appid,
                  "timeStamp": "%d" % time.time(),
                  "nonceStr": random_str(32),
                  "package": "prepay_id=%s" % prepay_id,
                  "signType": "MD5",
                 }
     js_params["paySign"] = calculate_sign(js_params, self.api_key)
     return js_params
Esempio n. 19
0
 def test_negative_get_auth_horizon_partner_not_exist(self):
     """
     Check exception raised while getting auth for not existent partner, and verify the exception contains correct error messages.
     """
     nosub = utils.random_str()
     logging.info("The not existent subdomain to be tested is '%s'" % nosub)
     with self.assertRaises(rest.RequestFailed) as e:
         self.res.get('/auth/config/' + (nosub), headers=utils.headers)
     self.assertEqual(self.res.response.status, 400)
     # verify the exception is expected
     utils.verify_rest_requetfailed_exception(e,utils.get_exception('UnknownSubdomain', 'GetAuthExceptions'), self) 
	def post(self):
		try:
			upload_path = os.path.join(os.path.dirname(__file__),config.temp_dir)
			key = utils.random_str(20)
			tempfile = os.path.join(upload_path,key)
			filemeta = self.request.files.get('file')[0]
			with open(tempfile,'wb') as op:
				op.write(filemeta.get('body'))
			self.write(self.__upload(key,tempfile))
		except Exception,e:
			logger.error(e)
			self.write('error')
Esempio n. 21
0
 def test_negative_get_tokens_invalid_token(self):
     """
     Check exception raised while getting tokens information with invalid tokens, and verify the exception contains correct error messages.
     """
     malpayloads = [utils.random_str()]
     for mp in malpayloads:
         logging.info("The malpayload acting unauthorized client is '%s'" % mp)
         with self.assertRaises(Exception) as e:
             self.res.get('/tokens/'+mp, headers=utils.headers)
         self.assertEqual(self.res.response.status, 404)
         # verify the retrieved exception is expected
         utils.verify_rest_requetfailed_exception(e, utils.get_exception('InvalidToken', 'GetTokensExceptions'), self)
Esempio n. 22
0
 def test_negative_delete_tokens_not_exist(self):
     """
     Delete tokens not exist and check the 'revoked_token_num' is '0'
     """
     r = self.res.delete('/tokens/'+utils.random_str(), headers=utils.headers)
     logging.info("Return response is '%s'" % r)
     self.assertEqual(self.res.response.status, 200)
     # convert string to dictionary
     rd = ast.literal_eval(r)
     logging.info("Return response in dictionary format is '%s'" % rd)
     # assert 'revoked_token_num' is 1
     self.assertEqual(rd['revoked_token_num'], 0, "The 'revoked_token_num' is not equal to 0")
Esempio n. 23
0
def route_login(request):
    headers = {
        'Content-Type': 'text/html',
    }
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_login():
            user = User.find_by(username=u.username)
            session_id = random_str()
            session[session_id] = user.id
            headers['Set-Cookie'] = 'user={}'.format(session_id)
            return redirect('/', headers)
    return html_response('login.html')
Esempio n. 24
0
def get_phone(url):
    phone = []
    for x in xrange(15, 30):
        res = requests.get(url % x)
        soup = bs(res.content, 'lxml')
        li = [
            x.text.strip() + '|' + random_str()
            for x in soup.find('div', attrs={
                'class': 'ListLink2'
            }).find_all('li')
        ]
        phone.extend(li)
        time.sleep(1.25)
    ipdb.set_trace()
Esempio n. 25
0
 def test_negative_delete_tokens_condition_user_not_exist(self):
     """
     Delete tokens with not existing user_id and check the 'revoked_token_num' '0'
     """
     malpayloads = [str(random.randint(0,99)), utils.random_str()]
     for mp in malpayloads:
         logging.info("The malpayload acting not existent user_id is '%s'" % mp)
         r = self.res.delete('/tokens/?user_id='+mp, headers=utils.headers)
         self.assertEqual(self.res.response.status, 200)
         # convert string to dictionary
         rd = ast.literal_eval(r)
         logging.info("Return response in dictionary format is '%s'" % rd)
         # assert 'revoked_token_num' is 0
         self.assertEqual(rd['revoked_token_num'], 0, "The 'revoked_token_num' is not 0")
Esempio n. 26
0
def render_infra_and_nfs(complementary_file_name, config):
    """based on info from config.yaml, generate the expected machine names etc."""

    # generate infra and nfs vmname, infer infra ip, dump to cluster.yaml, skip nfs ip

    # cloud_init_deploy.py render templates.

    # deploy master and nfs node.

    # complete nfs mount ip info in cluster.yaml['mountpoints']
    cc = {}
    cc["cluster_name"] = config["cluster_name"]
    cc["useclusterfile"] = True
    cc["deploydockerETCD"] = False
    cc["platform-scripts"] = "ubuntu"
    cc["basic_auth"] = "%s,admin,1000" % uuid.uuid4().hex[:16]
    domain_mapping = {
        "regular":
        "%s.cloudapp.azure.com" % config["azure_cluster"]["azure_location"],
        "low":
        config.get("network_domain",
                   config["azure_cluster"]["default_low_priority_domain"])
    }
    cc["machines"] = {}
    for spec in config["azure_cluster"]["vm"]:
        assert "role" in spec and ((set(spec["role"]) - set(config["allroles"])) == set()) and \
            "must specify valid role for vm!"
        for i in range(spec["num"]):
            # if explicitly specified a name, we use it
            if "name" in spec:
                assert spec[
                    "num"] == 1 and "cannot overwirte name for multiple machines one time!"
                vmname = spec["name"]
            else:
                vmname_pref = spec[
                    "prefix"] if "prefix" in spec else "{}-{}".format(
                        config["cluster_name"], '-'.join(spec["role"]))
                vmname = vmname_pref + '-' + random_str(6)
            cc["machines"][vmname] = {'role': spec["role"]}

    cc["etcd_node_num"] = len(
        [mv for mv in cc["machines"].values() if 'infra' in mv['role']])
    cc["admin_username"] = config["cloud_config"]["default_admin_username"]
    cc["network"] = {"domain": domain_mapping[config["priority"]]}
    if complementary_file_name != '':
        with open(complementary_file_name, 'w') as outfile:
            yaml.dump(cc, outfile, default_flow_style=False)
    return cc
 def _input_password(self):
     time.sleep(2)
     print("输入密码")
     #随机生成密码
     self.pass_word = utils.get_one_letters() + utils.random_str(
         6) + utils.get_one_number()
     #点击第一行密码输入框
     d(resourceId="com.netease.mail:id/first_password").click()
     #键入密码
     self._input_text(self.pass_word)
     #点击第二行密码输入框
     d(resourceId="com.netease.mail:id/second_password").click()
     #键入密码
     self._input_text(self.pass_word)
     #点击下一步
     d(text="下一步").click()
Esempio n. 28
0
 def test_negative_auth_get_auth_invalid_response_type(self):
     """
     Check exception raised while getting auth for invalid respone type other than 'token', and verify the exception contains correct error messages.
     """
     http = httplib2.Http()
     # construct invalid responses
     invalid_response = ['', utils.random_str()]
     for ir in invalid_response:
         logging.info("The invalid response type to be tested is '%s'" % str(ir))
         url = 'http://' + utils.auth_server + '/' + utils.auth_partner + '/authorize?' + 'response_type=' + ir + '&client_id=' + utils.auth_client_id
         logging.info("The requested url is '%s'" % url)
         h,c = http.request(url, 'GET', headers = utils.headers)
         # assert it's a bad request
         self.assertEqual(int(h['status']), 400)
         # assert the exception content is correct
         utils.verify_rest_requetfailed_exception(c, utils.get_exception('UnknownResponseType', 'AuthGetAuthExceptions'), self, ir)
Esempio n. 29
0
def route_login(request):
    """
    登录页面的路由函数
    """
    # 设置headers
    headers = {
        'Content-Type': 'text/html',
    }
    log('login, cookies', request.cookies)
    if request.method == 'POST':
        # 调用 Request 类的 form 方法来处理 request 的 body 得到字典格式的body,
        # {'messages': 'goo', 'id': '22'}
        form = request.form()
        # 把 body 传给新实例化的u,这里的body其实就是用户登录输入的名字和密码
        u = User(form)
        # 验证u的登录是否合法
        if u.validate_login():
            # 在数据文件中找到登录用户的用户名
            user = User.find_by(username=u.username)
            # 设置 session(每次登录都会设置新的session给user.id)
            session_id = random_str()
            session[session_id] = user.id
            # 把代表用户名的session_id传给headers
            headers['Set-Cookie'] = 'user={}'.format(session_id)
            log('headers response', headers)
            # 登录后定向到 /
            return redirect('/', headers)
    userid = current_user(request)
    if userid != -1:
        username = '******'
        result = '未登录或登录失败'
    else:
        user = User.find(id=userid)
        username = user.__repr__()
        result = '登录成功'
    # 显示登录页面
    # template函数接受一个路径和一系列参数,读取模板并渲染返回
    body = template('login.html')
    body = body.replace('{{result}}', result)
    body = body.replace('{{username}}', str(username))
    # 通过response_with_headers函数拼接响应头和headers
    header = response_with_headers(headers)
    # 拼接 header 和 body 形成一个完整的HTTP响应
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
Esempio n. 30
0
 def putStatus(self, resource, pdoc, expires, priority=0, tag=None):
     if expires > self.MAX_EXPIRE_TIME:
         raise PresenceServiceError("Expire limit exeeded")
     if not tag:
         tag = utils.random_str(10)
     expiresat = expires + reactor.seconds()
     table = self._resourceTable(resource)
     rset = self._resourcesSet()
     status = Status(pdoc, expiresat, priority)
     d1 = self.storage.hset(table, tag, status.serialize())
     d2 = self.storage.sadd(rset, resource)
     d3 = self._notifyWatchers(resource)
     d4 = self._setStatusTimer(resource, tag, expires)
     yield defer.DeferredList([d1, d2, d3, d4])
     stats['presence_put_statuses'] += 1
     log.msg("Put status (resource: %r, tag: %r, presence document: %r, expires: %r, priority: %r) ==> result: ok" %\
             (resource, tag, pdoc, expires, priority))
     defer.returnValue(tag)
Esempio n. 31
0
 def test_negative_auth_get_auth_invalid_client_id(self):
     """
     Check exception raised while getting auth for invalid client id, and verify the exception contains correct error messages.
     """
     http = httplib2.Http()
     # construct invalid client id 
     invalid_client = ['', utils.random_str(), '  ']
     for ic in invalid_client:
         logging.info("The invalid client id to be tested is '%s'" % str(ic))
         url = 'http://' + utils.auth_server + '/' + utils.auth_partner + '/authorize?' + 'response_type=token' + '&client_id=' + ic
         logging.info("The requested url is '%s'" % url)
         h,c = http.request(url, 'GET', headers = utils.headers)
         logging.debug("The retrieved header is '%s'" % str(h))
         logging.debug("The retrieved content is '%s'" % str(c))
         # assert it's a bad request
         self.assertEqual(int(h['status']), 400)
         # assert the exception content is correct
         utils.verify_rest_requetfailed_exception(c, utils.get_exception('UnknownClient', 'AuthGetAuthExceptions'), self)
Esempio n. 32
0
 def putStatus(self, resource, pdoc, expires, priority=0, tag=None):
     if expires > self.MAX_EXPIRE_TIME:
         raise PresenceServiceError("Expire limit exeeded")
     if not tag:
         tag = utils.random_str(10)
     expiresat = expires + reactor.seconds()
     table = self._resourceTable(resource)
     rset = self._resourcesSet()
     status = Status(pdoc, expiresat, priority)
     d1 = self.storage.hset(table, tag, status.serialize())
     d2 = self.storage.sadd(rset, resource)
     d3 = self._notifyWatchers(resource)
     d4 = self._setStatusTimer(resource, tag, expires)
     yield defer.DeferredList([d1, d2, d3, d4])
     stats['presence_put_statuses'] += 1
     log.msg("Put status (resource: %r, tag: %r, presence document: %r, expires: %r, priority: %r) ==> result: ok" %\
             (resource, tag, pdoc, expires, priority))
     defer.returnValue(tag)
Esempio n. 33
0
def login(request):
    """
    登录页面的路由函数
    """
    headers = {}
    result = ''
    # log('login, headers: ', request.headers)
    # log('login, cookies: ', request.cookies)
    cur_user = current_user(request)
    if cur_user is not None:
        username = cur_user.username
    else:
        username = "******"

    if request.method == 'POST':
        form = request.form()
        u = User(form)
        # 登录验证成功
        if u.validate_login():
            # 查找用户
            user = User.find_by(username=u.username)

            # 设置一个随机字符串来当令牌使用
            session_id = random_str()
            # session[session_id] = u.username
            session[session_id] = user.id
            headers['Set-Cookie'] = 'user={}'.format(session_id)

            # 下面是把用户名存入 cookie 中
            # headers['Set-Cookie'] = 'user={}'.format(u.username)

            # 登录成功后重定向到主页
            return redirect('/', headers=headers)

        # 登录验证失败
        else:
            result = '用户名或者密码错误'

    # 返回登录页面
    log("返回登录页面")
    body = template('login.html')
    body = body.replace('{{result}}', result)
    body = body.replace('{{username}}', username)
    return http_response(body, headers=headers)
Esempio n. 34
0
def register():
    body = request.get_json()
    errors = register_schema.validate(body)
    if errors:
        return jsonify({'error': errors}), 400
    user = User(**body)
    user.hash_password()
    user.email_verification_token = random_str()

    # Create default project for user
    # INSERT INTO project (name) VALUES (%s)
    # INSERT INTO user (...) VALUES ()
    # INSERT INTO user_project (user_id, project_id, `role`) VALUES (%s, %s, %s)
    project = Project(name='First project')
    user_project = UserProject(user=user, project=project, role=UserProjectRole.ADMIN)
    project.user_project.append(user_project)
    db.session.add(user)
    db.session.commit()
    welcome_email(user)
    return jsonify(user_schema.dump(user)), 201
Esempio n. 35
0
 def test_negative_auth_get_config_invalid_partner(self):
     """
     Check exception raised while getting auth for invalid partner, and verify the exception contains correct error messages.
     """
     # get config 
     headers = utils.headers
     # compose basic auth
     headers['Authorization'] = "Basic %s" % base64.encodestring('%s:%s' % (utils.auth_client_id, utils.auth_client_secret))[:-1]
     invalid_partners = [utils.random_str()]
     for ip in invalid_partners:
         logging.info("The invalid partner is '%s'" % ip)
         url = 'http://' + utils.auth_server + '/' + ip + '/config'
         logging.debug("The requested url is '%s'" % str(url))
         h, c = self.http.request(url, 'GET', headers = utils.headers)
         logging.debug("The response head is '%s'" % str(h))
         logging.debug("The response body is '%s'" % str(c))
         # assert status code is '400'
         self.assertEqual(int(h['status']), 400)
         # verify exception content is correct
         utils.verify_rest_requetfailed_exception(c, utils.get_exception("UnknownSubdomain", "AuthGetConfigExceptions"), self)
Esempio n. 36
0
 def start_session(username, **kwargs):
     """
     after user is successfully authenticated, start user session
     if user is not in local database, add them
     """
     remember = kwargs.get("remember", True)
     u = Users.load_user(username)
     # if user does not exist, create it with random local password
     if u is None:
         u = Users({"username": username, "password": random_str()})
         if not u._auto_create():
             if username in Users.RESERVED:
                 abort(400, "Username \"%s\" is reserved" % username)
             else:
                 abort(500, "Failed to create user session")
     login_user(u, remember=remember)
     current_app.mongo.db.users.update_one(
         {"username": u.username}, {"$set": {
             "last_login": time.time()
         }})
Esempio n. 37
0
 def test_negative_auth_post_token_invalid_SAML(self):
     """
     Check exception raised while posting token with invalid SAML, and verify the exception contains correct error messages.
     """
     headers = utils.headers
     # compose basic auth
     headers['Authorization'] = "Basic %s" % base64.encodestring('%s:%s' % (utils.auth_client_id, utils.auth_client_secret))[:-1]
     logging.debug("The requested header is '%s'" % str(headers))
     # construct invalid responses
     invalid_SAML= [utils.random_str()]
     for ism in invalid_SAML:
         logging.info("The invalid SAML to be tested is '%s'" % str(ism))
         logging.info("The requested url is '%s'" % self.url)
         # post token 
         body = {'grant_type': 'http://oauth.net/grant_type/assertion/saml/2.0/bearer', 'assertion': ism}
         h, c = self.http.request(self.url, 'POST', headers = headers, body = urllib.urlencode(body))
         # assert response head status is 400
         self.assertEqual(int(h['status']), 400)
         # assert error msg is correct
         utils.verify_rest_requetfailed_exception(c, utils.get_exception("InvalidSAML", "AuthPostTokenExceptions"), self)
Esempio n. 38
0
 def test_negative_auth_post_token_invalid_partner(self):
     """
     Check exception raised while getting auth for invalid partner, and verify the exception contains correct error messages.
     """
     # get config 
     headers = utils.headers
     # compose basic auth
     headers['Authorization'] = "Basic %s" % base64.encodestring('%s:%s' % (utils.auth_client_id, utils.auth_client_secret))[:-1]
     body = {'grant_type': 'http://oauth.net/grant_type/assertion/saml/2.0/bearer', 'assertion': utils.SAMLResponse}
     invalid_partners = [utils.random_str()]
     for ip in invalid_partners:
         logging.info("The invalid partner is '%s'" % ip)
         url = 'http://' + utils.auth_server + '/' + ip + '/token'
         logging.debug("The requested url is '%s'" % str(url))
         h, c = self.http.request(url, 'POST', headers = utils.headers, body = urllib.urlencode(body))
         logging.debug("The response head is '%s'" % str(h))
         logging.debug("The response body is '%s'" % str(c))
         # assert status code is '400'
         self.assertEqual(int(h['status']), 400)
         # verify exception content is correct
         utils.verify_rest_requetfailed_exception(c, utils.get_exception("UnknownSubdomain", "AuthPostTokenExceptions"), self)
Esempio n. 39
0
def api_nova():
    try_nova = get_nova(request, 'nova-pool')
    if try_nova['status'] != 200:
        return return_json(None, try_nova['error'], try_nova['status'])
    nova = try_nova['data']
    ncfg = dict(cfg.items('nova-pool'))
    response = return_json(
        None, 'Method Not Allowed (%s): %s' % (request.method, request.url),
        405)
    # list all VMs in nova-pool
    if request.method == 'GET':
        res = nova.server()
        response = return_json(
            res['data']) if res['status'] == 200 else return_json(
                None, res['error'], res['status'])
    # launch VM in nova pool - add to DB
    elif request.method == 'POST':
        try_ipydb = get_ipydb(request, False)
        if try_ipydb['status'] != 200:
            return return_json(None, try_ipydb['error'], try_ipydb['status'])
        ipydb = try_ipydb['data']
        name = request.args[
            'name'] if 'name' in request.args else 'ipynb_' + utils.random_str(
            )
        res = nova.create(name, ncfg["image"], ncfg["flavor"],
                          ncfg["security"], ncfg["vm_key"])
        if res['status'] == 200:
            vmid = res['data']['id']
            while len(res['data']['addresses']) == 0:
                time.sleep(30)
                res = nova.server(vmid)
            ipydb.insert(vmid, name, res['data']['addresses'][0],
                         ncfg["vm_key"], res['status'])
            response = return_json(res['data'])
        else:
            response = return_json(None, res['error'], res['status'])
        ipydb.exit()
    return response
Esempio n. 40
0
    def get_pwreset_key(username):
        # 'routing' handles the authentication, user should be authenticated
        # in order to request a pwreset link (usually admin)
        # this may change if we get email functionality.  Note, this function
        # may not be aware of routing so will not be used to generate link.
        # Instead, only pwreset key is returned on success.
        u = Users.load_user(username)
        if u is None:
            abort(404, "User(%s) not found" % username)

        # non-admins can only get a pwreset link for thier account
        if g.user.role != Roles.FULL_ADMIN and username != g.user.username:
            abort(403, MSG_403)

        # create a temporary random key and timestamp it
        key = random_str()
        current_app.mongo.db.users.update_one(
            {"username": u.username},
            {"$set": {
                "pw_reset_key": key,
                "pw_reset_timestamp": time.time()
            }})
        return key
Esempio n. 41
0
 def order(self, orderQty, stop=0):
     '''
     This is 'Market' order
     'buy' if orderQty is positive
     'sell' if orderQty is nagative
     '''
     clOrdID = 'Daxiang_' + u.random_str()
     side = 'Buy' if orderQty > 0 else 'Sell'
     if stop == 0:
         # market order
         orderType = 'Market'
         u.retry(lambda: self.client.Order.Order_new(symbol=s.SYMBOL,
                                                     ordType=orderType,
                                                     clOrdID=clOrdID,
                                                     side=side,
                                                     orderQty=orderQty).
                 result())
         u.logging_order(id=clOrdID,
                         type=orderType,
                         side=side,
                         qty=orderQty,
                         price=self.get_market_price())
     else:
         # stop order
         orderType = 'Stop'
         u.retry(lambda: self.client.Order.Order_new(symbol=s.SYMBOL,
                                                     ordType=orderType,
                                                     clOrdID=clOrdID,
                                                     side=side,
                                                     orderQty=orderQty,
                                                     stopPx=stop).result())
         u.logging_order(id=clOrdID,
                         type=orderType,
                         side=side,
                         qty=orderQty,
                         stop=stop)
Esempio n. 42
0
def register_app_163(adb):
    codeUtil = VeriCodeUtil()

    adb.shell_command("am force-stop  com.netease.mail")
    adb.shell_command(
        "am start -n com.netease.mail/com.netease.mobimail.activity.LaunchActivity"
    )
    # 随机生成用户名和密码
    user_name = utils.get_one_letters() + utils.random_str(11)
    pass_word = utils.get_one_letters() + utils.random_str(
        6) + utils.get_one_number()
    time.sleep(5)
    eleUtil = Element()
    evevt = Event()
    #点击注册
    time.sleep(3)
    print("点击注册")
    regBtn = eleUtil.findElementByName(u"注册新邮箱")
    # adb.shell_command("input tap " + regBtn[0] + " " + regBtn[1])
    evevt.touch(regBtn[0], regBtn[1])
    return
    time.sleep(2)
    #输入账号
    print("输入账号")
    adb.shell_command("input text " + user_name)
    print("账号输入完毕,点击下一步")
    adb.shell_command("input tap 538 660")

    #密码
    time.sleep(2)
    print("密码输入")
    adb.shell_command("input text " + pass_word)
    print("再次输入密码")
    adb.shell_command("input tap 285 615")
    adb.shell_command("input text " + pass_word)
    print("密码输入完毕,点击下一步")
    adb.shell_command("input tap 542 822")

    #手机号输入
    time.sleep(2)
    #点击输入框
    print("点击手机号码输入框")
    adb.shell_command("input tap 575 747")
    # 对接接码平台 获取电话和验证码
    phone = utils.get_phone_no('网易')
    print("获取到手机号码: " + phone)
    adb.shell_command("input text " + phone)
    adb.shell_command("input tap 516 930")
    # time.sleep(10)
    # input("input: ")

    time.sleep(1)
    print("更换一次验证码")
    check_code(adb, codeUtil)

    # checkCode = 1
    # while checkCode == 1:
    e = eleUtil.findElementById("alert_dialog_content_msg")
    print(e)
    print("下一步")
    print("点击输入验证码框")
    time.sleep(10)
    adb.shell_command("input tap 203 451")
    ver_code_str = utils.get_message("网易", phone)
    var_code_arr = re.findall(r'\d+', ver_code_str)
    print(var_code_arr)
    ver_code = " ".join(var_code_arr)
    print("获取到的验证码:" + ver_code)
    adb.shell_command("input text " + ver_code)
    print("点击同意协议")
    adb.shell_command("input tap 116 776")
    print("点击完成注册")
    adb.shell_command("input tap 577 644")
Esempio n. 43
0
def register_163():
    try:
        driver = utils.init_chrome()
        # driver = utils.init_IE()
        # 发送请求 打开注册页面
        driver.get('https://mail.163.com/register/index.htm?from=163mail')
        # 随机生成用户名和密码
        user_name = utils.get_one_letters() + utils.random_str(11)
        pass_word = utils.get_one_letters() + utils.random_str(
            6) + utils.get_one_number()

        # 定位元素框 填写用户名密码
        driver.find_element_by_id('username').send_keys(user_name)
        # 用户名是否有效
        user_name_tip_div = driver.find_element_by_xpath(
            '/html/body/div[2]/div/div/div[2]/div[2]/div[1]/div[3]')
        tip_display = user_name_tip_div.is_displayed()
        if tip_display:
            return None, None, None

        # 填写密码
        driver.find_element_by_id('password').send_keys(pass_word)
        # 密码是否有效
        pwd_tip_div = driver.find_element_by_xpath(
            '/html/body/div[2]/div/div/div[2]/div[2]/div[2]/div')
        pwd_tip = pwd_tip_div.get_attribute('innerText')
        err_msg = '密码过于简单,请尝试“字母+数字”的组合'
        if pwd_tip == err_msg:
            return None, None, None

        # 对接接码平台 获取电话和验证码
        phone = utils.get_phone_no('简书')
        driver.find_element_by_id("phone").send_keys(phone)
        time.sleep(3)
        # 电话是否有效
        phone_tip_div = driver.find_element_by_xpath(
            '/html/body/div[2]/div/div/div[2]/div[2]/div[3]/div[2]')
        phone_tip = phone_tip_div.get_attribute('innerText')
        err_msg = '该手机号关联帐号太多'
        if phone_tip == err_msg:
            # 拉黑当前手机号并退出
            utils.block_phone_no(phone)
            return None, None, None

        # 点击同意服务条款
        driver.find_element_by_xpath(
            '/html/body/div[2]/div/div/div[2]/div[2]/div[4]/span').click()
        time.sleep(2)

        # 点击手动发送
        driver.find_element_by_xpath(
            '/html/body/div[2]/div/div/div[2]/div[2]/div[3]/div[1]/div[1]/div[2]/a'
        ).click()
        time.sleep(3)
        show = driver.find_element_by_xpath(
            '/html/body/div[2]/div/div/div[2]/div[2]/div[3]/div[1]/div[2]'
        ).is_displayed()
        if show:
            # 获取收信人号码
            to_phone_span = driver.find_element_by_xpath(
                '/html/body/div[2]/div/div/div[2]/div[2]/div[3]/div[1]/div[2]/div[2]/p[2]/span'
            )
            to_phone = to_phone_span.get_attribute('innerText')
            # 获取要发送的内容
            send_msg_span = driver.find_element_by_xpath(
                '/html/body/div[2]/div/div/div[2]/div[2]/div[3]/div[1]/div[2]/div[2]/p[1]/span'
            )
            send_msg = send_msg_span.get_attribute('innerText')
            # 发送验证短信
            utils.send_msg(phone, to_phone, send_msg)
        else:
            return None, None, None
        time.sleep(5)
        # 点击立即注册按钮
        driver.find_element_by_xpath(
            '/html/body/div[2]/div/div/div[2]/div[2]/div[5]/a[1]').click()
        time.sleep(3)
        ssm_tip_div = driver.find_element_by_xpath(
            '/html/body/div[2]/div/div/div[2]/div[2]/div[3]/div[2]')
        ssm_tip = ssm_tip_div.get_attribute('innerText')
        err_msg = '系统未收到短信,请检查手机号是否正确或重新发送短信'
        if ssm_tip == err_msg:
            print(err_msg)
            return None, None, None

        return user_name, pass_word, phone

    except Exception as e:
        print('=========注册失败,执行下一个任务=========')
        print(e)
    finally:
        driver.close()
Esempio n. 44
0
 def test_negative_auth_post_token_invalid_client(self):
     """
     Check exception raised while getting auth for invalid client, and verify the exception contains correct error messages.
     """
     # get config 
     headers = utils.headers
     # compose basic auth
     invalid_auth = ["Basic %s" % base64.encodestring('%s:%s' % (utils.auth_client_id, utils.random_str()))[:-1], "Basic %s" % base64.encodestring('%s:%s' % (utils.random_str(), utils.auth_client_secret))[:-1], "", " "]
     body = {'grant_type': 'http://oauth.net/grant_type/assertion/saml/2.0/bearer', 'assertion': utils.SAMLResponse}
     for ia in invalid_auth:
         headers['Authorization'] = ia
         logging.debug("The requested url is '%s'" % str(self.url))
         logging.info("The invalid authentication head is '%s'" % ia)
         h, c = self.http.request(self.url, 'POST', headers = headers, body = urllib.urlencode(body))
         logging.debug("The response head is '%s'" % str(h))
         logging.debug("The response body is '%s'" % str(c))
         # assert status code is '400'
         self.assertEqual(int(h['status']), 400)
         # verify exception content is correct
         utils.verify_rest_requetfailed_exception(c, utils.get_exception("UnknownClient", "AuthGetConfigExceptions"), self)
Esempio n. 45
0
def create_survey_response():

    survey_json = {'title': random_str(12),
                   'rowCount': random_str(12),
                   'session_id': random_str(12),
                   'ques_id1': random_str(12),
                   'ques_id2': random_str(12),
                   'ques_id3': random_str(12),
                   'ques_id4': random_str(12),
                   'ques_description1': random_str(12),
                   'ques_description2': random_str(12),
                   'ques_description3': random_str(12),
                   'ques_description4': random_str(12),

                   }
    """
                   'type1': random_str(12),
                   'type2': random_str(12),
                   'type3': random_str(12),
                   'type4': random_str(12)
                   """

    return survey_json
Esempio n. 46
0
def conll(data,
          cols=('form', 'postag', 'chunktag', 'guesstag'),
          *args,
          **kwargs):
    """Evaluates chunking f1-score provided with data with the following fields:
    form, postag, chunktag, guesstag

    Currently uses the CoNLL-2000 evaluation script to make the estimate.

    This method will be deprecated with version 0.2

    :param data: np.array
    :param cols: columns to be used for the evaluation
    :type cols: str or tuple or list
    :return: f1-score estimate
    :rtype: AccuracyResults
    """
    warnings.warn(
        'Using the CoNLL-2000 evaluation script is deprecated. `bio` '
        'evaluation should be used instead.')
    try:
        os.makedirs(join(os.getcwd(), 'tmp/'))
    except OSError:
        pass

    td = join(os.getcwd(), 'tmp/')

    rn = rnd.randint(1000, 1000000000000)

    fp_dp = join(td,
                 'chdata.%s.%s.tmp' % (time.asctime().replace(' ', ''), rn))
    fp_res = join(td,
                  'chres.%s.%s.tmp' % (time.asctime().replace(' ', ''), rn))
    fh_out = open(fp_res, 'w')

    export(data, open(fp_dp, 'w'), cols=cols, ts=' ')

    cwd = os.getcwd()
    prl = join(cwd, 'conll_eval.pl' + random_str())
    with open(prl, 'w') as fh:
        fh.write(conll_script)
    c = cmd('perl %s -l < {}' % prl, fp_dp, cwd=cwd, stdout=fh_out)

    r = AccuracyResults()

    try:
        check_call(c)
        r.parse_conll_eval_table(fp_res)
    except CalledProcessError:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print "*** print_tb:"
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
        print "*** print_exception:"
        traceback.print_exception(exc_type,
                                  exc_value,
                                  exc_traceback,
                                  limit=2,
                                  file=sys.stdout)
    finally:
        os.remove(fp_dp)
        os.remove(fp_res)
        os.remove(prl)
        return r
Esempio n. 47
0
def conll(data, cols=('form', 'postag', 'chunktag', 'guesstag'),
          *args, **kwargs):
    """Evaluates chunking f1-score provided with data with the following fields:
    form, postag, chunktag, guesstag

    Currently uses the CoNLL-2000 evaluation script to make the estimate.

    This method will be deprecated with version 0.2

    :param data: np.array
    :param cols: columns to be used for the evaluation
    :type cols: str or tuple or list
    :return: f1-score estimate
    :rtype: AccuracyResults
    """
    warnings.warn('Using the CoNLL-2000 evaluation script is deprecated. `bio` '
                  'evaluation should be used instead.')
    try:
        os.makedirs(join(os.getcwd(), 'tmp/'))
    except OSError:
        pass

    td = join(os.getcwd(), 'tmp/')

    rn = rnd.randint(1000, 1000000000000)

    fp_dp = join(td, 'chdata.%s.%s.tmp' % (time.asctime().replace(' ', ''), rn))
    fp_res = join(td, 'chres.%s.%s.tmp' % (time.asctime().replace(' ', ''), rn))
    fh_out = open(fp_res, 'w')

    export(data,
           open(fp_dp, 'w'),
           cols=cols,
           ts=' ')

    cwd = os.getcwd()
    prl = join(cwd, 'conll_eval.pl' + random_str())
    with open(prl, 'w') as fh:
        fh.write(conll_script)
    c = cmd(
        'perl %s -l < {}' % prl,
        fp_dp,
        cwd=cwd,
        stdout=fh_out
    )

    r = AccuracyResults()

    try:
        check_call(c)
        r.parse_conll_eval_table(fp_res)
    except CalledProcessError:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print "*** print_tb:"
        traceback.print_tb(exc_traceback,
                           limit=1,
                           file=sys.stdout)
        print "*** print_exception:"
        traceback.print_exception(exc_type,
                                  exc_value,
                                  exc_traceback,
                                  limit=2,
                                  file=sys.stdout)
    finally:
        os.remove(fp_dp)
        os.remove(fp_res)
        os.remove(prl)
        return r