Exemplo n.º 1
0
def editprob_submit(probid):
    if (session.get('username') in configs.admin):
        if dbhandler.col_probs.count({"unique_id": probid}):
            print(request.form)
            prob = {
                "display_name": request.form['title'],
                "by": request.form['by'],
                "diff": request.form['diff'],
                "adminonly": ('adminonly' in request.form),
                "gshs": ('gshs' in request.form),
                "limit_time": int(request.form['tlimit']),
                "limit_memory": int(request.form['mlimit']),
                "desc": request.form['desc'],
                "input": request.form['input'],
                "output": request.form['output'],
                "exin": request.form['input_ex'],
                "exout": request.form['output_ex']
            }
            dbhandler.col_probs.update({"unique_id": probid}, {"$set": prob})
            return newrender("title_editprob",
                             filename='basic_display.html',
                             mode='editprob_success')
        else:
            return newrender("title_editprob",
                             filename='basic_display.html',
                             mode='editprob_err_nosuch')
    else:
        return newrender("title_404", "404 Not Found")
Exemplo n.º 2
0
def login_submit():
	try:
		user = dbhandler.col_members.find_one({"username": request.form['username']})
		if user['activated'] == False:
			session['activation_link'] = user['activation_link']
			session['activation_email'] = user['email']
			return newrender('title_login', '', 'login_err.html', 'login_err_email')
		if 'migrated' in user: #migrated from koistudy1
			if hashlib.md5("request.form['password']").hexdigest() == user['password']:
				session['username'] = request.form['username']
				session['nickname'] = user['nickname']
				session['locale'] = user['locale']
				log = {"date": datetime.datetime.now(), "type": "login_migrated", "result": "succeed", "username": request.form['username'], "ip": request.remote_addr}
				user['password'] = bcrypt.hashpw(request.form['password'].encode("UTF-8"), bcrypt.gensalt())
				del user['migrated']
				dbhandler.col_members.update({'_id': user['_id']}, {"$set": user}, upsert=False)
				dbhandler.col_logs.insert_one(log)
				return redirect('/')
		else:
			if bcrypt.hashpw(request.form['password'].encode("UTF-8"), user['password'].encode('utf-8')) == user['password']:
				session['username'] = request.form['username']
				session['nickname'] = user['nickname']
				session['locale'] = user['locale']
				log = {"date": datetime.datetime.now(), "type": "login", "result": "succeed", "username": request.form['username'], "ip": request.remote_addr}
				dbhandler.col_logs.insert_one(log)
				return redirect('/')
			else:
				log = {"date": datetime.datetime.now(), "type": "login", "result": "wrongpw", "username": request.form['username'], "ip": request.remote_addr}
				dbhandler.col_logs.insert_one(log)
				return newrender('title_login', '', 'login_err.html', 'login_err_pw')
	except (IndexError, TypeError):
		log = {"date": datetime.datetime.now(), "type": "login", "result": "wrongusername", "username": request.form['username'], "ip": request.remote_addr}
		dbhandler.col_logs.insert_one(log)
		return newrender('title_login', '', 'login_err.html', 'login_err_username')
Exemplo n.º 3
0
def submitfile():
    if 'username' in session and session['username'] in configs.admin:
        filename_saved = ''.join(
            random.choice(string.ascii_lowercase + string.digits)
            for _ in range(16))
        while dbhandler.col_uploads.count({"filename_saved": filename_saved}):
            filename_saved = ''.join(
                random.choice(string.ascii_lowercase + string.digits)
                for _ in range(16))
        file = request.files['file']
        if file:
            filename_real = file.filename
            file.save('./uploads/' + filename_saved)
            dbfile = {
                'filename_real': filename_real,
                'filename_saved': filename_saved,
                'size': os.path.getsize('./uploads/' + filename_saved)
            }
            dbhandler.col_uploads.insert_one(dbfile)
            return newrender(
                'title_file', '', 'upload_result.html', '',
                {'url': configs.default_url + '/uploads/' + filename_saved})
        return newrender('title_file', 'Error')
    else:
        return error_handler.error_404(0)
Exemplo n.º 4
0
def editprob(probid):
    if session.get("username") in configs.admin:
        if dbhandler.col_probs.count({"unique_id": probid}):
            prob = dbhandler.col_probs.find_one({"unique_id": probid})
            return newrender("title_editprob", filename="editprob.html", data=prob)
        else:
            return newrender("title_editprob", filename="basic_display.html", mode="editprob_err_nosuch")
    else:
        return newrender("title_404", "404 Not Found")
Exemplo n.º 5
0
def user():
	try:
		user = dbhandler.col_members.find_one({"username": session['username']})
		data = {}
		data['name'] = user['name']
		data['username'] = user['username']
		data['nickname'] = user['nickname']
		return newrender('title_user', filename='user.html', data=data)
	except KeyError:
		return newrender('title_user', filename='basic_display.html', mode='changeuser_err_unknown')
