def public_profile(user): cur = query_db('select * from users where username = ?', [user], one=True) challenges = None if cur is not None: user_id = cur[0] username = cur[1] email = cur[2] imagename = cur[6] print imagename if cur[5] is not None: solved_challenges = cur[5] query_string = "id = " + solved_challenges.replace("|", " or id = ") cur = query_db('select id, name, submitter_id from challenges where %s' % query_string) challenges = [dict(id=row[0],name=row[1],submitter_id=row[2],completed=True) for row in cur] # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" else: return render_template('user_dne.html',username=user) return render_template('public_profile.html',userid=user_id,username=user,email=email,challenges=challenges,imagename=imagename)
def show_specific_submission(id): if 'logged_in' not in session or session['logged_in'] == False: abort(401) # look up DB for this partciular submission cur = query_db('''select s.id, user_id, challenge_id, timestamp, status, status_info, c.name, s.code ''' ''' from submissions s join challenges c on s.challenge_id = c.id where s.id = ?''', [id], one=True) if cur is not None: _id = cur[0] else: abort(404) # Convert user_id to username cur2 = query_db('select username from users where id = ?', [cur[1]], one=True) if cur is not None: user_id = cur2[0] else: abort(401) # If the user doesn't own this submission, 401 unauth. if 'user' not in session or session['user'] != user_id: abort(401) problem_name = cur[6] timestamp = cur[3] status = cur[4] status_info = cur[5] code = cur[7] # Send it to the page return render_template('submission.html', id=_id, user_id=user_id, problem_name=problem_name, timestamp=timestamp, status=status, status_info=status_info, code=code)
def updateprofile(): email = request.form['email'] username = request.form['username'] pass1 = request.form['pass1'] pass2 = request.form['pass2'] # check passwords are the same if pass1 != pass2: flash('Passwords do not match', 'error') return redirect(url_for('profile')) # check username does not already exist username_check = query_db('''select id from users where username = ? and id != ?''',[username, session['userid']], one=True) if username_check is not None: flash('Username is already taken','error') return redirect(url_for('profile')) # check email does not already exist email_check = query_db('''select id from users where email = ? and id != ?''',[email, session['userid']], one=True) if email_check is not None: flash('Email is already taken','error') return redirect(url_for('profile')) if pass1 != "" and pass2 != "": user_pass = query_db('''select salt from users where id = ?''',[session['userid']], one=True) hashed_password = hashlib.sha512(pass1 + user_pass[0]).hexdigest() update_db('''update users set username = ?, email = ?, password = ? where id = ?''', [username, email, hashed_password, session['userid']]) else: update_db('''update users set username = ?, email = ? where id = ?''', [username, email, session['userid']]) session['user'] = username return redirect(url_for('profile'))
def do_browse(com=False): if com is False: # com_flag of 2 signfies admin chosen challenges that can be attempted by anyone cur = query_db('select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2') else: cur = query_db('select id, name, submitter_id from challenges where com_flag = 1') challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur] # Retrieve category names cur = query_db('select name from categories'); if cur: categories = [dict(name=row[0]) for row in cur] # Add completion status if 'user' in session: lookup = query_db("select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: for completed_challenge in lookup[0].split('|'): for displayed_challenge in challenges: if str(displayed_challenge["id"]) == completed_challenge: displayed_challenge["completed"] = 1 # The HTML page just checks for the existance of this key-value pair # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" return (challenges, categories)
def show_submissions(): if 'logged_in' not in session or session['logged_in'] == False: abort(401) # Convert session user to a user ID cur = query_db('select id from users where username = ?', [session['user']], one=True) if cur is not None: user_id = cur[0] else: abort(401) # Get stuff from the database cur = query_db( '''select s.id, user_id, challenge_id, timestamp, status, status_info, c.name, language ''' '''from submissions s join challenges c on s.challenge_id = c.id where user_id = ?''', [user_id]) # Produce an array of hashes that looks something like: # [{id->'1', user_id->'5', problem_name->'2', timestamp->'<the time>', status->'Accepted', status_info->'Some Error', language->'C'}, {other hash}] submissions = [ dict(id=row[0], user_id=row[1], challenge_name=row[6], timestamp=row[3], status=row[4], status_info=row[5], language=row[7]) for row in cur ] # Send it to submissions return render_template('submissions.html', submissions=submissions)
def public_profile(user): cur = query_db("select * from users where username = ?", [user], one=True) challenges = None if cur is not None: user_id = cur[0] username = cur[1] email = cur[2] imagename = cur[6] print imagename if cur[5] is not None: solved_challenges = cur[5] query_string = "id = " + solved_challenges.replace("|", " or id = ") cur = query_db("select id, name, submitter_id from challenges where %s" % query_string) challenges = [dict(id=row[0], name=row[1], submitter_id=row[2], completed=True) for row in cur] # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" else: return render_template("user_dne.html", username=user) return render_template( "public_profile.html", userid=user_id, username=user, email=email, challenges=challenges, imagename=imagename )
def show_playlist_challenges(playlist_id): # Retrieve the requested playlist cur = query_db('select * from playlists where id = ?', [playlist_id], one=True) if cur is not None: playlist_name = cur[1] challenge_ids = cur[3] cur = query_db('select id, name, submitter_id from challenges') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name', submitter_id->5}, {other hash}] all_challenges = [ dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur ] challenges = [] if challenge_ids: # Obtain a list of in order challenge ids for a playlist id_list = [int(s) for s in challenge_ids.split('|')] for id in id_list: for challenge in all_challenges: if challenge['id'] == id: challenges.append( dict(id=challenge['id'], name=challenge['name'], submitter_id=challenge['submitter_id'])) break # Add completion status if 'user' in session: lookup = query_db( "select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: for completed_challenge in lookup[0].split('|'): for displayed_challenge in challenges: if str(displayed_challenge["id"] ) == completed_challenge: displayed_challenge[ "completed"] = 1 # The HTML page just checks for the existance of this key-value pair # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" return render_template('browse.html', challenges=challenges, playlist_name=playlist_name) else: abort(404)
def create_new_playlist(): if "user" in session: username = session["user"] cur = query_db("select id from users where username = ?", [username], one=True) if cur is not None: user_id = cur[0] # Set fields to check to false and grab playlist name flags = {"no_name": False, "conflict_name": False, "new_name": None} playlist_name = request.form.get("playlist_name") temp = re.sub("[\s+]", "", playlist_name) play_id = None cur = query_db("select id, name from challenges") challenges = [dict(id=row[0], name=row[1]) for row in cur] # If invalid playlist name, flash an alert if not request.form.get("playlist_name") or not temp: flags["no_name"] = True # Insert new playlist into database else: flags["new_name"] = playlist_name cur2 = query_db( "select * from playlists where owner_id = ? and name = ?", [user_id, playlist_name], one=True ) if cur2 is None: play_id = random.randint(0, 1000000) id_check = query_db("select * from playlists where id = ?", [play_id], one=True) while id_check is not None: play_id = random.randint(0, 1000000) id_check = query_db("select * from playlists where id = ?", [play_id], one=True) challenge_ids = "" for challenge in challenges: id = request.form.get(challenge["name"]) if id: if not challenge_ids: challenge_ids = str(id) else: challenge_ids += "|" + str(id) g.db.execute( "insert into playlists (id, name, owner_id, challenges) values (?, ?, ?, ?)", [play_id, playlist_name, user_id, challenge_ids], ) g.db.commit() else: flags["conflict_name"] = True return render_template("new_playlist.html", challenges=challenges, flags=flags, play_id=play_id) else: abort(401) else: abort(401)
def show_playlist_form(): if "user" in session: cur = query_db("select id, name from challenges") challenges = [dict(id=row[0], name=row[1]) for row in cur] flags = {} play_id = None return render_template("new_playlist.html", challenges=challenges, flags=flags, play_id=play_id) else: abort(401)
def show_playlist_challenges(playlist_id): # Retrieve the requested playlist cur = query_db("select * from playlists where id = ?", [playlist_id], one=True) if cur is not None: playlist_name = cur[1] challenge_ids = cur[3] cur = query_db("select id, name, submitter_id from challenges") # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name', submitter_id->5}, {other hash}] all_challenges = [dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur] challenges = [] if challenge_ids: # Obtain a list of in order challenge ids for a playlist id_list = [int(s) for s in challenge_ids.split("|")] for id in id_list: for challenge in all_challenges: if challenge["id"] == id: challenges.append( dict(id=challenge["id"], name=challenge["name"], submitter_id=challenge["submitter_id"]) ) break # Add completion status if "user" in session: lookup = query_db("select solved_challenges from users where username = ?", [session["user"]], one=True) if lookup is not None and lookup[0] is not None: for completed_challenge in lookup[0].split("|"): for displayed_challenge in challenges: if str(displayed_challenge["id"]) == completed_challenge: displayed_challenge[ "completed" ] = 1 # The HTML page just checks for the existance of this key-value pair # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" return render_template("browse.html", challenges=challenges, playlist_name=playlist_name) else: abort(404)
def show_submissions(): if 'logged_in' not in session or session['logged_in'] == False: abort(401) # Convert session user to a user ID cur = query_db('select id from users where username = ?', [session['user']], one=True) if cur is not None: user_id = cur[0] else: abort(401) # Get stuff from the database cur = query_db('''select s.id, user_id, challenge_id, timestamp, status, status_info, c.name, language ''' '''from submissions s join challenges c on s.challenge_id = c.id where user_id = ?''', [user_id]) # Produce an array of hashes that looks something like: # [{id->'1', user_id->'5', problem_name->'2', timestamp->'<the time>', status->'Accepted', status_info->'Some Error', language->'C'}, {other hash}] submissions = [dict(id=row[0],user_id=row[1],challenge_name=row[6],timestamp=row[3],status=row[4],status_info=row[5],language=row[7]) for row in cur] # Send it to submissions return render_template('submissions.html', submissions=submissions)
def do_browse(com=False): if com is False: # com_flag of 2 signfies admin chosen challenges that can be attempted by anyone cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2' ) else: cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 1') challenges = [ dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur ] # Retrieve category names cur = query_db('select name from categories') if cur: categories = [dict(name=row[0]) for row in cur] # Add completion status if 'user' in session: lookup = query_db( "select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: for completed_challenge in lookup[0].split('|'): for displayed_challenge in challenges: if str(displayed_challenge["id"]) == completed_challenge: displayed_challenge[ "completed"] = 1 # The HTML page just checks for the existance of this key-value pair # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" return (challenges, categories)
def show_playlist_form(): if 'user' in session: cur = query_db('select id, name from challenges') challenges = [dict(id=row[0], name=row[1]) for row in cur] flags = {} play_id = None return render_template('new_playlist.html', challenges=challenges, flags=flags, play_id=play_id) else: abort(401)
def show_specific_submission(id): if 'logged_in' not in session or session['logged_in'] == False: abort(401) # look up DB for this partciular submission cur = query_db( '''select s.id, user_id, challenge_id, timestamp, status, status_info, c.name, s.code ''' ''' from submissions s join challenges c on s.challenge_id = c.id where s.id = ?''', [id], one=True) if cur is not None: _id = cur[0] else: abort(404) # Convert user_id to username cur2 = query_db('select username from users where id = ?', [cur[1]], one=True) if cur is not None: user_id = cur2[0] else: abort(401) # If the user doesn't own this submission, 401 unauth. if 'user' not in session or session['user'] != user_id: abort(401) problem_name = cur[6] timestamp = cur[3] status = cur[4] status_info = cur[5] code = cur[7] # Send it to the page return render_template('submission.html', id=_id, user_id=user_id, problem_name=problem_name, timestamp=timestamp, status=status, status_info=status_info, code=code)
def community_browse_post(): cur = query_db('select id, name, submitter_id from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur] # Retrieve category names cur = query_db('select name from categories'); if cur: categories = [dict(name=row[0]) for row in cur] if request.form.get('add') is not None: # Admin request to move challenges if session['user'] == "admin": for challenge in challenges: move_name = request.form.get(challenge['name']) if move_name: move = "update challenges set com_flag=0 where name=?;" update_db(move, [challenge['name']]) cur = query_db('select id, name, submitter_id from challenges where com_flag = 1') challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur] # Admin request to delete challenge elif request.form.get('delete_chal') is not None: if session['user'] == "admin": update_db('delete from challenges where name=?',[request.form.get('delete_chal')]) cur = query_db('select id, name, submitter_id from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur] # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge['submitter_id']], one=True) if lookup is not None: challenge['submitter_id'] = lookup[0] else: challenge['submitter_id'] = "DvJudge" vals = do_browse_post(com=True) return render_template('browse.html', challenges=vals[0], searchterm=vals[1], categories=vals[2], no_completed=vals[3], com_flag=True)
def get_forum_comments(forum_id): cur = g.db.cursor() cur.execute('select username, comment, post_time, comment_id from forum_comment where forum_page=?', [str(forum_id)]) comments = [dict(username=row[0],comment=row[1], post_time=row[2], comment_id=row[3], votes=get_forum_net_votes(row[3])) for row in cur] for comment in comments: # get user profile pics cur2 = query_db('select image from users where username=?', [comment["username"]], one=True) if cur2 is not None: comment["image"] = cur2[0] return comments
def updateprofile(): email = request.form["email"] username = request.form["username"] pass1 = request.form["pass1"] pass2 = request.form["pass2"] # check passwords are the same if pass1 != pass2: flash("Passwords do not match", "error") return redirect(url_for("profile")) # check username does not already exist username_check = query_db( """select id from users where username = ? and id != ?""", [username, session["userid"]], one=True ) if username_check is not None: flash("Username is already taken", "error") return redirect(url_for("profile")) # check email does not already exist email_check = query_db("""select id from users where email = ? and id != ?""", [email, session["userid"]], one=True) if email_check is not None: flash("Email is already taken", "error") return redirect(url_for("profile")) if pass1 != "" and pass2 != "": user_pass = query_db("""select salt from users where id = ?""", [session["userid"]], one=True) hashed_password = hashlib.sha512(pass1 + user_pass[0]).hexdigest() update_db( """update users set username = ?, email = ?, password = ? where id = ?""", [username, email, hashed_password, session["userid"]], ) else: update_db("""update users set username = ?, email = ? where id = ?""", [username, email, session["userid"]]) session["user"] = username return redirect(url_for("profile"))
def do_browse_post(com=False): # User is searching if request.form.get('searchterm') is not None: # Search passes a search term name = request.form.get('searchterm') if com is False: cur = query_db('select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2') else: cur = query_db('select id, name, submitter_id from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur] # Iterate over challenges, and only keep hashes (i.e. challenges) where the names match up results = [challenge for challenge in challenges if name.lower() in challenge["name"].lower()] # Add completion status if 'user' in session: lookup = query_db("select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: for completed_challenge in lookup[0].split('|'): for displayed_challenge in challenges: if str(displayed_challenge["id"]) == completed_challenge: displayed_challenge["completed"] = 1 # The HTML page just checks for the existance of this key-value pair # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" cur = query_db('select name from categories'); if cur: categories = [dict(name=row[0]) for row in cur] # Pass only those on return (results, request.form.get('searchterm'), categories, None) # Admin request to move challenges elif request.form.get('remove') is not None: if session['user'] == "admin": if com is False: cur = query_db('select id, name from challenges where com_flag = 0 or com_flag = 2') else: cur = query_db('select id, name from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [dict(id=row[0],name=row[1]) for row in cur] cur = query_db('select name from categories'); if cur: categories = [dict(name=row[0]) for row in cur] for challenge in challenges: move_name = request.form.get(challenge['name']) if move_name: move = "update challenges set com_flag=1 where name=?;" update_db(move, [challenge['name']]) if com is False: cur = query_db('select id, name from challenges where com_flag = 0 or com_flag = 2') else: cur = query_db('select id, name from challenges where com_flag = 1') challenges = [dict(id=row[0],name=row[1]) for row in cur] return (challenges, None, categories, None) # Admin request to delete challenge elif request.form.get('delete_chal') is not None: if session['user'] == "admin": update_db('delete from challenges where name=?',[request.form.get('delete_chal')]) if com is False: cur = query_db('select id, name from challenges where com_flag = 0 or com_flag = 2') else: cur = query_db('select id, name from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [dict(id=row[0],name=row[1]) for row in cur] cur = query_db('select name from categories'); if cur: categories = [dict(name=row[0]) for row in cur] return (challenges, None, categories, None) else: # If there's no searchterm and we get a post, it's probably filtering. # Retrieve category names cur = query_db('select name from categories'); categories = "" if cur: categories = [dict(name=row[0]) for row in cur] else: categories = None # Set categories matching_problems = [] # Check Completed filter no_completed = False if request.form.get("no_completed") is not None: no_completed = True # Check the ret of the filters, Figure out which ones were set, and keep them set no_filters = True for category in categories: if request.form.get(category["name"]) is not None: no_filters = False category["checked"] = True # Look it up in the DB to get problems in this category cur = query_db('select challenges from categories where name = ?', [category["name"]], one=True) if cur is not None: for category_problem in cur[0].split('|'): if category_problem != "" and int(category_problem) not in matching_problems: # Remember all the problems that match any filter matching_problems.append(int(category_problem)) else: abort(500) # Now pull all the problems and only keep matching_problems if com is False: cur = query_db('select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2') else: cur = query_db('select id, name, submitter_id from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur] # List comprehension, for each item in challenges, only keep ones that are in the matching_problems set if no_filters == False: challenges = [x for x in challenges if x["id"] in matching_problems] # If completed is turned on, we need to remove any matching_problems that are complete # Add completion status if no_completed == True and 'user' in session: lookup = query_db("select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: # List comprehension: Matching problems only challenges = [x for x in challenges if str(x["id"]) not in lookup[0].split('|')] # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" # Also figure out what to put in the completed column for the page, for the displayed problems if 'user' in session: lookup = query_db("select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: for completed_challenge in lookup[0].split('|'): for displayed_challenge in challenges: if str(displayed_challenge["id"]) == completed_challenge: displayed_challenge["completed"] = 1 # The HTML page just checks for the existance of this key-value pair return (challenges, None, categories, None)
def login_signup_form(): error = "" # print request.form['page'] if request.form["submit"] == 'signin': #retrieve username and password username = request.form['username'] password = request.form['password'] user_pass = query_db('select id, username, password, salt, image from users where username = ? or email = ?',[username,username], one=True) if user_pass is not None: #print user_pass hashed_password = hashlib.sha512(password + user_pass[3]).hexdigest() if username == user_pass[1] and hashed_password == user_pass[2]: session['userid'] = user_pass[0] session['logged_in'] = True session['user'] = username session['image'] = user_pass[4] flash('You were logged in','alert') else: error += "Username and password do not match" else: error += "Username and password do not match" #print request.form["submit"] if request.form["submit"] == 'signup': #check if duplicate username username = request.form['username'] value = query_db('select * from users where username = ?',[username], one=True) if value is not None: error += "Username is already taken\n" email = request.form['email'] password = request.form['password'] if len(password) < 6: error += "Passwords need to be 6 characters or longer" if not password or password != request.form['confirmpassword']: error += "Passwords do not match\n" else: #hash password and salt salt = uuid.uuid4().hex hashed_password = hashlib.sha512(password + salt).hexdigest() #submit info to the database g.db.execute("insert into users (username, email, password, salt) values (?, ?, ?, ?)", [username, email, hashed_password, salt]) g.db.commit() flash('You successfully created an account','alert') session['logged_in'] = True session['user'] = username session['userid'] = query_db('''select last_insert_rowid()''')[0][0]; session['image'] = "default_profile.jpg" flash('You were logged in','alert') if error != "": flash(error,'error') # session['error'] = error if request.form['page'] == "browse_specific_challenge": return redirect(url_for('browse_specific_challenge', challenge_name=request.form['challenge_name'])) if request.form['page'] == "forums_browse": return redirect(url_for('forums_browse', forum_problem=request.form['forum_problem'])) # if "forum_question" in request.form: if request.form['page'] == "forums_question": return redirect(url_for('forums_question', forum_problem=request.form['forum_problem'], forum_question=request.form['forum_question'])) return redirect(url_for(request.form['page']))
def submit_specific_challenge(): skip = False language = request.form.get('language') #if user is logged in the compiled file will be under the username if 'user' in session: username = session['user'] user_id = query_db('select id from users where username = ?', [username], one=True)[0] else: username = '******' skip = True #do database stuff challenge_id = request.args.get('challenge_id') cur = query_db('select * from challenges where id = ?', [challenge_id], one=True) if cur is not None: challenge_id = cur[0] name = cur[1] description = cur[2] input_tests = cur[3] expected_output = cur[4] sample_tests = cur[5] input_desc = cur[6] output_desc = cur[7] else: abort(404) challenge_info = { 'challenge_id': challenge_id, 'name': name, 'description': description, 'sample_tests': sample_tests, 'input_desc': input_desc, 'output_desc': output_desc } # get the code from the form code = request.form['editor'] session['code'] = code session['language'] = language # create a directory for current submission directory = subprocess.Popen(['sudo', 'mkdir', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) directory.wait() directory = subprocess.Popen( ['sudo', 'chown', 'azureuser:azureuser', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) directory.wait() if language == 'C': result = run_c(code=code, username=username, input_tests=input_tests, expected_output=expected_output) elif language == 'C++': result = run_c_plus(code=code, username=username, input_tests=input_tests, expected_output=expected_output) elif language == 'Python': result = run_python(code=code, username=username, input_tests=input_tests, expected_output=expected_output) elif language == 'Java': result = run_java(code=code, username=username, input_tests=input_tests, expected_output=expected_output) else: result = {'output': 'Unknown language', 'status': 'Error'} # if not a default user, the one that is just trying out the website new_solved_challenges = "" if not skip: update_db( "insert into submissions (user_id, challenge_id, status, status_info, language, code) values (?, ?, ?, ?, ?, ?)", [ user_id, challenge_id, result['status'], result['output'], language, code ]) # Check to see if the user has completed this challenge lookup = query_db("select solved_challenges from users where id = ?", [user_id], one=True) done = False if lookup is not None and lookup[0] is not None: new_solved_challenges = lookup[0] for challenge_done in lookup[0].split('|'): if int(challenge_done) == challenge_id: done = True break # If they haven't done it before, append it to their done list if done == False: if new_solved_challenges == "": new_solved_challenges = challenge_info["challenge_id"] else: new_solved_challenges += "|" + str( challenge_info["challenge_id"]) update_db("update users set solved_challenges = ? where id = ?", [new_solved_challenges, user_id]) #clean up subprocess.Popen(['sudo', 'rm', '-rf', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if len(result['output']) > 2069: result['output'] = result['output'][:2069] session['output'] = result['output'] return redirect(url_for('browse_specific_challenge', challenge_name=name))
def do_browse_post(com=False): # User is searching if request.form.get( 'searchterm') is not None: # Search passes a search term name = request.form.get('searchterm') if com is False: cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2' ) else: cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 1' ) # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [ dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur ] # Iterate over challenges, and only keep hashes (i.e. challenges) where the names match up results = [ challenge for challenge in challenges if name.lower() in challenge["name"].lower() ] # Add completion status if 'user' in session: lookup = query_db( "select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: for completed_challenge in lookup[0].split('|'): for displayed_challenge in challenges: if str(displayed_challenge["id"] ) == completed_challenge: displayed_challenge[ "completed"] = 1 # The HTML page just checks for the existance of this key-value pair # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" cur = query_db('select name from categories') if cur: categories = [dict(name=row[0]) for row in cur] # Pass only those on return (results, request.form.get('searchterm'), categories, None) # Admin request to move challenges elif request.form.get('remove') is not None: if session['user'] == "admin": if com is False: cur = query_db( 'select id, name from challenges where com_flag = 0 or com_flag = 2' ) else: cur = query_db( 'select id, name from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [dict(id=row[0], name=row[1]) for row in cur] cur = query_db('select name from categories') if cur: categories = [dict(name=row[0]) for row in cur] for challenge in challenges: move_name = request.form.get(challenge['name']) if move_name: move = "update challenges set com_flag=1 where name=?;" update_db(move, [challenge['name']]) if com is False: cur = query_db( 'select id, name from challenges where com_flag = 0 or com_flag = 2' ) else: cur = query_db( 'select id, name from challenges where com_flag = 1') challenges = [dict(id=row[0], name=row[1]) for row in cur] return (challenges, None, categories, None) # Admin request to delete challenge elif request.form.get('delete_chal') is not None: if session['user'] == "admin": update_db('delete from challenges where name=?', [request.form.get('delete_chal')]) if com is False: cur = query_db( 'select id, name from challenges where com_flag = 0 or com_flag = 2' ) else: cur = query_db( 'select id, name from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [dict(id=row[0], name=row[1]) for row in cur] cur = query_db('select name from categories') if cur: categories = [dict(name=row[0]) for row in cur] return (challenges, None, categories, None) else: # If there's no searchterm and we get a post, it's probably filtering. # Retrieve category names cur = query_db('select name from categories') categories = "" if cur: categories = [dict(name=row[0]) for row in cur] else: categories = None # Set categories matching_problems = [] # Check Completed filter no_completed = False if request.form.get("no_completed") is not None: no_completed = True # Check the ret of the filters, Figure out which ones were set, and keep them set no_filters = True for category in categories: if request.form.get(category["name"]) is not None: no_filters = False category["checked"] = True # Look it up in the DB to get problems in this category cur = query_db( 'select challenges from categories where name = ?', [category["name"]], one=True) if cur is not None: for category_problem in cur[0].split('|'): if category_problem != "" and int( category_problem) not in matching_problems: # Remember all the problems that match any filter matching_problems.append(int(category_problem)) else: abort(500) # Now pull all the problems and only keep matching_problems if com is False: cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2' ) else: cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 1' ) # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [ dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur ] # List comprehension, for each item in challenges, only keep ones that are in the matching_problems set if no_filters == False: challenges = [ x for x in challenges if x["id"] in matching_problems ] # If completed is turned on, we need to remove any matching_problems that are complete # Add completion status if no_completed == True and 'user' in session: lookup = query_db( "select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: # List comprehension: Matching problems only challenges = [ x for x in challenges if str(x["id"]) not in lookup[0].split('|') ] # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" # Also figure out what to put in the completed column for the page, for the displayed problems if 'user' in session: lookup = query_db( "select solved_challenges from users where username = ?", [session['user']], one=True) if lookup is not None and lookup[0] is not None: for completed_challenge in lookup[0].split('|'): for displayed_challenge in challenges: if str(displayed_challenge["id"] ) == completed_challenge: displayed_challenge[ "completed"] = 1 # The HTML page just checks for the existance of this key-value pair return (challenges, None, categories, None)
def show_playlists(): if "user" in session: username = session["user"] # Convert user session to user ID cur = query_db("select id from users where username = ?", [username], one=True) if cur is not None: owner_id = str(cur[0]) # Check if selected 'Delete Playlist' del_name = request.form.get("delete_list") if del_name: update_db("delete from playlists where owner_id=? and name=?", [owner_id, del_name]) # Retrieve the playlists available to this user cur = query_db("select * from playlists where owner_id = ?", [cur[0]]) # Build a dictionary to pass to the page later # Dictionary contains playlist name, id, and which challenges belong to it playlists = [dict(id=row[0], name=row[1], challenges=row[3]) for row in cur] if playlists: selected_name = request.form.get("selected_name") selection = playlists[0] if selected_name is not None: for play in playlists: if play["name"] == selected_name: selection = play cur = query_db("select id, name, submitter_id from challenges") challenges = [dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur] challenge_list = [] # Determine whether Submit Changes was pressed auto_reorder = request.form.get("auto") if auto_reorder: reorder_entry = {} # Match each challenge to their new order for challenge in challenges: if request.form.get(challenge["name"]): chal_order = int(request.form.get(challenge["name"])) chal_id = int(challenge["id"]) reorder_entry[chal_order] = chal_id # Generate an order string to insert into the database new_order = "" for key in reorder_entry: if not new_order: new_order = str(reorder_entry[key]) else: new_order += "|" + str(reorder_entry[key]) reorder_str = "update playlists set challenges=? where name=? and owner_id=?;" update_db(reorder_str, [new_order, selection["name"], owner_id]) challenge_ids = new_order else: challenge_ids = selection["challenges"] if challenge_ids: # Obtain a list of in order challenge ids for a playlist id_list = [int(s) for s in challenge_ids.split("|")] for id in id_list: for challenge in challenges: if challenge["id"] == id: # Convert user_ids to usernames lookup = query_db( "select username from users where id = ?", [challenge["submitter_id"]], one=True ) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" # Add challenges to list challenge_list.append(challenge) break else: playlists = None selection = None challenge_list = None # Passing playlists.html all the playilst info in a hash return render_template( "playlists.html", playlists=playlists, selection=selection, challenge_list=challenge_list ) else: abort(401) else: abort(401)
def browse_specific_challenge(challenge_name): supported_languages = {'C', 'Python', 'Java', 'C++'} data = {'C':"// enter code here", 'Python':"# enter code here", 'Java':"// enter code here", 'C++':"// enter code here"} cur = query_db('select * from challenges where name = ?', [challenge_name], one=True) if cur is not None: challenge_id = cur[0] name = cur[1] description = cur[2] sample_tests = cur[5] input_desc = cur[6] output_desc = cur[7] com_flag = cur[8] else: abort(404) challenge_info = {'challenge_id': challenge_id, 'name': name, 'description': description, 'sample_tests': sample_tests, 'input_desc': input_desc, 'output_desc': output_desc, 'languages':supported_languages, 'com_flag':com_flag} #check for posted comment if request.method == 'POST': comment = request.form['comment'] if comment: post_comment(session['user'], challenge_id, comment) #Check if it's a redirect from submission and the program #has produced output #Stored in session cookie if 'output' in session: info = session['output'] session.pop('output', None) else: info = None #check for submitted code from user if 'code' in session: code = session['code'] session.pop('code', None) else: code = None if 'language' in session: language = session['language'] session.pop('language', None) else: language = 'C' # Variables for playlist add exists = False playlist_name = request.args.get('playlist_name') # Prepare playlist information for the dropdown if user logged in playlists = {} if 'user' in session: username = session['user'] # Convert user session to user ID cur = query_db('select id from users where username = ?', [username], one=True) if cur is not None: user_id = cur[0] # Retrieve the playlists available to this user cur = query_db('select * from playlists where owner_id = ?', [cur[0]]) # Build a dictionary to pass to the page later playlists = [dict(id=row[0],name=row[1]) for row in cur] # Selected to add to playlist if playlist_name: add_list = query_db('select * from playlists where owner_id = ? and name = ?', [user_id, playlist_name], one=True) # Check if playlist name exists if add_list is not None: challenge_ids = add_list[3] # Check that challenge IDs is not an empty string if challenge_ids: id_list = [int(s) for s in challenge_ids.split('|')] if challenge_id not in id_list: challenge_ids += "|" + str(challenge_id) # if challenge id is in list, set the exists flag for the alert else: exists = True # Add id to playlist else: challenge_ids = str(challenge_id) add_str = "update playlists set challenges=? where name=? and owner_id=?;" update_db(add_str, [challenge_ids,playlist_name,user_id]) # Playlist name not found else: playlist_name = "" else: abort(401) #insert the comments section question_comments = get_comments(challenge_id) return render_template('challenge.html', challenge_info=challenge_info, output=info, code=code, playlists=playlists, language=language, comments=question_comments, data=json.dumps(data), playlist_name=playlist_name, exists=exists)
def browse_specific_challenge(challenge_name): supported_languages = {'C', 'Python', 'Java', 'C++'} data = { 'C': "// enter code here", 'Python': "# enter code here", 'Java': "// enter code here", 'C++': "// enter code here" } cur = query_db('select * from challenges where name = ?', [challenge_name], one=True) if cur is not None: challenge_id = cur[0] name = cur[1] description = cur[2] sample_tests = cur[5] input_desc = cur[6] output_desc = cur[7] com_flag = cur[8] else: abort(404) challenge_info = { 'challenge_id': challenge_id, 'name': name, 'description': description, 'sample_tests': sample_tests, 'input_desc': input_desc, 'output_desc': output_desc, 'languages': supported_languages, 'com_flag': com_flag } #check for posted comment if request.method == 'POST': comment = request.form['comment'] if comment: post_comment(session['user'], challenge_id, comment) #Check if it's a redirect from submission and the program #has produced output #Stored in session cookie if 'output' in session: info = session['output'] session.pop('output', None) else: info = None #check for submitted code from user if 'code' in session: code = session['code'] session.pop('code', None) else: code = None if 'language' in session: language = session['language'] session.pop('language', None) else: language = 'C' # Variables for playlist add exists = False playlist_name = request.args.get('playlist_name') # Prepare playlist information for the dropdown if user logged in playlists = {} if 'user' in session: username = session['user'] # Convert user session to user ID cur = query_db('select id from users where username = ?', [username], one=True) if cur is not None: user_id = cur[0] # Retrieve the playlists available to this user cur = query_db('select * from playlists where owner_id = ?', [cur[0]]) # Build a dictionary to pass to the page later playlists = [dict(id=row[0], name=row[1]) for row in cur] # Selected to add to playlist if playlist_name: add_list = query_db( 'select * from playlists where owner_id = ? and name = ?', [user_id, playlist_name], one=True) # Check if playlist name exists if add_list is not None: challenge_ids = add_list[3] # Check that challenge IDs is not an empty string if challenge_ids: id_list = [int(s) for s in challenge_ids.split('|')] if challenge_id not in id_list: challenge_ids += "|" + str(challenge_id) # if challenge id is in list, set the exists flag for the alert else: exists = True # Add id to playlist else: challenge_ids = str(challenge_id) add_str = "update playlists set challenges=? where name=? and owner_id=?;" update_db(add_str, [challenge_ids, playlist_name, user_id]) # Playlist name not found else: playlist_name = "" else: abort(401) #insert the comments section question_comments = get_comments(challenge_id) return render_template('challenge.html', challenge_info=challenge_info, output=info, code=code, playlists=playlists, language=language, comments=question_comments, data=json.dumps(data), playlist_name=playlist_name, exists=exists)
def show_playlists(): if 'user' in session: username = session['user'] # Convert user session to user ID cur = query_db('select id from users where username = ?', [username], one=True) if cur is not None: owner_id = str(cur[0]) # Check if selected 'Delete Playlist' del_name = request.form.get('delete_list') if del_name: update_db('delete from playlists where owner_id=? and name=?', [owner_id, del_name]) # Retrieve the playlists available to this user cur = query_db('select * from playlists where owner_id = ?', [cur[0]]) # Build a dictionary to pass to the page later # Dictionary contains playlist name, id, and which challenges belong to it playlists = [ dict(id=row[0], name=row[1], challenges=row[3]) for row in cur ] if playlists: selected_name = request.form.get('selected_name') selection = playlists[0] if selected_name is not None: for play in playlists: if play['name'] == selected_name: selection = play cur = query_db('select id, name, submitter_id from challenges') challenges = [ dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur ] challenge_list = [] # Determine whether Submit Changes was pressed auto_reorder = request.form.get('auto') if auto_reorder: reorder_entry = {} # Match each challenge to their new order for challenge in challenges: if request.form.get(challenge['name']): chal_order = int( request.form.get(challenge['name'])) chal_id = int(challenge['id']) reorder_entry[chal_order] = chal_id # Generate an order string to insert into the database new_order = "" for key in reorder_entry: if not new_order: new_order = str(reorder_entry[key]) else: new_order += "|" + str(reorder_entry[key]) reorder_str = "update playlists set challenges=? where name=? and owner_id=?;" update_db(reorder_str, [new_order, selection['name'], owner_id]) challenge_ids = new_order else: challenge_ids = selection['challenges'] if challenge_ids: # Obtain a list of in order challenge ids for a playlist id_list = [int(s) for s in challenge_ids.split('|')] for id in id_list: for challenge in challenges: if challenge['id'] == id: # Convert user_ids to usernames lookup = query_db( "select username from users where id = ?", [challenge["submitter_id"]], one=True) if lookup is not None: challenge["submitter_id"] = lookup[0] else: challenge["submitter_id"] = "DvJudge" # Add challenges to list challenge_list.append(challenge) break else: playlists = None selection = None challenge_list = None # Passing playlists.html all the playilst info in a hash return render_template('playlists.html', playlists=playlists, selection=selection, challenge_list=challenge_list) else: abort(401) else: abort(401)
def create_new_playlist(): if 'user' in session: username = session['user'] cur = query_db('select id from users where username = ?', [username], one=True) if cur is not None: user_id = cur[0] # Set fields to check to false and grab playlist name flags = { 'no_name': False, 'conflict_name': False, 'new_name': None } playlist_name = request.form.get('playlist_name') temp = re.sub('[\s+]', '', playlist_name) play_id = None cur = query_db('select id, name from challenges') challenges = [dict(id=row[0], name=row[1]) for row in cur] # If invalid playlist name, flash an alert if not request.form.get('playlist_name') or not temp: flags['no_name'] = True # Insert new playlist into database else: flags['new_name'] = playlist_name cur2 = query_db( 'select * from playlists where owner_id = ? and name = ?', [user_id, playlist_name], one=True) if cur2 is None: play_id = random.randint(0, 1000000) id_check = query_db('select * from playlists where id = ?', [play_id], one=True) while id_check is not None: play_id = random.randint(0, 1000000) id_check = query_db( 'select * from playlists where id = ?', [play_id], one=True) challenge_ids = "" for challenge in challenges: id = request.form.get(challenge['name']) if id: if not challenge_ids: challenge_ids = str(id) else: challenge_ids += "|" + str(id) g.db.execute( 'insert into playlists (id, name, owner_id, challenges) values (?, ?, ?, ?)', [play_id, playlist_name, user_id, challenge_ids]) g.db.commit() else: flags['conflict_name'] = True return render_template('new_playlist.html', challenges=challenges, flags=flags, play_id=play_id) else: abort(401) else: abort(401)
def community_browse_post(): cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 1') # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [ dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur ] # Retrieve category names cur = query_db('select name from categories') if cur: categories = [dict(name=row[0]) for row in cur] if request.form.get('add') is not None: # Admin request to move challenges if session['user'] == "admin": for challenge in challenges: move_name = request.form.get(challenge['name']) if move_name: move = "update challenges set com_flag=0 where name=?;" update_db(move, [challenge['name']]) cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 1' ) challenges = [ dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur ] # Admin request to delete challenge elif request.form.get('delete_chal') is not None: if session['user'] == "admin": update_db('delete from challenges where name=?', [request.form.get('delete_chal')]) cur = query_db( 'select id, name, submitter_id from challenges where com_flag = 1' ) # Produce an array of hashes that looks something like: # [{id->'1', name->'some challenge name'}, {other hash}] challenges = [ dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur ] # Convert user_ids to usernames for challenge in challenges: lookup = query_db("select username from users where id = ?", [challenge['submitter_id']], one=True) if lookup is not None: challenge['submitter_id'] = lookup[0] else: challenge['submitter_id'] = "DvJudge" vals = do_browse_post(com=True) return render_template('browse.html', challenges=vals[0], searchterm=vals[1], categories=vals[2], no_completed=vals[3], com_flag=True)
def upload(): # Retrieve category names cur = query_db('select name from categories'); if cur: categories = [dict(name=row[0]) for row in cur] # Initialise alert flags flags = {} # Someone is trying to submit a new challenge if request.method == 'POST': if 'user' not in session: abort(401) # Find out who's submitting a problem. lookup = query_db("select id from users where username = ?", [session['user']], one=True) user_id = lookup[0] if user_id is None: abort(401) challenge_name = request.form.get('challenge_name') description = request.form.get('description') input_ = request.form.get('input_') output_ = request.form.get('output_') tests = request.form.get('tests') input_desc = request.form.get('input_desc') output_desc = request.form.get('output_desc') flags['empty'] = False flags['length'] = False flags['special'] = False flags['conflict'] = False flags['success'] = False flags['inempty'] = False flags['outempty'] = False # Check if challenge_name is empty temp = re.sub('[\s+]', '', challenge_name) in_temp = re.sub('[\s+]', '', input_) out_temp = re.sub('[\s+]', '', output_) if not challenge_name or not temp: flags['empty'] = True elif len(challenge_name) > 70: flags['length'] = True elif not whitelist(challenge_name): flags['special'] = True elif not input_ or not in_temp: flags['inempty'] = True elif not output_ or not out_temp: flags['outempty'] = True if flags['empty'] or flags['length'] or flags['special'] or flags['inempty'] or flags['outempty']: return render_template('upload_challenge.html', challenge_name=challenge_name, description=description, input_=input_, output_=output_, tests=tests, input_desc=input_desc, output_desc=output_desc, categories=categories, flags=flags) # Check if the challenge_name already exists in the db cur = query_db('select * from challenges where name = ?', [challenge_name], one=True) if cur is None: add_challenge (challenge_name, description, input_, output_, tests,input_desc, output_desc, user_id) # Get new challenge instance cur = query_db('select * from challenges where name = ?', [challenge_name], one=True) # Check if adding to a category if cur is not None: for category in categories: category_name = request.form.get(category['name']) if category_name: cur2 = query_db('select * from categories where name = ?', [category_name], one=True) if cur2 is not None: challenge_ids = cur2[1] if challenge_ids: challenge_ids += "|" + str(cur[0]) else: challenge_ids = str(cur[0]) new_chal = "update categories set challenges=? where name=?;" update_db(new_chal, [challenge_ids,category_name]) flags['success'] = True return render_template('upload_challenge.html', categories=categories, flags=flags) # If the challenge_name is not fresh, leave the user's details in the page else: flags['conflict'] = True render_template('upload_challenge.html', challenge_name=challenge_name, description=description, input_=input_, output_=output_, tests=tests, input_desc=input_desc, output_desc=output_desc, categories=categories, flags=flags) return render_template('upload_challenge.html', categories=categories, flags=flags)
def upload(): # Retrieve category names cur = query_db('select name from categories') if cur: categories = [dict(name=row[0]) for row in cur] # Initialise alert flags flags = {} # Someone is trying to submit a new challenge if request.method == 'POST': if 'user' not in session: abort(401) # Find out who's submitting a problem. lookup = query_db("select id from users where username = ?", [session['user']], one=True) user_id = lookup[0] if user_id is None: abort(401) challenge_name = request.form.get('challenge_name') description = request.form.get('description') input_ = request.form.get('input_') output_ = request.form.get('output_') tests = request.form.get('tests') input_desc = request.form.get('input_desc') output_desc = request.form.get('output_desc') flags['empty'] = False flags['length'] = False flags['special'] = False flags['conflict'] = False flags['success'] = False flags['inempty'] = False flags['outempty'] = False # Check if challenge_name is empty temp = re.sub('[\s+]', '', challenge_name) in_temp = re.sub('[\s+]', '', input_) out_temp = re.sub('[\s+]', '', output_) if not challenge_name or not temp: flags['empty'] = True elif len(challenge_name) > 70: flags['length'] = True elif not whitelist(challenge_name): flags['special'] = True elif not input_ or not in_temp: flags['inempty'] = True elif not output_ or not out_temp: flags['outempty'] = True if flags['empty'] or flags['length'] or flags['special'] or flags[ 'inempty'] or flags['outempty']: return render_template('upload_challenge.html', challenge_name=challenge_name, description=description, input_=input_, output_=output_, tests=tests, input_desc=input_desc, output_desc=output_desc, categories=categories, flags=flags) # Check if the challenge_name already exists in the db cur = query_db('select * from challenges where name = ?', [challenge_name], one=True) if cur is None: add_challenge(challenge_name, description, input_, output_, tests, input_desc, output_desc, user_id) # Get new challenge instance cur = query_db('select * from challenges where name = ?', [challenge_name], one=True) # Check if adding to a category if cur is not None: for category in categories: category_name = request.form.get(category['name']) if category_name: cur2 = query_db( 'select * from categories where name = ?', [category_name], one=True) if cur2 is not None: challenge_ids = cur2[1] if challenge_ids: challenge_ids += "|" + str(cur[0]) else: challenge_ids = str(cur[0]) new_chal = "update categories set challenges=? where name=?;" update_db(new_chal, [challenge_ids, category_name]) flags['success'] = True return render_template('upload_challenge.html', categories=categories, flags=flags) # If the challenge_name is not fresh, leave the user's details in the page else: flags['conflict'] = True render_template('upload_challenge.html', challenge_name=challenge_name, description=description, input_=input_, output_=output_, tests=tests, input_desc=input_desc, output_desc=output_desc, categories=categories, flags=flags) return render_template('upload_challenge.html', categories=categories, flags=flags)
def submit_specific_challenge(): skip = False language = request.form.get('language') #if user is logged in the compiled file will be under the username if 'user' in session: username = session['user'] user_id = query_db('select id from users where username = ?',[username], one=True)[0] else: username = '******' skip = True #do database stuff challenge_id = request.args.get('challenge_id') cur = query_db('select * from challenges where id = ?', [challenge_id], one=True) if cur is not None: challenge_id = cur[0] name = cur[1] description = cur[2] input_tests = cur[3] expected_output = cur[4] sample_tests= cur[5] input_desc = cur[6] output_desc = cur[7] else: abort(404) challenge_info = {'challenge_id': challenge_id, 'name': name, 'description': description, 'sample_tests': sample_tests, 'input_desc': input_desc, 'output_desc': output_desc} # get the code from the form code = request.form['editor'] session['code'] = code session['language'] = language # create a directory for current submission directory = subprocess.Popen(['sudo','mkdir', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) directory.wait() directory = subprocess.Popen(['sudo','chown', 'azureuser:azureuser', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) directory.wait() if language == 'C': result = run_c(code=code, username = username, input_tests = input_tests, expected_output = expected_output) elif language == 'C++': result = run_c_plus(code=code, username = username, input_tests = input_tests, expected_output = expected_output) elif language == 'Python': result = run_python(code=code, username = username, input_tests = input_tests, expected_output = expected_output) elif language == 'Java': result = run_java(code=code, username = username, input_tests = input_tests, expected_output = expected_output) else: result = {'output': 'Unknown language', 'status':'Error'} # if not a default user, the one that is just trying out the website new_solved_challenges = "" if not skip: update_db("insert into submissions (user_id, challenge_id, status, status_info, language, code) values (?, ?, ?, ?, ?, ?)", [user_id,challenge_id,result['status'],result['output'],language,code]) # Check to see if the user has completed this challenge lookup = query_db("select solved_challenges from users where id = ?", [user_id], one=True) done = False if lookup is not None and lookup[0] is not None: new_solved_challenges = lookup[0] for challenge_done in lookup[0].split('|'): if int(challenge_done) == challenge_id: done = True break # If they haven't done it before, append it to their done list if done == False: if new_solved_challenges == "": new_solved_challenges = challenge_info["challenge_id"] else: new_solved_challenges += "|" + str(challenge_info["challenge_id"]) update_db("update users set solved_challenges = ? where id = ?", [new_solved_challenges, user_id]) #clean up subprocess.Popen(['sudo','rm', '-rf', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if len(result['output']) > 2069: result['output'] = result['output'][:2069] session['output'] = result['output'] return redirect(url_for('browse_specific_challenge', challenge_name=name))
def login_signup_form(): error = "" # print request.form['page'] if request.form["submit"] == 'signin': #retrieve username and password username = request.form['username'] password = request.form['password'] user_pass = query_db( 'select id, username, password, salt, image from users where username = ? or email = ?', [username, username], one=True) if user_pass is not None: #print user_pass hashed_password = hashlib.sha512(password + user_pass[3]).hexdigest() if username == user_pass[1] and hashed_password == user_pass[2]: session['userid'] = user_pass[0] session['logged_in'] = True session['user'] = username session['image'] = user_pass[4] flash('You were logged in', 'alert') else: error += "Username and password do not match" else: error += "Username and password do not match" #print request.form["submit"] if request.form["submit"] == 'signup': #check if duplicate username username = request.form['username'] value = query_db('select * from users where username = ?', [username], one=True) if value is not None: error += "Username is already taken\n" email = request.form['email'] password = request.form['password'] if len(password) < 6: error += "Passwords need to be 6 characters or longer" if not password or password != request.form['confirmpassword']: error += "Passwords do not match\n" else: #hash password and salt salt = uuid.uuid4().hex hashed_password = hashlib.sha512(password + salt).hexdigest() #submit info to the database g.db.execute( "insert into users (username, email, password, salt) values (?, ?, ?, ?)", [username, email, hashed_password, salt]) g.db.commit() flash('You successfully created an account', 'alert') session['logged_in'] = True session['user'] = username session['userid'] = query_db( '''select last_insert_rowid()''')[0][0] session['image'] = "default_profile.jpg" flash('You were logged in', 'alert') if error != "": flash(error, 'error') # session['error'] = error if request.form['page'] == "browse_specific_challenge": return redirect( url_for('browse_specific_challenge', challenge_name=request.form['challenge_name'])) if request.form['page'] == "forums_browse": return redirect( url_for('forums_browse', forum_problem=request.form['forum_problem'])) # if "forum_question" in request.form: if request.form['page'] == "forums_question": return redirect( url_for('forums_question', forum_problem=request.form['forum_problem'], forum_question=request.form['forum_question'])) return redirect(url_for(request.form['page']))