def bury(itemcode): try: uid = get_cookie(UID) if uid is None: return 'noLogin' else: item = db.query_one('select t.id,t.itemcode,t.burytimes \ from gkgp_item t where t.itemcode=%s',itemcode) if item is not None: digOrBuryHistory = get_cookie('DigOrBury_'+itemcode) if digOrBuryHistory is not None and len(digOrBuryHistory)>0: if item[2] is not None: return beautifulDisPlay(str(item[2])) else: return '0' else: if item[2] is not None: temp = item[2]+1 db.update('update gkgp_item set burytimes=%s where id=%s',(temp,item[0])) set_cookie('DigOrBury_'+itemcode,itemcode) return beautifulDisPlay(str(temp)) else: return '0' else: return '0' except Exception: traceback.print_exc() return 'bury error'
def test_delete_user_in_backends_by_username(self): """ Delete a user previously registered user by username """ # first, create a user and register it with services try: self.msu.create_user('bootsy', 'collins', '*****@*****.**') except NotImplementedError: skip("user management not supported in this version of managesf") self.logout() self.login('bootsy', 'collins', config.GATEWAY_URL) # make sure user is in gerrit self.assertEqual('*****@*****.**', self.gu.get_account('bootsy').get('email')) # now suppress it del_url = config.GATEWAY_URL +\ '/manage/services_users/?username=bootsy' # try with a a non-admin user, it should not work ... auth_cookie = get_cookie('user5', config.ADMIN_PASSWORD) d = requests.delete(del_url, cookies={'auth_pubtkt': auth_cookie}) self.assertTrue(400 < int(d.status_code) < 500) # try with an admin ... auth_cookie = config.USERS[config.ADMIN_USER]['auth_cookie'] d = requests.delete(del_url, cookies={'auth_pubtkt': auth_cookie}) self.assertTrue(int(d.status_code) < 400, d.status_code) # make sure the user does not exist anymore self.assertEqual(False, self.gu.get_account('bootsy'))
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} for id in args.keys(): try: id = int(id) cur.execute("""DELETE FROM news WHERE id=%s """, id) except ValueError: continue finally: con.commit() cur.close() con.close() return {"Location":"deletenews.html", "notice_msg":"Post delete successfully"}
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} if not args.has_key("file"): return {"Location":"files.html", "error_msg":"File to view was not specified"} req_file = args["file"] user_home = utils.get_user_home(user_id) os.chdir(user_home) handle = open(req_file) contents = handle.read() handle.close() finally: con.commit() cur.close() con.close() req.content_type = 'image/jpeg' return contents;
def handler(req, args): req.headers_out.add( "Set-Cookie", utils.delete_cookie("session")) session_id = utils.get_cookie(req, "session").strip() if session_id == "": return {"Location":"login.html"} con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) cur.execute("SELECT login FROM logins WHERE id = %s", (user_id, )) result = cur.fetchone() login = "" if result: login = result[0] finally: con.commit() cur.close() con.close() logging.info('Logout of %s from %s' % (login, req.connection.remote_ip)) return {"Location":"login.html"}
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} if not args.has_key("upload"): return {"Location":"files.html", "error_msg":"File to upload was not specified"} upload = args["upload"] if type(upload) is str: return {"Location":"files.html", "error_msg":"File to upload was not specified"} user_home = utils.get_user_home(user_id) os.chdir(user_home) fileName = upload.filename.replace('\\','/').split('/')[-1] #check filename if validator.invalid_filename_re.search(fileName): return {"Location":"files.html", "error_msg":"Only number, latin characters and underscores are allowed in filenames"} if not fileName.lower().endswith(".jpg"): return {"Location":"files.html", "error_msg":"Only JPEG files can be stored on this server"} filePath = os.path.join(user_home, fileName) fileHandle = open(filePath, 'wb') size = 0 while True: data = upload.read(8192) if not data: break fileHandle.write(data) size += len(data) fileHandle.close() import stat os.chmod(filePath, stat.S_IREAD | stat.S_IWRITE | stat.S_IRGRP | stat.S_IWGRP) finally: con.commit() cur.close() con.close() return {"Location":"files.html", "notice_msg":"File uploaded successfully"}
def setUpClass(cls): cookie = get_cookie(config.ADMIN_USER, config.ADMIN_PASSWORD) cls.cookie = {"auth_pubtkt": cookie} cls.ju = JenkinsUtils() cls.test_job = "test-sleep-" + rand_suffix() cls.ju.create_job(cls.test_job, TEST_PARAMETERIZED_JOB) cls.ju.run_job(cls.test_job, {'timeout': '1'}) cls.ju.wait_till_job_completes(cls.test_job, 1, 'lastBuild') cls.base_url = config.GATEWAY_URL + "/manage/jobs/"
def delplaylist(): try: itemcode = request.query.get('itemcode') playlist = get_cookie('playlist') l=json.loads(playlist) del l[l.index(itemcode)] set_cookie('playlist',json.dumps(l)) return 'ok' except Exception: traceback.print_exc() return 'error'
def get_my_stars(year): config = read_config() cookie = get_cookie(config) bord_id = get_board_id(config) user_id = get_user_id(config) board_url = LIDERSHIP_BOARD.format(year=year, board=bord_id) response = requests.post(board_url, cookies={'session': cookie}) try: response_json = response.json() return response_json['members'][user_id]['stars'] except Exception: return ''
def __init__(self): with open('resources.yaml', 'r') as rsc: self.resources = yaml.load(rsc) config.USERS[config.ADMIN_USER]['auth_cookie'] = get_cookie( config.ADMIN_USER, config.USERS[config.ADMIN_USER]['password']) self.msu = ManageSfUtils(config.GATEWAY_URL) self.ggu = GerritGitUtils(config.ADMIN_USER, config.ADMIN_PRIV_KEY_PATH, config.USERS[config.ADMIN_USER]['email']) self.ju = JenkinsUtils() self.rm = RedmineUtils( config.REDMINE_URL, auth_cookie=config.USERS[config.ADMIN_USER]['auth_cookie'])
def playlist(): plscodes = get_cookie('playlist') print "plscodes is ",plscodes if not plscodes: return json.dumps(None) l=json.loads(plscodes) if None==plscodes or len(l)==0: return json.dumps(None) pls = getPlayVideoByCodes(plscodes) if None==pls or len(pls)==0: return json.dumps(None) return json.dumps(pls,cls=CJsonEncoder)
def __init__(self): with open("%s/resources.yaml" % pwd, 'r') as rsc: self.resources = yaml.load(rsc) config.USERS[config.ADMIN_USER]['auth_cookie'] = get_cookie( config.ADMIN_USER, config.USERS[config.ADMIN_USER]['password']) self.msu = ManageSfUtils(config.GATEWAY_URL) self.ggu = GerritGitUtils(config.ADMIN_USER, config.ADMIN_PRIV_KEY_PATH, config.USERS[config.ADMIN_USER]['email']) self.ju = JenkinsUtils() self.rm = RedmineUtils( config.GATEWAY_URL + "/redmine/", auth_cookie=config.USERS[config.ADMIN_USER]['auth_cookie'])
def __init__(self): with open("%s/resources.yaml" % pwd, 'r') as rsc: self.resources = yaml.load(rsc) config.USERS[config.ADMIN_USER]['auth_cookie'] = get_cookie( config.ADMIN_USER, config.USERS[config.ADMIN_USER]['password']) self.msu = ManageSfUtils(config.GATEWAY_URL) self.ru = ResourcesUtils() self.ggu = GerritGitUtils(config.ADMIN_USER, config.ADMIN_PRIV_KEY_PATH, config.USERS[config.ADMIN_USER]['email']) self.stb_client = SFStoryboard( config.GATEWAY_URL + "/storyboard_api", config.USERS[config.ADMIN_USER]['auth_cookie'])
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} if not args.has_key("id"): return {"Location":"editnews.html"} id = args["id"].strip() try: id = int(id) except ValueError: return {"Location":"editnews.html"} if not preprocess.input_matches(req, args, expected_args): cur.execute("""SELECT title, text FROM news WHERE id=%s """, id) row = cur.fetchone() if row is None: return {"Location":"editnews.html"} title = row[0] text = row[1] return postprocess.fill_page(template_path, "", "", utils.build_dict(expected_args, [id, title, text])) title = args["title"].strip() text = args["body"] xss_strip = xss.XssCleaner() title = xss_strip.strip(title) text = xss_strip.strip(text) cur.execute("""UPDATE news SET title=%s, text=%s WHERE id=%s""", (title, text, id)) finally: con.commit() cur.close() con.close() return {"Location":"editnews.html", "notice_msg":"Post saved successfully"}
def __init__(self): with open("%s/resources.yaml" % pwd, 'r') as rsc: self.resources = yaml.load(rsc) config.USERS[config.ADMIN_USER]['auth_cookie'] = get_cookie( config.ADMIN_USER, config.USERS[config.ADMIN_USER]['password']) self.gu = GerritUtils( 'http://%s/' % config.GATEWAY_HOST, auth_cookie=config.USERS[config.ADMIN_USER]['auth_cookie']) self.ggu = GerritGitUtils(config.ADMIN_USER, config.ADMIN_PRIV_KEY_PATH, config.USERS[config.ADMIN_USER]['email']) self.ju = JenkinsUtils() self.rm = RedmineUtils( config.GATEWAY_URL + "/redmine/", auth_cookie=config.USERS[config.ADMIN_USER]['auth_cookie'])
def play(itemcode): item = db.query_one('select t1.id,t1.itemcode,t.username,t.id,t1.title,t1.addtime,t1.description,t1.playtimes,t1.digtimes,t1.burytimes \ ,t1.pics from gkgp_user t,gkgp_item t1 ,gkgp_user_item t2 where t1.id = t2.videoid and t2.userid = t.id and \ itemcode=%s',(itemcode)) # put play history into cookie # key : playlist # value : {'itemcode1','itemcode3','itemcode4'} playlist = get_cookie('playlist') if playlist: l=json.loads(playlist) if itemcode not in l: if(len(l)>=10): del l[0] l.append(itemcode) else: l.append(itemcode) set_cookie('playlist',json.dumps(l)) else: l=[] l.append(itemcode) set_cookie('playlist',json.dumps(l)) # end if item is not None: playtime = 0 if item[7] is not None and item[7]>=0: playtime = item[7]+1 else: playtime =1 db.update('update gkgp_item set playtimes=%s where id=%s',(playtime,item[0])) #首发 firstvideo = main.changeVideo(main.findItem(8,5)) # get user other videos othervideos = db.query_list('select t.title,t.pics,t.itemcode from gkgp_item t, \ gkgp_user_item t1 where t.id=t1.videoid and t1.userid=%s order by t.addtime desc limit 0,4 ',(item[3])) item = list(item) item[7] = beautifulDisPlay(str(item[7])) item[8] = beautifulDisPlay(str(item[8])) item[9] = beautifulDisPlay(str(item[9])) return dict(domain=SITE_DOMAIN,picdomain=PIC_DOMAIN,itemcode=itemcode,item=item,firstvideo=firstvideo,othervideos=othervideos)
def ip_66(): """ 66ip 代理:http://www.66ip.cn """ from copy import deepcopy headers = deepcopy(HEADERS) cookie = loop.run_until_complete(get_cookie()) headers.update({ "Cookie": cookie, "Host": "www.66ip.cn", "Referer": "http://www.66ip.cn/nm.html" }) url = 'http://www.66ip.cn/nmtq.php?getnum=100&isp=0&anonymoustype=0&start=&ports=&export=&ipaddress=&area=1&proxytype={}&api=66ip' pattern = "\d+\.\d+.\d+\.\d+:\d+" items = [(0, "http://{}"), (1, "https://{}")] for item in items: proxy_type, host = item html = fetch(url.format(proxy_type), headers=headers) if html: for proxy in re.findall(pattern, html): yield host.format(proxy)
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} if not preprocess.input_matches(req, args, expected_args): return postprocess.fill_page(template_path, "", "", utils.build_dict(expected_args, [])) title = args["title"].strip() text = args["body"] xss_strip = xss.XssCleaner() title = xss_strip.strip(title) text = xss_strip.strip(text) cur.execute("""INSERT INTO news (date, title, author, text) VALUES (now(), %s, %s, %s)""", (title, user_id, text)) finally: con.commit() cur.close() con.close() return {"Location":"news.html", "notice_msg":"Post added successfully"}
def test_check_project_test_workflow(self): """ Validate new project to test via zuul """ # We want to create a project, provide project source # code with tests. We then configure zuul/jjb to handle the # run of the test cases. We then validate Gerrit has been # updated about the test results # We use the sample-project (that already exists) pname = 'test_workflow_%s' % create_random_str() logger.info("Creating project %s" % pname) # Create it self.create_project(pname) logger.info("Populating the project with %s" % self.sample_project_dir) # Add the sample-project to the empty repository clone_dir = self.clone_as_admin(pname) copytree(self.sample_project_dir, clone_dir) self.commit_direct_push_as_admin(clone_dir, "Add the sample project") # Change to config/{zuul,jobs}/projects.yaml # in order to test the new project logger.info("Adding config-repo configuration") ycontent = file(os.path.join( self.config_clone_dir, "zuul/projects.yaml")).read() file(os.path.join( self.config_clone_dir, "zuul/projects.yaml"), 'w').write( ycontent.replace("zuul-demo", pname), ) ycontent2 = load(file(os.path.join( self.config_clone_dir, "jobs/projects.yaml")).read()) sp2 = copy.deepcopy( [p for p in ycontent2 if 'project' in p and p['project']['name'] == 'zuul-demo'][0]) sp2['project']['name'] = pname ycontent2.append(sp2) file(os.path.join( self.config_clone_dir, "jobs/projects.yaml"), 'w').write( dump(ycontent2)) # Send review (config-check) will be triggered logger.info("Submitting the config review") change_sha = self.push_review_as_admin( self.config_clone_dir, "Add config definition in Zuul/JJB config for %s" % pname) change_nr = self.gu.get_change_number(change_sha) logger.info("Waiting for verify +1 on change %d" % change_nr) self.assertEquals(self.gu.wait_for_verify(change_nr), 1) # review the config change as a member from the config-core group logger.info("Approving and waiting for verify +2") self.gu2.submit_change_note(change_nr, "current", "Code-Review", "2") self.gu2.submit_change_note(change_nr, "current", "Workflow", "1") for retry in xrange(60): jenkins_vote = self.gu.get_vote(change_nr, "Verified") if jenkins_vote == 2: break time.sleep(1) self.assertEquals(jenkins_vote, 2) # verify whether zuul merged the patch logger.info("Waiting for change to be merged") for retry in xrange(60): change_status = self.gu.get_info(change_nr)['status'] if change_status == "MERGED": break time.sleep(1) self.assertEqual(change_status, 'MERGED') self.need_restore_config_repo = True logger.info("Waiting for config-update") config_update_log = self.ju.wait_for_config_update(change_sha) self.assertIn("Finished: SUCCESS", config_update_log) # Propose a change on a the repo and expect a Verified +1 logger.info("Submiting a test change to %s" % pname) change_sha = self.gitu_admin.add_commit_and_publish( clone_dir, 'master', "Add useless file", self.un) change_nr = self.gu.get_change_number(change_sha) logger.info("Waiting for verify +1 on change %d" % change_nr) self.assertEquals(self.gu.wait_for_verify(change_nr), 1) # Update the change on a the repo and expect a Verified -1 logger.info("Submiting a test change to %s suppose to fail" % pname) data = "#!/bin/bash\nexit 1\n" file(os.path.join(clone_dir, "run_tests.sh"), 'w').write(data) os.chmod(os.path.join(clone_dir, "run_tests.sh"), 0755) self.gitu_admin.add_commit_and_publish( clone_dir, "master", None, fnames=["run_tests.sh"]) logger.info("Waiting for verify -1 on change %d" % change_nr) self.assertEquals(self.gu.wait_for_verify(change_nr), -1) logger.info("Validate jobs ran via the job api %s" % pname) # This piece of code is there by convenience ... # TODO: Should be moved in the job api tests file. # Test the manageSF jobs API: query per patch & revision change_ids = self.gu.get_my_changes_for_project(pname) self.assertGreater(len(change_ids), 0) change_id = change_ids[0] patch = self.gu.get_change_last_patchset(change_id)['_number'] cookie = get_cookie(config.ADMIN_USER, config.ADMIN_PASSWORD) cookies = {"auth_pubtkt": cookie} base_url = config.GATEWAY_URL + "/manage/jobs/" for j in ["%s-functional-tests" % pname, "%s-unit-tests" % pname]: job = requests.get(base_url + '%s/?change=%s' % (j, patch), cookies=cookies).json() self.assertTrue("jenkins" in job.keys(), job) self.assertTrue(len(job["jenkins"]) > 1, job)
def simple_login(self, user, password): """log as user""" return get_cookie(user, password)
# 登录部分TODO: add more if len(sys.argv)== 4: username = sys.argv[1] password = sys.argv[2] main_level = int(sys.argv[3]) if username== '': username, password, main_level, minor_level, config = ask_basic_info() # UI config = dict(zip(config_item, config)) if not username or not password: sys.exit(1) for _ in xrange(6): try: cookie, uid = get_cookie(username, password) break except: print u"登录失败, 重试." continue else: print u"你比渔民杯具, 谢谢." sys.exit(-1) print u"获得 Uid:", uid # AMF 连接设置 client = RemotingService("http://xiaonei.paopaoyu.cn/gateway/") client.addHTTPHeader('Referer', refer) client.addHTTPHeader('Connection', "close") client.addHTTPHeader('Cookie', cookie)
def assign_cookies(): for k, v in config.USERS.items(): v['auth_cookie'] = get_cookie(k, v['password'])
def simple_login(self, user): """log as user to make the user listable""" get_cookie(user, config.USERS[user]['password'])
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} notice_message = "" if args.has_key("notice_msg"): notice_message = args["notice_msg"] error_message = "" if args.has_key("error_msg"): error_message = args["error_msg"] filter = "" if args.has_key("q"): filter = args["q"] con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} #construct user home user_home = utils.get_user_home(user_id) file_list = os.popen("ls -l %s" % os.path.join(user_home, "*%s*" % filter)).read().split(os.linesep) title = "<h2>List of Your files</h2>" if len(filter) > 0: title = "<h2>Search results for: %s</h2>" % filter contents = '''<table width="100%%" cellspacing="3" cellpadding="3"> <tr> <td align="left" width = "50%%">%s</td> <td align="right" width="50%%"> <form action="files.html" method="GET"> Search files: <input type="text" name="q" value="%s"> <input type="submit" value="Search"> </form> </td> </tr> </table> ''' % (title, filter) + os.linesep contents = contents + "<table width=\"100%\" border=\"1\" cellspacing=\"3\" cellpadding=\"3\">" + os.linesep contents = contents + "<form action=\"deletefiles.html\" method=\"POST\" >" + os.linesep contents = contents + "<tr>" + os.linesep contents = contents + "<td align=\"center\" colspan=\"2\">Name</td>" + os.linesep contents = contents + "<td align=\"center\" width=\"200\" >Size (bytes)</td>" + os.linesep contents = contents + "<td align=\"center\" width=\"200\">Uploaded</td>" + os.linesep contents = contents + "</tr>" + os.linesep n_files = 0 for file_entry in file_list: if file_entry.strip() == "": break file_attrs = file_entry.split(" ") i = 0 while i < len(file_attrs): if len(file_attrs[i].strip()) == 0: del file_attrs[i] else: i = i + 1 try: file_perm = file_attrs[0] file_id = file_attrs[1] file_owner = file_attrs[2] file_grp = file_attrs[3] file_size = file_attrs[4] file_date = file_attrs[5] file_time = file_attrs[6] file_name = os.path.basename(file_attrs[7]) except KeyError: break contents = contents + "<tr>" + os.linesep contents = contents + "<td width=\"30\">" + os.linesep contents = contents + "<input type=\"checkbox\" name=\"%s\">" % (file_name, ) + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "<td>" + os.linesep file_relative = utils.relpath(os.path.dirname(template_path), os.path.join(user_home, file_name)) contents = contents + "<a target=\"_blank\" href=\"showfile.html?file=%s\">%s</a>" % (file_name, file_name) + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "<td align=\"center\">" + os.linesep contents = contents + file_size + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "<td align=\"center\">" + os.linesep contents = contents + file_date + " " + file_time + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "</tr>" + os.linesep n_files = n_files + 1 contents = contents + "<tr>" + os.linesep contents = contents + "<td colspan=\"4\" align=\"center\">" + os.linesep if n_files > 0: contents = contents + "<input type=\"submit\" value=\"Delete files\">" + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "</tr>" + os.linesep contents = contents + "</form>" + os.linesep contents = contents + "</table>" + os.linesep contents = contents + "<p align=\"right\">" + os.linesep contents = contents + "<b><i>Add more files:</i></b><br>" + os.linesep contents = contents + "<form action=\"addfiles.html\" method=\"POST\" ENCTYPE=\"multipart/form-data\">" + os.linesep contents = contents + "<input type=\"file\" name=\"upload\">" + os.linesep contents = contents + "<input type=\"submit\" value=\"Upload file\">" + os.linesep contents = contents + "</form>" + os.linesep contents = contents + "</p>" + os.linesep finally: con.commit() cur.close() con.close() contents = const.html_template.replace("%contents%", contents) contents = contents.replace(const.notice_pattern, const.notice_message % notice_message) contents = contents.replace(const.error_pattern, const.error_message % error_message) return contents
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} notice_message = "" if args.has_key("notice_msg"): notice_message = args["notice_msg"] try: skip = int(args["skip"]) except: skip = 0 NewsToQuery = settings.general_settings["max_news_per_page"] + 1; QueryOffset = (NewsToQuery-1)*skip; con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} cur.execute("""SELECT title, text, date, name, surname, news.id FROM news JOIN (logins, emails) ON (news.author = logins.id AND logins.emails_ref = emails.id ) WHERE news.author=%s ORDER BY news.id DESC LIMIT %s, %s""" % (user_id, QueryOffset, NewsToQuery)) row = cur.fetchone() contents = "<h2>Edit news</h2>" + os.linesep contents = contents + "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\" width=\"100%\">" + os.linesep i = 1 while row and i < NewsToQuery: contents = contents + "<tr>" + os.linesep contents = contents + "<td width=\"10%\" rowspan=\"3\" valign=\"center\">" + os.linesep contents = contents + "<a href=\"doeditnews.html?id=%s\">Edit</a>" % (row[5], ) + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "<td colspan=\"2\" align=\"left\">" + os.linesep contents = contents + "<hr/>" contents = contents + """<b><i>%s</i></b>""" % row[0] + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "</tr>" + os.linesep contents = contents + "<tr>" + os.linesep contents = contents + "<td colspan=\"2\">" + os.linesep contents = contents + row[1] + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "</tr>" + os.linesep contents = contents + "<tr>" + os.linesep contents = contents + "<td colspan=\"2\" align=\"right\">" + os.linesep contents = contents + """by <i>%s %s</i> at %s""" % (row[3], row[4], row[2].strftime('%Y-%m-%d %H:%M:%S')) + os.linesep contents = contents + "<hr/>" contents = contents + "</td>" + os.linesep contents = contents + "</tr>" + os.linesep row = cur.fetchone() i = i + 1 contents = contents + "<tr>" + os.linesep contents = contents + "<td colspan=\"2\" align=\"left\">" + os.linesep if skip > 0: contents = contents + "<a href=\"editnews.html?skip=%s\">Previous %s news...</a> <br/>" % (str(skip-1), str(settings.general_settings["max_news_per_page"])) + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "<td align=\"right\">" + os.linesep if int(cur.rowcount) == NewsToQuery: contents = contents + "<a href=\"editnews.html?skip=%s\">Next %s news...</a> <br/>" % (str(skip+1), str(settings.general_settings["max_news_per_page"])) + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "</tr>" + os.linesep contents = contents + "<tr>" + os.linesep contents = contents + "<td width=\"10%\">" + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "<td width=\"45%\" align=\"right\">" + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "<td width=\"45%\">" + os.linesep contents = contents + "</td>" + os.linesep contents = contents + "</tr>" + os.linesep contents = contents + "</table>" + os.linesep contents = contents + "<br/><hr/>" + os.linesep contents = contents + "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\" width=\"100%\">" + os.linesep contents = contents + "<tr>" + os.linesep contents = contents + "<td align=\"left\">" + os.linesep contents = contents + "<a href=\"addnews.html\"><h3>Post news</h3></a>" contents = contents + "</td>" + os.linesep contents = contents + "<td align=\"center\">" + os.linesep contents = contents + "<a href=\"news.html\"><h3>View news</h3></a>" contents = contents + "</td>" + os.linesep contents = contents + "<td align=\"right\">" + os.linesep contents = contents + "<a href=\"deletenews.html\"><h3>Delete news</h3></a>" contents = contents + "</td>" + os.linesep contents = contents + "</tr>" + os.linesep finally: con.commit() cur.close() con.close() contents = const.html_template.replace("%contents%", contents) contents = contents.replace(const.notice_pattern, const.notice_message % notice_message) contents = contents.replace(const.error_pattern, const.error_message % "") return contents
def simple_login(self, user, password): """log as user to make the user listable""" get_cookie(user, password)
#!/usr/bin/env python import cgitb; cgitb.enable() import sys import os sys.path.append(os.path.dirname(__file__)) import utils from utils import Headers #utils.send_response('test') origin = os.environ.get('HTTP_ORIGIN', '*') headers = Headers() headers['Access-Control-Allow-Origin'] = origin headers['Access-Control-Allow-Credentials'] = 'true' headers['Set-Cookie'] = 'sessionid=1234' headers['Set-Cookie'] = 'sessionid2=5678; HttpOnly' html = """ Please enter your name: <input type="text" id="name" /> <button onclick="document.cookie='name='+document.getElementById('name').value;location.reload()">Save</button> """ if utils.get_cookie('name'): html = "Hello %s" % (utils.get_cookie('name') or 'nobody') utils.send_response(html, headers)
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} notice_message = "" if args.has_key("notice_msg"): notice_message = args["notice_msg"] error_message = "" if args.has_key("error_msg"): error_message = args["error_msg"] con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} if args.has_key("uid"): try: user_id = int(args["uid"]) except: logging.warning("Request to edit profile %s specifiied wrong user id. Client %s" % (req.the_request, req.connection.remote_ip)) cur.execute(""" SELECT logins.id, login, email, name, surname FROM logins JOIN emails ON logins.emails_ref = emails.id WHERE logins.id = %s""", (user_id,)) row = cur.fetchone() if row is None: return {"Location":"viewprofile.html", "error_msg":"Profile to edit specified wrongly"} if not preprocess.input_matches(req, args, expected_args): return postprocess.fill_page(template_path, notice_message, error_message, {"login":row[1], "passwd":"", "passwd_confirm":"", "email":row[2], "name":row[3], "surname":row[4]}) name = cgi.escape(args["name"].strip()) surname = cgi.escape(args["surname"].strip()) passwd = args["passwd"] email = row[2] if passwd != args["passwd_confirm"]: args["login"] = row[1] args["email"] = row[2] return postprocess.fill_page(template_path, "", "Entered passwords do not match", args ) if validator.invalid_passwd_re.search(passwd): args["login"] = row[1] args["email"] = row[2] return postprocess.fill_page(template_path, "", "Whitespaces are not allowed in passwords", args) cur.execute(""" UPDATE emails SET name=%s, surname=%s WHERE email=%s""", (name, surname, email)) if passwd != "": cur.execute(""" UPDATE logins SET passwd=%s WHERE id=%s""", (md5.new(passwd).digest(), user_id)) finally: con.commit() cur.close() con.close() logging.warning("Request to edit profile %s succeded. Client %s" % (req.the_request, req.connection.remote_ip)) return {"Location":"viewprofile.html", "notice_msg":"Profile saved successful!"}
def handler(req, args): session_id = utils.get_cookie(req, "session").strip() if session_id == "": logging.warning('Unathorized attempt to access %s from %s' % (req.the_request, req.connection.remote_ip)) return {"Location":"login.html", "error_msg":"Authorization required!"} notice_message = "" if args.has_key("notice_msg"): notice_message = args["notice_msg"] error_message = "" if args.has_key("error_msg"): error_message = args["error_msg"] con = MySQLdb.connect( host = settings.database_settings["host"], user = settings.database_settings["login"], passwd = settings.database_settings["password"], db = settings.database_settings["database"]) cur = con.cursor() try: expired, user_id = utils.is_expired(cur, session_id) if expired: return {"Location":"login.html", "error_msg":"You session has expired. Please log in"} mode = "" if args.has_key("mode"): mode = args["mode"].strip() if mode.lower() == "admin": cur.execute(""" SELECT logins.id, login, email, name, surname FROM logins JOIN emails ON logins.emails_ref = emails.id """) else: cur.execute(""" SELECT logins.id, login, email, name, surname FROM logins JOIN emails ON logins.emails_ref = emails.id WHERE logins.id = %s""", (user_id)) contents = ''' <table border="0" width="50%" cellspacing="3" cellpadding="3"> ''' row = cur.fetchone() while row: hidden = "" if row[0] != user_id: hidden = '''<input type="hidden" name="uid" value="%s">''' % row[0] contents = contents + ''' <tr> <td width="50%%" align="right"><b>Login:</b></td> <td width="50%%" align="left">%s</td> </tr> <tr> <td align="right"><b>Name:</b></td> <td align="left">%s</td> </tr> <tr> <td align="right"><b>Surname:</b></td> <td align="left">%s</td> </tr> <tr> <td align="right"><b>Email:</b></td> <td align="left">%s</td> </tr> <tr> <td colspan="2" align="center"> <form action="profile.html" method="GET"> %s<input type="submit" value="Edit"> <hr> <br> </form> </td> </tr> ''' % (row[1], row[3], row[4], row[2], hidden) row = cur.fetchone() contents = contents + ''' </table> ''' finally: con.commit() cur.close() con.close() contents = const.html_template.replace("%contents%", contents) contents = contents.replace(const.notice_pattern, const.notice_message % notice_message) contents = contents.replace(const.error_pattern, const.error_message % error_message) return contents