Exemplo n.º 6
0
def addprob_submit():
    if (session.get('username') in configs.admin):
        if dbhandler.col_probs.count({"unique_id": request.form['uniqid']}):
            return newrender('title_addprob',
                             filename='basic_display.html',
                             mode='addprob_err_dup')
        else:
            if re.match('[0-9]+', request.form['tlimit']) and re.match(
                    '[0-9]+', request.form['mlimit']) and re.match(
                        '[^/]+', request.form['uniqid']):
                prob = {
                    "unique_id": request.form['uniqid'],
                    "display_name": request.form['title'],
                    "by": request.form['by'],
                    "diff": request.form['diff'],
                    "adminonly": ('adminonly' in request.form),
                    "gshs": ('gshs' in request.form),
                    "limit_time": int(request.form['tlimit']),
                    "limit_memory": int(request.form['mlimit']),
                    "desc": request.form['desc'],
                    "input": request.form['input'],
                    "output": request.form['output'],
                    "exin": request.form['input_ex'],
                    "exout": request.form['output_ex'],
                    'solved': 0,
                    'submits': 0,
                    'diff': 0
                }
                dbhandler.col_probs.insert_one(prob)

                #elasticsearch indexing
                #creating new index
                conn = httplib.HTTPConnection('localhost', 9200)
                conn.request("PUT", "/koistudy")
                res = conn.getresponse()
                result = res.read()

                #creating document
                params = urllib.urlencode(json.dumps(prob))
                conn = httplib.HTTPConnection('localhost', 9200)
                conn.request("POST",
                             "/koistudy/probs/" + request.form['unique_id'],
                             params)
                res = conn.getresponse()
                result = res.read()
                return newrender("title_addprob",
                                 filename='basic_display.html',
                                 mode='addprob_added')
            else:
                return newrender('title_addprob',
                                 filename='basic_display.html',
                                 mode='addprob_err_timemem')
    else:
        return newrender("title_404", "404 Not Found")
Exemplo n.º 7
0
def editprob(probid):
    if (session.get('username') in configs.admin):
        if dbhandler.col_probs.count({"unique_id": probid}):
            prob = dbhandler.col_probs.find_one({"unique_id": probid})
            return newrender("title_editprob",
                             filename='editprob.html',
                             data=prob)
        else:
            return newrender("title_editprob",
                             filename='basic_display.html',
                             mode='editprob_err_nosuch')
    else:
        return newrender("title_404", "404 Not Found")
Exemplo n.º 8
0
def signup_submit():
	params = urllib.urlencode({'secret': configs.recaptcha_secret, 'response': request.form['g-recaptcha-response']})
	headers = {"Content-type": "application/x-www-form-urlencoded"}
	conn = httplib.HTTPSConnection('www.google.com')
	conn.request("POST", "/recaptcha/api/siteverify", params, headers)
	res = conn.getresponse()
	result = json.loads(res.read())
	if not result['success']:
		return newrender("title_signup", filename='basic_display.html', mode='signup_err_captcha')
	else:
		if re.match(u'^[a-zA-Z가-힣ㄱ-ㅎㅏ-ㅣぁ-ゔァ-ヴー々〆〤0-9_\\-.]{4,20}$', request.form['username']):
			if re.match('^.{6,200}$', request.form['password']):
				if request.form['password'] == request.form['password_re']:
					if re.match(u'^[가-힣A-Za-zぁ-ゔァ-ヴー々〆〤 ]{2,30}$', request.form['name']):
						if re.match('^[a-zA-Z._+\\-0-9]+@[a-z0-9.\\-]+\\.[a-z]{2,5}$', request.form['email']):
							import dbhandler
							try:
								idchecker = dbhandler.col_members.find_one({"username": request.form['username']})
								if idchecker['username']:
									return newrender("title_signup", filename='basic_display.html', mode='signup_err_iddup')
							except TypeError:
								try:
									emailchecker = dbhandler.col_members.find_one({"email": request.form['email']})
									if emailchecker['username']:
										return newrender("title_signup", filename='basic_display.html', mode='signup_err_emaildup')
								except TypeError:
									import bcrypt
									activation_link = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
									if 'locale' in session and session['locale']:
										locale = session['locale']
									else:
										locale = 'ko'
									human = {"username": request.form['username'], "password": bcrypt.hashpw(request.form['password'].encode('UTF-8'), bcrypt.gensalt(configs.bcrypt_round)), "name": request.form['name'], "nickname": request.form['nickname'], "email": request.form['email'], 'activated': False, 'activation_link': activation_link, 'locale': locale}
									msg = MIMEText(render_template('email.txt', link=configs.default_url + '/confirm/' + activation_link).encode('utf-8'), 'html', 'utf-8')
									msg['Subject'] = Header(lang.lang[session.get('locale', 'ko')]['signup_welcome'], 'utf-8')
									msg['From'] = configs.gmail_id + '@gmail.com'
									msg['To'] = request.form['email']
									s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
									s.set_debuglevel(1)
									#try:
									s.login(configs.gmail_id, configs.gmail_pw)
									s.sendmail(msg['From'], msg['To'], msg.as_string())
									s.quit()
									dbhandler.col_members.insert_one(human)
									return newrender('title_signup', filename='basic_display.html', mode='signup_complete')
						else:
							return newrender("title_signup", filename='basic_display.html', mode='signup_err_email')
					else:
						return newrender("title_signup", filename='basic_display.html', mode='signup_err_name')
				else:
					return newrender("title_signup", filename='basic_display.html', mode='signup_err_pwmatch')
			else:
				return newrender("title_signup", filename='basic_display.html', mode='signup_err_password')
		else:
			return newrender("title_signup", filename='basic_display.html', mode='signup_err_username')
