def UpdateUserPoints(UserID): # Start user point count UserPoints = 0 # Query all complete unique solutions challenges = Challenges.QueryAllChallenges() for challenge in challenges: if Solutions.HasUserSolvedChallenge(UserID, challenge.ChallengeID): UserPoints += Challenges.ChallengeQueryID(challenge.ChallengeID).Points # Query all achievements achievements = Achievements.AchievementsQueryUserID(UserID) for achievement in achievements: UserPoints += int(achievement.AchievementScore) # Update this user's score in the database ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserID == UserID).all() # Commit changes if len(ExistingUsers) == 1: ExistingUsers[0].UserPoints = UserPoints Session.commit() # Post to session if we have a matching ID (otherwise, just return the user points) if session.get("UserID") and session["UserID"] == UserID: session["UserPoints"] = UserPoints session.save() return UserPoints
def UserDelete(UserID, Password, ConfirmPassword): # Is the form empty? Return no error... if not UserID and not Password and not ConfirmPassword: return "" # Do these user passwords match? if Password != ConfirmPassword: return "Error: Passwords do not match!" # Get existing user ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserID == UserID).all() if len(ExistingUsers) <= 0: return "Error: User name does not exist." ExistingUser = ExistingUsers[0] # Is the given password the active password? ExistingHash = __GeneratePasswordHash(Password) if ExistingUser.UserPassword != ExistingHash: return "Error: Given password is not correct." # Delete user from users table Session.delete(ExistingUser) Session.commit() # Logout user UserLogout() # Done! return "deleted"
def UserDelete(UserID, Password, ConfirmPassword): # Is the form empty? Return no error... if not UserID and not Password and not ConfirmPassword: return "" # Do these user passwords match? if Password != ConfirmPassword: return "Error: Passwords do not match!" # Get existing user ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserID == UserID).all() if len(ExistingUsers) <= 0: return "Error: User name does not exist." ExistingUser = ExistingUsers[0] # Is the given password the active password? ExistingHash = __GeneratePasswordHash(Password) if ExistingUser.UserPassword != ExistingHash: return "Error: Given password is not correct." # Delete user from users table Session.delete(ExistingUser) Session.commit() # Logout user UserLogout() # Done! return "deleted"
def UserSetIconID(UserID, IconID): # Convert to integer if not IconID.isdigit(): return "Error: IconID is not an integer." else: IconID = int(IconID) # Bounds check the icon ID (should only range betwee [0, 18] if IconID < 0 or IconID > 19: return "Error: IconID is out of range." # Update this user's score in the database ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserID == UserID).all() # Commit changes if len(ExistingUsers) == 1: ExistingUsers[0].IconID = IconID Session.commit() else: return "Error: No users found." # Post to session if we have a matching ID (otherwise, just return the user points) if session.get("UserID") and session["UserID"] == UserID: session["UserIconID"] = IconID session.save() # All done! return "Icon change saved!"
def UpdateUserPoints(UserID): # Start user point count UserPoints = 0 # Query all complete unique solutions challenges = Challenges.QueryAllChallenges() for challenge in challenges: if Solutions.HasUserSolvedChallenge(UserID, challenge.ChallengeID): UserPoints += Challenges.ChallengeQueryID(challenge.ChallengeID).Points # Query all achievements achievements = Achievements.AchievementsQueryUserID(UserID) for achievement in achievements: UserPoints += int(achievement.AchievementScore) # Update this user's score in the database ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserID == UserID).all() # Commit changes if len(ExistingUsers) == 1: ExistingUsers[0].UserPoints = UserPoints Session.commit() # Post to session if we have a matching ID (otherwise, just return the user points) if session.get("UserID") and session["UserID"] == UserID: session["UserPoints"] = UserPoints session.save() return UserPoints
def UserSetIconID(UserID, IconID): # Convert to integer if not IconID.isdigit(): return "Error: IconID is not an integer." else: IconID = int(IconID) # Bounds check the icon ID (should only range betwee [0, 18] if IconID < 0 or IconID > 19: return "Error: IconID is out of range." # Update this user's score in the database ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserID == UserID).all() # Commit changes if len(ExistingUsers) == 1: ExistingUsers[0].IconID = IconID Session.commit() else: return "Error: No users found." # Post to session if we have a matching ID (otherwise, just return the user points) if session.get("UserID") and session["UserID"] == UserID: session["UserIconID"] = IconID session.save() # All done! return "Icon change saved!"
def UserReset(UserName): # Get existing user ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all() if len(ExistingUsers) <= 0: return "Error: User name does not exist." # Register this new user into the database ExistingUser = ExistingUsers[0] # Randomize an 8-character string NewPassword = "" for i in range(8): NewPassword += random.choice(h.string_whitelist) # Send an email with the password try: # Form a message message = """\ From: [email protected] To: %s Subject: Password Change New Password: \"%s\" (Change this as soon as possible!) Visit www.corecodex.com to learn more. """ % ( ExistingUser.UserEMail, NewPassword, ) # Send mail s = smtplib.SMTP() s.connect() s.sendmail("*****@*****.**", ExistingUser.UserEMail, message) s.quit() except: return "Error: Unable to send email. Password was not reset." # Hash password ExistingUser.UserPassword = __GeneratePasswordHash(NewPassword) # Save changes to DB; done! Session.commit() return ""
def UserLogin(UserName, UserPassword, IgnoreRedirect = False): # Check for cookies - are we already logged in? if not IgnoreRedirect and session.get("UserName"): return "redirect" # Check for missing strings if not UserName: return "Error: Missing user name." if not UserPassword: return "Error: Missing password." # Does this username exist in the db? ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all() if len(ExistingUsers) <= 0: return "Error: User does not exist." # Pull up this user's information ExistingUser = ExistingUsers[0] # Hash password UserPassword = __GeneratePasswordHash(UserPassword) # Do the passwords match? if ExistingUser.UserPassword != UserPassword: return "Error: User password mismatch." # Update the login count by 1 and the login time ExistingUser.LogInCount += 1 ExistingUser.LastLogin = datetime.datetime.now() Session.commit() # Go ahead and start the cookie! session["UserID"] = ExistingUser.UserID session["UserName"] = ExistingUser.UserName session["UserPoints"] = UpdateUserPoints(ExistingUser.UserID) session["UserIconID"] = ExistingUser.IconID if ExistingUser.IsAdmin == 1: session["IsAdmin"] = True else: session["IsAdmin"] = False session.save() # All done return ""
def UserLogin(UserName, UserPassword, IgnoreRedirect=False): # Check for cookies - are we already logged in? if not IgnoreRedirect and session.get("UserName"): return "redirect" # Check for missing strings if not UserName: return "Error: Missing user name." if not UserPassword: return "Error: Missing password." # Does this username exist in the db? ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all() if len(ExistingUsers) <= 0: return "Error: User does not exist." # Pull up this user's information ExistingUser = ExistingUsers[0] # Hash password UserPassword = __GeneratePasswordHash(UserPassword) # Do the passwords match? if ExistingUser.UserPassword != UserPassword: return "Error: User password mismatch." # Update the login count by 1 and the login time ExistingUser.LogInCount += 1 ExistingUser.LastLogin = datetime.datetime.now() Session.commit() # Go ahead and start the cookie! session["UserID"] = ExistingUser.UserID session["UserName"] = ExistingUser.UserName session["UserPoints"] = UpdateUserPoints(ExistingUser.UserID) session["UserIconID"] = ExistingUser.IconID if ExistingUser.IsAdmin == 1: session["IsAdmin"] = True else: session["IsAdmin"] = False session.save() # All done return ""
def SetUserPassword(UserName, ExistingPassword, NewPassword, ConfirmPassword): # Is the form empty? Return no error... if not ExistingPassword and not NewPassword and not ConfirmPassword: return "" # Is the form partially filled? elif not ExistingPassword: return "Error: Missing existing password." elif not NewPassword: return "Error: Missing new password." elif not ConfirmPassword: return "Error: Missing confirmation password." # Get existing user ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all() if len(ExistingUsers) <= 0: return "Error: User name does not exist." ExistingUser = ExistingUsers[0] # Is the given password the active password? ExistingHash = __GeneratePasswordHash(ExistingPassword) if ExistingUser.UserPassword != ExistingHash: return "Error: Old password is not correct." # Check password lengths if len(NewPassword) <= 5: return "Error: New password is not long enough. Must be at least 6 characters long." if len(NewPassword) > 32: return "Error: New password is too long. May be at most 32 characters long." # Validate against whitelist to make sure these are valid characters if h.string_check_whitelist(NewPassword, h.string_whitelist_password) == False: return "Error: New password contains invalid characters." # Confirm the passwords are the same... if NewPassword != ConfirmPassword: return "Error: New passwords do not match." # All good to go - commit password changes ExistingUser.UserPassword = __GeneratePasswordHash(NewPassword) Session.commit() # Done! return "Success: Password has changed!"
def SetUserPassword(UserName, ExistingPassword, NewPassword, ConfirmPassword): # Is the form empty? Return no error... if not ExistingPassword and not NewPassword and not ConfirmPassword: return "" # Is the form partially filled? elif not ExistingPassword: return "Error: Missing existing password." elif not NewPassword: return "Error: Missing new password." elif not ConfirmPassword: return "Error: Missing confirmation password." # Get existing user ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all() if len(ExistingUsers) <= 0: return "Error: User name does not exist." ExistingUser = ExistingUsers[0] # Is the given password the active password? ExistingHash = __GeneratePasswordHash(ExistingPassword) if ExistingUser.UserPassword != ExistingHash: return "Error: Old password is not correct." # Check password lengths if len(NewPassword) <= 5: return "Error: New password is not long enough. Must be at least 6 characters long." if len(NewPassword) > 32: return "Error: New password is too long. May be at most 32 characters long." # Validate against whitelist to make sure these are valid characters if h.string_check_whitelist(NewPassword, h.string_whitelist_password) == False: return "Error: New password contains invalid characters." # Confirm the passwords are the same... if NewPassword != ConfirmPassword: return "Error: New passwords do not match." # All good to go - commit password changes ExistingUser.UserPassword = __GeneratePasswordHash(NewPassword) Session.commit() # Done! return "Success: Password has changed!"
def UserAddAchievement(UserID, AchievementID): # Does the current user have this achivement? UserAchievements = Achievements.AchievementsQueryUserID(UserID) for achievement in UserAchievements: if achievement.AchievementID == AchievementID: return # New achievement for this user! NewAchievement = UserAchievementsTable() NewAchievement.UserID = UserID NewAchievement.AchievementID = AchievementID # Commit to DB Session.add(NewAchievement) Session.commit() # Recompute the latest user points and force it onto this user UpdateUserPoints(UserID)
def UserAddAchievement(UserID, AchievementID): # Does the current user have this achivement? UserAchievements = Achievements.AchievementsQueryUserID(UserID) for achievement in UserAchievements: if achievement.AchievementID == AchievementID: return # New achievement for this user! NewAchievement = UserAchievementsTable() NewAchievement.UserID = UserID NewAchievement.AchievementID = AchievementID # Commit to DB Session.add(NewAchievement) Session.commit() # Recompute the latest user points and force it onto this user UpdateUserPoints(UserID)
def UserReset(UserName): # Get existing user ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all() if len(ExistingUsers) <= 0: return "Error: User name does not exist." # Register this new user into the database ExistingUser = ExistingUsers[0] # Randomize an 8-character string NewPassword = "" for i in range(8): NewPassword += random.choice(h.string_whitelist) # Send an email with the password try: # Form a message message = """\ From: [email protected] To: %s Subject: Password Change New Password: \"%s\" (Change this as soon as possible!) Visit www.corecodex.com to learn more. """ % (ExistingUser.UserEMail, NewPassword) # Send mail s = smtplib.SMTP() s.connect() s.sendmail("*****@*****.**", ExistingUser.UserEMail, message) s.quit() except: return "Error: Unable to send email. Password was not reset." # Hash password ExistingUser.UserPassword = __GeneratePasswordHash(NewPassword) # Save changes to DB; done! Session.commit() return ""
def UserRegister(UserName, UserEMail, UserPassword, UserPasswordConfirm): # Check for cookies - are we already logged in? if session.get("UserName"): return "redirect" # Did we get the entire form correctly? if not UserName or not UserEMail or not UserPassword or not UserPasswordConfirm: return "Error: Missing fields. Please fill out all fields completely." # Check username lengths if len(UserName) <= 5: return "Error: User name is not long enough. Must be at least 6 characters long." if len(UserName) > 32: return "Error: User name is too long. May be at most 32 characters long." # Check email lengths if len(UserEMail) <= 5: return "Error: User e-mail is not long enough. Must be at least 6 characters long." if len(UserEMail) > 32: return "Error: User e-mail is too long. May be at most 32 characters long." # Check password lengths if len(UserPassword) <= 5: return "Error: User password is not long enough. Must be at least 6 characters long." if len(UserPassword) > 32: return "Error: User password is too long. May be at most 32 characters long." # Validate against whitelist to make sure these are valid characters if h.string_check_whitelist(UserName, h.string_whitelist) == False: return "Error: User name contains invalid characters." if h.string_check_whitelist(UserEMail, h.string_whitelist) == False: return "Error: User e-mail contains invalid characters." if h.string_check_whitelist(UserPassword, h.string_whitelist_password) == False: return "Error: Password contains invalid characters." # Confirm the passwords are the same... if UserPassword != UserPasswordConfirm: return "Error: Passwords do not match." # Finally, make sure no other users with the same name exist.. ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all() if len(ExistingUsers) > 0: return "Error: User name already exists! Please select a new user name." # Register this new user into the database NewUser = UsersTable() # Note that the user ID will auto-increment NewUser.UserName = UserName NewUser.UserEMail = UserEMail NewUser.UserPoints = 0 NewUser.UserPassword = __GeneratePasswordHash(UserPassword) NewUser.LogInCount = 0 NewUser.LastLogin = datetime.datetime.now() NewUser.IsAdmin = False NewUser.IconID = 0 # Commit to DB Session.add(NewUser) Session.commit() # Special achivement earned by people who register now - alpha testers UserAddAchievement(NewUser.UserID, 0) # All done return ""
def UserRegister(UserName, UserEMail, UserPassword, UserPasswordConfirm): # Check for cookies - are we already logged in? if session.get("UserName"): return "redirect" # Did we get the entire form correctly? if not UserName or not UserEMail or not UserPassword or not UserPasswordConfirm: return "Error: Missing fields. Please fill out all fields completely." # Check username lengths if len(UserName) <= 5: return "Error: User name is not long enough. Must be at least 6 characters long." if len(UserName) > 32: return "Error: User name is too long. May be at most 32 characters long." # Check email lengths if len(UserEMail) <= 5: return "Error: User e-mail is not long enough. Must be at least 6 characters long." if len(UserEMail) > 32: return "Error: User e-mail is too long. May be at most 32 characters long." # Check password lengths if len(UserPassword) <= 5: return "Error: User password is not long enough. Must be at least 6 characters long." if len(UserPassword) > 32: return "Error: User password is too long. May be at most 32 characters long." # Validate against whitelist to make sure these are valid characters if h.string_check_whitelist(UserName, h.string_whitelist) == False: return "Error: User name contains invalid characters." if h.string_check_whitelist(UserEMail, h.string_whitelist) == False: return "Error: User e-mail contains invalid characters." if h.string_check_whitelist(UserPassword, h.string_whitelist_password) == False: return "Error: Password contains invalid characters." # Confirm the passwords are the same... if UserPassword != UserPasswordConfirm: return "Error: Passwords do not match." # Finally, make sure no other users with the same name exist.. ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all() if len(ExistingUsers) > 0: return "Error: User name already exists! Please select a new user name." # Register this new user into the database NewUser = UsersTable() # Note that the user ID will auto-increment NewUser.UserName = UserName NewUser.UserEMail = UserEMail NewUser.UserPoints = 0 NewUser.UserPassword = __GeneratePasswordHash(UserPassword) NewUser.LogInCount = 0 NewUser.LastLogin = datetime.datetime.now() NewUser.IsAdmin = False NewUser.IconID = 0 # Commit to DB Session.add(NewUser) Session.commit() # Special achivement earned by people who register now - alpha testers UserAddAchievement(NewUser.UserID, 0) # All done return ""
def SolveChallenge(UserID, ChallengeID, ChallengeSourceCode, ChallengeLanguage): # Create a new solutions Solution = UserSolutionsTable() Solution.UserID = UserID Solution.ChallengeID = ChallengeID Solution.ResultCode = 0 Solution.ResultString = "Internal CoreJudge Failure." Solution.SampleResultString = "" # Leave empty Solution.MemoryUsage = 0 Solution.RuntimeUsage = 0 Solution.SourceCode = ChallengeSourceCode Solution.SourceLanguage = ChallengeLanguage Solution.SubmitDateTime = datetime.datetime.now() # Failure flag Failed = False # Load the challenge information Challenge = Challenges.ChallengeQueryID(ChallengeID) if not Challenge: Failed = True # Is this a supported language? # Formally accepted strings: Python, GCC C, C++, Java if not Failed: if ChallengeLanguage != "Python" and ChallengeLanguage != "GCC C" and ChallengeLanguage != "C++" and ChallengeLanguage != "Java": Failed = True # Check source code for viability to execute... if not Failed: SourceSafeErr = __IsSourceSafe(ChallengeSourceCode, ChallengeLanguage) if len(SourceSafeErr) > 0: Failed = True Solution.ResultCode = 8 # Attempt to execute the code against both the challenge test cases and the sample inputs if not Failed: # Execute the sample code Attempt = __ExecuteSource(Challenge.SampleCode, Challenge.SampleInput, Challenge.SampleOutput, ChallengeSourceCode, ChallengeLanguage, True) Solution.ResultString = Attempt.ResultString Solution.SampleResultString = Attempt.ResultString # Execute the official test case # Note that we don't post the result string, we just ignore the output # since we do the comparison of correct I/O within the exec source function Attempt = __ExecuteSource(Challenge.TestCode, Challenge.TestInput, Challenge.TestOutput, ChallengeSourceCode, ChallengeLanguage) Solution.MemoryUsage = Attempt.MemoryUsage Solution.RuntimeUsage = Attempt.RuntimeUsage Solution.ResultCode = Attempt.ResultCode Solution.ResultString = Attempt.ResultString # Commit to DB Session.add(Solution) Session.commit() # Force update the user's score if this solution is valid if Solution.ResultCode == 1: Users.UpdateUserPoints(UserID) # Return this new result ID (So the browser redirects) return Solution.SolutionID
def SolveChallenge(UserID, ChallengeID, ChallengeSourceCode, ChallengeLanguage): # Create a new solutions Solution = UserSolutionsTable() Solution.UserID = UserID Solution.ChallengeID = ChallengeID Solution.ResultCode = 0 Solution.ResultString = "Internal CoreJudge Failure." Solution.SampleResultString = "" # Leave empty Solution.MemoryUsage = 0 Solution.RuntimeUsage = 0 Solution.SourceCode = ChallengeSourceCode Solution.SourceLanguage = ChallengeLanguage Solution.SubmitDateTime = datetime.datetime.now() # Failure flag Failed = False # Load the challenge information Challenge = Challenges.ChallengeQueryID(ChallengeID) if not Challenge: Failed = True # Is this a supported language? # Formally accepted strings: Python, GCC C, C++, Java if not Failed: if ChallengeLanguage != "Python" and ChallengeLanguage != "GCC C" and ChallengeLanguage != "C++" and ChallengeLanguage != "Java": Failed = True # Check source code for viability to execute... if not Failed: SourceSafeErr = __IsSourceSafe(ChallengeSourceCode, ChallengeLanguage) if len(SourceSafeErr) > 0: Failed = True Solution.ResultCode = 8 # Attempt to execute the code against both the challenge test cases and the sample inputs if not Failed: # Execute the sample code Attempt = __ExecuteSource(Challenge.SampleCode, Challenge.SampleInput, Challenge.SampleOutput, ChallengeSourceCode, ChallengeLanguage, True) Solution.ResultString = Attempt.ResultString Solution.SampleResultString = Attempt.ResultString # Execute the official test case # Note that we don't post the result string, we just ignore the output # since we do the comparison of correct I/O within the exec source function Attempt = __ExecuteSource(Challenge.TestCode, Challenge.TestInput, Challenge.TestOutput, ChallengeSourceCode, ChallengeLanguage) Solution.MemoryUsage = Attempt.MemoryUsage Solution.RuntimeUsage = Attempt.RuntimeUsage Solution.ResultCode = Attempt.ResultCode Solution.ResultString = Attempt.ResultString # Commit to DB Session.add(Solution) Session.commit() # Force update the user's score if this solution is valid if Solution.ResultCode == 1: Users.UpdateUserPoints(UserID) # Return this new result ID (So the browser redirects) return Solution.SolutionID