Exemplo n.º 9
0
def addcontest_submit():
	if (session.get('username') in configs.admin):
		cur_contest = {"unique_id": request.form['unique_id'],
				"display_name": request.form['display_name'],
				"start" : request.form['start'],
				"end": request.form['end'],
				"duration" : request.form['duration'],
				"type": request.form['type']}
		if(cur_contest['type'] == 'Private'):
			cur_contest['password']=request.form['password']
		dbhandler.col_contests.insert_one(cur_contest)
		return newrender("title_addcontest", lang.lang[session.get('locale', 'ko')]['addcontest_added'])
	else:
		return newrender("title_404", "404 Not Found")
Exemplo n.º 10
0
def resend():
	try:
		msg = MIMEText(render_template('email.txt', link=configs.default_url + '/confirm/' + session['activation_link']).encode('utf-8'), 'html', 'utf-8')
		msg['Subject'] = Header(lang.lang[session['locale']]['signup_welcome'], 'utf-8')
		msg['From'] = configs.gmail_id + '@gmail.com'
		msg['To'] = session['activation_email']
		s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
		s.set_debuglevel(1)
		s.login(configs.gmail_id, configs.gmail_pw)
		s.sendmail(msg['From'], msg['To'], msg.as_string())
		s.quit()
		return newrender('title_login', '', 'login_err.html', 'login_err_resent')
	except KeyError:
		return newrender('title_login', '', 'login_err.html', 'login_err_session')
Exemplo n.º 11
0
def confirm(path):
	import dbhandler
	try:
		user = dbhandler.col_members.find_one({"activation_link": path})
		if user['activated'] == False:
			newuser = dict(user)
			newuser['activated'] = True
			del newuser['activation_link']
			del newuser['_id']
			dbhandler.col_members.update({'_id': user['_id']}, {"$set": newuser}, upsert=False)
			return newrender('title_signup', filename='basic_display.html', mode='signup_verification_complete')
		else:
			return newrender("title_signup", filename='basic_display.html', mode='signup_err_link')
	except TypeError:
		return newrender("title_signup", filename='basic_display.html', mode='signup_err_link')
Exemplo n.º 12
0
def contests(page=1):
	page -= 1
	contest_list = dbhandler.col_contests.find().skip(page * configs.contests_per_page).limit(configs.contests_per_page)
	contest_count = contest_list.count()
	if 'username' in session and session['username']:
		user=session['username']
	else:
		user=''
	key_list = [('unique_id','Code'), ('display_name','Name'), ('start','Starts'), ('end','Ends'),('duration','Duration'),('type','Type')]
	is_admin = (user in configs.admin)
	lastpage = ceil(1.0 * contest_count / configs.contests_per_page)
	page += 1
	if lastpage >= page+3:
		pager1 = page+1
		pager2 = page+2
		pager3 = page+3
	elif lastpage >= page+2:
		pager1 = page+1
		pager2 = page+2
		pager3 = 0
	elif lastpage >= page+1:
		pager1 = page+1
		pager2 = 0
		pager3 = 0
	else:
		pager1 = 0
		pager2 = 0
		pager3 = 0
	return newrender('title_contests', '', 'contests.html', 'contests',
		{'contest_list':contest_list, 'key_list':key_list, 'is_admin': is_admin, 'pagenow': page,
		'pagel0' : page-3, 'pagel1' : page-2, 'pagel2' : page-1,
		'pager1' : pager1, 'pager2' : pager2, 'pager3' : pager3})
Exemplo n.º 13
0
def submitfile():
	if 'username' in session and session['username'] in configs.admin:
		filename_saved = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
		while dbhandler.col_uploads.count({"filename_saved": filename_saved}):
			filename_saved = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
		file = request.files['file']
		if file:
			filename_real=file.filename
			file.save('./uploads/' + filename_saved)
			dbfile = {
				'filename_real': filename_real,
				'filename_saved': filename_saved,
				'size': os.path.getsize('./uploads/' + filename_saved)
			}
			dbhandler.col_uploads.insert_one(dbfile)
			return newrender('title_file', '', 'upload_result.html', '', {'url': configs.default_url + '/uploads/' + filename_saved})
		return newrender('title_file', 'Error')
	else:
		return error_handler.error_404(0)
Exemplo n.º 14
0
def viewprob(probid):
	prob = dbhandler.col_probs.find_one({"unique_id": probid})
	if 'username' in session:
		user = dbhandler.col_members.find_one({"username": session['username']})
		if 'defaulttheme' in user:
			theme = user['defaulttheme']
		else:
			theme = 'chrome'
	else:
		theme = 'chrome'
	return newrender('title_viewprob', '', 'viewprob.html', '', {'prob':prob, 'session': session, 'theme': theme})
Exemplo n.º 15
0
def resend():
    try:
        msg = MIMEText(
            render_template('email.txt',
                            link=configs.default_url + '/confirm/' +
                            session['activation_link']).encode('utf-8'),
            'html', 'utf-8')
        msg['Subject'] = Header(
            lang.lang[session.get('locale', 'ko')]['signup_welcome'], 'utf-8')
        msg['From'] = configs.gmail_id + '@gmail.com'
        msg['To'] = session['activation_email']
        s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
        s.set_debuglevel(1)
        s.login(configs.gmail_id, configs.gmail_pw)
        s.sendmail(msg['From'], msg['To'], msg.as_string())
        s.quit()
        return newrender('title_login', '', 'login_err.html',
                         'login_err_resent')
    except KeyError:
        return newrender('title_login', '', 'login_err.html',
                         'login_err_session')
Exemplo n.º 16
0
def changeuser_submit():
	try:
		user = dbhandler.col_members.find_one({"username": session['username']})
		data = {}
		if bcrypt.hashpw(request.form['password_now'].encode("UTF-8"), user['password']) == user['password']:
			if request.form['password_new'] != '':
				if re.match('^.{6,200}$', request.form['password_new']):
					if request.form['password_new'] == request.form['password_new_re']:
						user['password'] = bcrypt.hashpw(request.form['password_new'].encode("UTF-8"), bcrypt.gensalt(configs.bcrypt_round))
					else:
						return newrender('title_user', filename='basic_display.html', mode='changeuser_err_pw_match')
				else:
					return newrender('title_user', filename='basic_display.html', mode='changeuser_err_pw_format')
			if re.match(u'^[가-힣A-Za-zぁ-ゔァ-ヴー々〆〤 ]{2,30}$', request.form['name']):
				user['name'] = request.form['name']
			else:
				return newrender('title_user', filename='basic_display.html', mode='changeuser_err_name')
			#if re.match('^[a-zA-Z._+\\-0-9]+@[a-z0-9.\\-]+\\.[a-z]{2,5}$', request.form['email']):
				#user['email'] = request.form['email']
			#else:
			#	return newrender('title_user', '', 'changeuser_err.html', 'changeuser_err_email')
			dbhandler.col_members.update({'_id': user['_id']}, {"$set": user}, upsert=False)
			return newrender('title_user', filename='basic_display.html', mode='changeuser_complete')
		else:
			return newrender('title_user', filename='basic_display.html', mode='changeuser_err_pw')
	except KeyError:
		return newrender('title_user', filename='basic_display.html', mode='changeuser_err_unknown')
Exemplo n.º 17
0
def addprob_submit():
	if (session.get('username') in configs.admin):
		if dbhandler.col_probs.count({"unique_id": request.form['uniqid']}):
			return newrender('title_addprob', filename='basic_display.html', mode='addprob_err_dup')
		else:
			if re.match('[0-9]+',request.form['tlimit']) and re.match('[0-9]+',request.form['mlimit']) and re.match('[^/]+', request.form['uniqid']):
				prob = {"unique_id": request.form['uniqid'], 
					"display_name": request.form['title'], 
					"by": request.form['by'], 
					"diff": request.form['diff'], 
					"adminonly" : ('adminonly' in request.form),
					"gshs" : ('gshs' in request.form), 
					"limit_time": int(request.form['tlimit']), 
					"limit_memory": int(request.form['mlimit']), 
					"desc": request.form['desc'], 
					"input": request.form['input'], 
					"output": request.form['output'], 
					"exin": request.form['input_ex'], 
					"exout": request.form['output_ex'], 
					'solved': 0, 'submits': 0, 'diff': 0}
				dbhandler.col_probs.insert_one(prob)

				#elasticsearch indexing
				#creating new index
				conn = httplib.HTTPConnection('localhost', 9200)
				conn.request("PUT", "/koistudy")
				res = conn.getresponse()
				result = res.read()

				#creating document
				params = urllib.urlencode(json.dumps(prob))
				conn = httplib.HTTPConnection('localhost', 9200)
				conn.request("POST", "/koistudy/probs/" + request.form['unique_id'], params)
				res = conn.getresponse()
				result = res.read()
				return newrender("title_addprob", filename='basic_display.html', mode='addprob_added')
			else:
				return newrender('title_addprob', filename='basic_display.html', mode='addprob_err_timemem')
	else:
		return newrender("title_404", "404 Not Found")
Exemplo n.º 18
0
def confirm(path):
    import dbhandler
    try:
        user = dbhandler.col_members.find_one({"activation_link": path})
        if user['activated'] == False:
            newuser = dict(user)
            newuser['activated'] = True
            del newuser['activation_link']
            del newuser['_id']
            dbhandler.col_members.update({'_id': user['_id']},
                                         {"$set": newuser},
                                         upsert=False)
            return newrender('title_signup',
                             filename='basic_display.html',
                             mode='signup_verification_complete')
        else:
            return newrender("title_signup",
                             filename='basic_display.html',
                             mode='signup_err_link')
    except TypeError:
        return newrender("title_signup",
                         filename='basic_display.html',
                         mode='signup_err_link')
Exemplo n.º 19
0
def editprob_submit(probid):
    if session.get("username") in configs.admin:
        if dbhandler.col_probs.count({"unique_id": probid}):
            print(request.form)
            prob = {
                "display_name": request.form["title"],
                "by": request.form["by"],
                "diff": request.form["diff"],
                "adminonly": ("adminonly" in request.form),
                "gshs": ("gshs" in request.form),
                "limit_time": int(request.form["tlimit"]),
                "limit_memory": int(request.form["mlimit"]),
                "desc": request.form["desc"],
                "input": request.form["input"],
                "output": request.form["output"],
                "exin": request.form["input_ex"],
                "exout": request.form["output_ex"],
            }
            dbhandler.col_probs.update({"unique_id": probid}, {"$set": prob})
            return newrender("title_editprob", filename="basic_display.html", mode="editprob_success")
        else:
            return newrender("title_editprob", filename="basic_display.html", mode="editprob_err_nosuch")
    else:
        return newrender("title_404", "404 Not Found")
Exemplo n.º 20
0
def viewprob(probid):
    prob = dbhandler.col_probs.find_one({"unique_id": probid})
    if 'username' in session:
        user = dbhandler.col_members.find_one(
            {"username": session['username']})
        if 'defaulttheme' in user:
            theme = user['defaulttheme']
        else:
            theme = 'chrome'
    else:
        theme = 'chrome'
    return newrender('title_viewprob', '', 'viewprob.html', '', {
        'prob': prob,
        'session': session,
        'theme': theme
    })
Exemplo n.º 21
0
def probs(page=1):
	page -= 1
	a = lang.lang[session['locale']]
	key_list = [('unique_id', a['probs_code']), ('verdict', a['probs_verdict']), ('display_name', a['probs_name']), ('solved', a['probs_solved']), ('submits', a['probs_submits']), ('diff',a['probs_diff'])]
	is_admin = False
	if 'username' in session and session['username'] in configs.admin:
		prob_list = dbhandler.col_probs.find().skip(page * configs.probs_per_page).limit(configs.probs_per_page)
		probcnt = dbhandler.col_probs.count()
		is_admin = True
	elif 'username' in session and session['username']:
		user = dbhandler.col_members.find_one({"username": session['username']})
		if 'gshs' in user:
			prob_list = dbhandler.col_probs.find({"adminonly": False}).skip(page * configs.probs_per_page).limit(configs.probs_per_page)
			probcnt = dbhandler.col_probs.count({"adminonly": False})
		else:
			prob_list = dbhandler.col_probs.find({"adminonly": False, "gshs": False}).skip(page * configs.probs_per_page).limit(configs.probs_per_page)
			probcnt = dbhandler.col_probs.count({"adminonly": False, "gshs": False})
	else:
		prob_list = dbhandler.col_probs.find({"adminonly": False, "gshs": False}).skip(page * configs.probs_per_page).limit(configs.probs_per_page)
		probcnt = dbhandler.col_probs.count({"adminonly": False, "gshs": False})
	prob_list = prob_list.sort('unique_id',1)
	user = dbhandler.col_members.find({"username": session.get('username')})
	if session.get('username') in configs.admin:
		is_admin = True
	else:
		is_admin = False
	lastpage = math.ceil(1.0 * probcnt / configs.probs_per_page)
	page += 1
	pager1 = 0
	pager2 = 0
	pager3 = 0
	if lastpage >= page+1:
		pager1 = page+1
	if lastpage >= page+2:
		pager2 = page+2
	if lastpage >= page+3:
		pager3 = page+3
	return newrender('title_probs', '', 'probs.html', 'probs', 
		{'prob_list':prob_list, 
		 'key_list':key_list,
		 'is_admin': is_admin,
		 'pagenow': page,
		 'pagel0': page-3, 'pagel1': page-2, 'pagel2': page-1,
		 'pager1': pager1, 'pager2': pager2, 'pager3': pager3})
Exemplo n.º 22
0
def probs(page=1):
	page -= 1
	a = lang.lang[session.get('locale', 'ko')]
	key_list = [('unique_id', a['probs_code']), ('verdict', a['probs_verdict']), ('display_name', a['probs_name']), ('solved', a['probs_solved']), ('submits', a['probs_submits']), ('diff',a['probs_diff'])]
	is_admin = False
	if 'username' in session and session['username'] in configs.admin:
		prob_list = dbhandler.col_probs.find().skip(page * configs.probs_per_page).limit(configs.probs_per_page)
		probcnt = dbhandler.col_probs.count()
		is_admin = True
	elif 'username' in session and session['username']:
		user = dbhandler.col_members.find_one({"username": session['username']})
		if 'gshs' in user:
			prob_list = dbhandler.col_probs.find({"adminonly": False}).skip(page * configs.probs_per_page).limit(configs.probs_per_page)
			probcnt = dbhandler.col_probs.count({"adminonly": False})
		else:
			prob_list = dbhandler.col_probs.find({"adminonly": False, "gshs": False}).skip(page * configs.probs_per_page).limit(configs.probs_per_page)
			probcnt = dbhandler.col_probs.count({"adminonly": False, "gshs": False})
	else:
		prob_list = dbhandler.col_probs.find({"adminonly": False, "gshs": False}).skip(page * configs.probs_per_page).limit(configs.probs_per_page)
		probcnt = dbhandler.col_probs.count({"adminonly": False, "gshs": False})
	prob_list = prob_list.sort('unique_id',1)
	user = dbhandler.col_members.find({"username": session.get('username')})
	if session.get('username') in configs.admin:
		is_admin = True
	else:
		is_admin = False
	lastpage = math.ceil(1.0 * probcnt / configs.probs_per_page)
	page += 1
	pager1 = 0
	pager2 = 0
	pager3 = 0
	if lastpage >= page+1:
		pager1 = page+1
	if lastpage >= page+2:
		pager2 = page+2
	if lastpage >= page+3:
		pager3 = page+3
	return newrender('title_probs', '', 'probs.html', 'probs', 
		{'prob_list':prob_list, 
		 'key_list':key_list,
		 'is_admin': is_admin,
		 'pagenow': page,
		 'pagel0': page-3, 'pagel1': page-2, 'pagel2': page-1,
		 'pager1': pager1, 'pager2': pager2, 'pager3': pager3})
Exemplo n.º 23
0
def contests(page=1):
    page -= 1
    contest_list = dbhandler.col_contests.find().skip(
        page * configs.contests_per_page).limit(configs.contests_per_page)
    contest_count = contest_list.count()
    if 'username' in session and session['username']:
        user = session['username']
    else:
        user = ''
    key_list = [('unique_id', 'Code'), ('display_name', 'Name'),
                ('start', 'Starts'), ('end', 'Ends'), ('duration', 'Duration'),
                ('type', 'Type')]
    is_admin = (user in configs.admin)
    lastpage = ceil(1.0 * contest_count / configs.contests_per_page)
    page += 1
    if lastpage >= page + 3:
        pager1 = page + 1
        pager2 = page + 2
        pager3 = page + 3
    elif lastpage >= page + 2:
        pager1 = page + 1
        pager2 = page + 2
        pager3 = 0
    elif lastpage >= page + 1:
        pager1 = page + 1
        pager2 = 0
        pager3 = 0
    else:
        pager1 = 0
        pager2 = 0
        pager3 = 0
    return newrender(
        'title_contests', '', 'contests.html', 'contests', {
            'contest_list': contest_list,
            'key_list': key_list,
            'is_admin': is_admin,
            'pagenow': page,
            'pagel0': page - 3,
            'pagel1': page - 2,
            'pagel2': page - 1,
            'pager1': pager1,
            'pager2': pager2,
            'pager3': pager3
        })
Exemplo n.º 24
0
def signup_submit():
    params = urllib.urlencode({
        'secret': configs.recaptcha_secret,
        'response': request.form['g-recaptcha-response']
    })
    headers = {"Content-type": "application/x-www-form-urlencoded"}
    conn = httplib.HTTPSConnection('www.google.com')
    conn.request("POST", "/recaptcha/api/siteverify", params, headers)
    res = conn.getresponse()
    result = json.loads(res.read())
    if not result['success']:
        return newrender("title_signup",
                         filename='basic_display.html',
                         mode='signup_err_captcha')
    else:
        if re.match(u'^[a-zA-Z가-힣ㄱ-ㅎㅏ-ㅣぁ-ゔァ-ヴー々〆〤0-9_\\-.]{4,20}$',
                    request.form['username']):
            if re.match('^.{6,200}$', request.form['password']):
                if request.form['password'] == request.form['password_re']:
                    if re.match(u'^[가-힣A-Za-zぁ-ゔァ-ヴー々〆〤 ]{2,30}$',
                                request.form['name']):
                        if re.match(
                                '^[a-zA-Z._+\\-0-9]+@[a-z0-9.\\-]+\\.[a-z]{2,5}$',
                                request.form['email']):
                            import dbhandler
                            try:
                                idchecker = dbhandler.col_members.find_one(
                                    {"username": request.form['username']})
                                if idchecker['username']:
                                    return newrender(
                                        "title_signup",
                                        filename='basic_display.html',
                                        mode='signup_err_iddup')
                            except TypeError:
                                try:
                                    emailchecker = dbhandler.col_members.find_one(
                                        {"email": request.form['email']})
                                    if emailchecker['username']:
                                        return newrender(
                                            "title_signup",
                                            filename='basic_display.html',
                                            mode='signup_err_emaildup')
                                except TypeError:
                                    import bcrypt
                                    activation_link = ''.join(
                                        random.choice(string.ascii_lowercase +
                                                      string.digits)
                                        for _ in range(16))
                                    if 'locale' in session and session[
                                            'locale']:
                                        locale = session['locale']
                                    else:
                                        locale = 'ko'
                                    human = {
                                        "username":
                                        request.form['username'],
                                        "password":
                                        bcrypt.hashpw(
                                            request.form['password'].encode(
                                                'UTF-8'),
                                            bcrypt.gensalt(
                                                configs.bcrypt_round)),
                                        "name":
                                        request.form['name'],
                                        "nickname":
                                        request.form['nickname'],
                                        "email":
                                        request.form['email'],
                                        'activated':
                                        False,
                                        'activation_link':
                                        activation_link,
                                        'locale':
                                        locale
                                    }
                                    msg = MIMEText(
                                        render_template(
                                            'email.txt',
                                            link=configs.default_url +
                                            '/confirm/' +
                                            activation_link).encode('utf-8'),
                                        'html', 'utf-8')
                                    msg['Subject'] = Header(
                                        lang.lang[session.get(
                                            'locale', 'ko')]['signup_welcome'],
                                        'utf-8')
                                    msg['From'] = configs.gmail_id + '@gmail.com'
                                    msg['To'] = request.form['email']
                                    s = SMTP_SSL('smtp.gmail.com',
                                                 465,
                                                 timeout=10)
                                    s.set_debuglevel(1)
                                    #try:
                                    s.login(configs.gmail_id, configs.gmail_pw)
                                    s.sendmail(msg['From'], msg['To'],
                                               msg.as_string())
                                    s.quit()
                                    dbhandler.col_members.insert_one(human)
                                    return newrender(
                                        'title_signup',
                                        filename='basic_display.html',
                                        mode='signup_complete')
                        else:
                            return newrender("title_signup",
                                             filename='basic_display.html',
                                             mode='signup_err_email')
                    else:
                        return newrender("title_signup",
                                         filename='basic_display.html',
                                         mode='signup_err_name')
                else:
                    return newrender("title_signup",
                                     filename='basic_display.html',
                                     mode='signup_err_pwmatch')
            else:
                return newrender("title_signup",
                                 filename='basic_display.html',
                                 mode='signup_err_password')
        else:
            return newrender("title_signup",
                             filename='basic_display.html',
                             mode='signup_err_username')
Exemplo n.º 25
0
def error_404(error):
	return newrender("title_404", "404 Not Found")
Exemplo n.º 26
0
def addcontest():
	if (session.get('username') in configs.admin):
		return newrender("title_addcontest", '', 'addcontest.html')
	else:
		return newrender("title_404", "404 Not Found")
Exemplo n.º 27
0
def login():
    return newrender("title_login", "", "login.html")
Exemplo n.º 28
0
def upload():
	if 'username' in session and session['username'] in configs.admin:
		return newrender('title_file', '', 'upload.html')
	else:
		return error_handler.error_404(0)
Exemplo n.º 29
0
def login_submit():
    try:
        user = dbhandler.col_members.find_one(
            {"username": request.form['username']})
        if user['activated'] == False:
            session['activation_link'] = user['activation_link']
            session['activation_email'] = user['email']
            return newrender('title_login', '', 'login_err.html',
                             'login_err_email')
        if 'migrated' in user:  #migrated from koistudy1
            if hashlib.md5("request.form['password']").hexdigest(
            ) == user['password']:
                session['username'] = request.form['username']
                session['nickname'] = user['nickname']
                session['locale'] = user['locale']
                log = {
                    "date": datetime.datetime.now(),
                    "type": "login_migrated",
                    "result": "succeed",
                    "username": request.form['username'],
                    "ip": request.remote_addr
                }
                user['password'] = bcrypt.hashpw(
                    request.form['password'].encode("UTF-8"), bcrypt.gensalt())
                del user['migrated']
                dbhandler.col_members.update({'_id': user['_id']},
                                             {"$set": user},
                                             upsert=False)
                dbhandler.col_logs.insert_one(log)
                return redirect('/')
        else:
            if bcrypt.hashpw(
                    request.form['password'].encode("UTF-8"),
                    user['password'].encode('utf-8')) == user['password']:
                session['username'] = request.form['username']
                session['nickname'] = user['nickname']
                session['locale'] = user['locale']
                log = {
                    "date": datetime.datetime.now(),
                    "type": "login",
                    "result": "succeed",
                    "username": request.form['username'],
                    "ip": request.remote_addr
                }
                dbhandler.col_logs.insert_one(log)
                return redirect('/')
            else:
                log = {
                    "date": datetime.datetime.now(),
                    "type": "login",
                    "result": "wrongpw",
                    "username": request.form['username'],
                    "ip": request.remote_addr
                }
                dbhandler.col_logs.insert_one(log)
                return newrender('title_login', '', 'login_err.html',
                                 'login_err_pw')
    except (IndexError, TypeError):
        log = {
            "date": datetime.datetime.now(),
            "type": "login",
            "result": "wrongusername",
            "username": request.form['username'],
            "ip": request.remote_addr
        }
        dbhandler.col_logs.insert_one(log)
        return newrender('title_login', '', 'login_err.html',
                         'login_err_username')
Exemplo n.º 30
0
def signup():
	return newrender('title_signup', filename='signup.html')
Exemplo n.º 31
0
def findacc():
	return newrender('findacc', filename='findacc.html')
Exemplo n.º 32
0
def index():
	content = ''
	return newrender("title_main", "Sample Content")
Exemplo n.º 33
0
def error_500(error):
	return newrender("title_500", error)
Exemplo n.º 34
0
def index():
    content = ''
    return newrender("title_main", "Sample Content")
Exemplo n.º 35
0
def upload():
    if 'username' in session and session['username'] in configs.admin:
        return newrender('title_file', '', 'upload.html')
    else:
        return error_handler.error_404(0)
Exemplo n.º 36
0
def signup():
    return newrender('title_signup', filename='signup.html')
Exemplo n.º 37
0
def addprob():
    if (session.get('username') in configs.admin):
        return newrender("title_addprob", '', 'addprob.html')
    else:
        return newrender("title_404", "404 Not Found")
Exemplo n.º 38
0
def login():
	return newrender('title_login', '', 'login.html')
Exemplo n.º 39
0
def login():
    return newrender('title_login', '', 'login.html')
Exemplo n.º 40
0
def stats():
	return newrender('title_stats', '', 'stats.html')
Exemplo n.º 41
0
def login_submit():
    try:
        user = dbhandler.col_members.find_one({"username": request.form["username"]})
        if user["activated"] == False:
            session["activation_link"] = user["activation_link"]
            session["activation_email"] = user["email"]
            return newrender("title_login", "", "login_err.html", "login_err_email")
        if "migrated" in user:  # migrated from koistudy1
            if hashlib.md5("request.form['password']").hexdigest() == user["password"]:
                session["username"] = request.form["username"]
                session["nickname"] = user["nickname"]
                session["locale"] = user["locale"]
                log = {
                    "date": datetime.datetime.now(),
                    "type": "login_migrated",
                    "result": "succeed",
                    "username": request.form["username"],
                    "ip": request.remote_addr,
                }
                user["password"] = bcrypt.hashpw(request.form["password"].encode("UTF-8"), bcrypt.gensalt())
                del user["migrated"]
                dbhandler.col_members.update({"_id": user["_id"]}, {"$set": user}, upsert=False)
                dbhandler.col_logs.insert_one(log)
                return redirect("/")
        else:
            if (
                bcrypt.hashpw(request.form["password"].encode("UTF-8"), user["password"].encode("utf-8"))
                == user["password"]
            ):
                session["username"] = request.form["username"]
                session["nickname"] = user["nickname"]
                session["locale"] = user["locale"]
                log = {
                    "date": datetime.datetime.now(),
                    "type": "login",
                    "result": "succeed",
                    "username": request.form["username"],
                    "ip": request.remote_addr,
                }
                dbhandler.col_logs.insert_one(log)
                return redirect("/")
            else:
                log = {
                    "date": datetime.datetime.now(),
                    "type": "login",
                    "result": "wrongpw",
                    "username": request.form["username"],
                    "ip": request.remote_addr,
                }
                dbhandler.col_logs.insert_one(log)
                return newrender("title_login", "", "login_err.html", "login_err_pw")
    except (IndexError, TypeError):
        log = {
            "date": datetime.datetime.now(),
            "type": "login",
            "result": "wrongusername",
            "username": request.form["username"],
            "ip": request.remote_addr,
        }
        dbhandler.col_logs.insert_one(log)
        return newrender("title_login", "", "login_err.html", "login_err_username")