예제 #1
0
파일: Users.py 프로젝트: nint22/CoreCodex
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"
예제 #2
0
파일: Users.py 프로젝트: nint22/CoreCodex
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!"
예제 #3
0
파일: Users.py 프로젝트: nint22/CoreCodex
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
예제 #4
0
파일: Users.py 프로젝트: nint22/CoreCodex
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!"
예제 #5
0
파일: Users.py 프로젝트: nint22/CoreCodex
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"
예제 #6
0
파일: Users.py 프로젝트: nint22/CoreCodex
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
예제 #7
0
파일: Users.py 프로젝트: nint22/CoreCodex
def GetUsersByScores():
	
	# Get existing users based on scores
	ExistingUsers = Session.query(UsersTable).order_by(sa.desc(UsersTable.UserPoints)).all()
	
	# Only return the top 10
	return ExistingUsers[0:10]
예제 #8
0
파일: Users.py 프로젝트: nint22/CoreCodex
def GetUsersByChallenges():
	
	# Get user list
	ExistingUsers = Session.query(UsersTable).all()
	
	# Create challenge count
	UserChallengesComplete = []
	
	# For each user, find out how many challenges they have complete...
	for User in ExistingUsers:
		
		# Total number of challenges complete
		ChallengesComplete = 0
		
		# For each challenge, save solved count
		for Challenge in Challenges.QueryAllChallenges():
			if Solutions.HasUserSolvedChallenge(User.UserID, Challenge.ChallengeID):
				ChallengesComplete += 1
		
		# Push back into the user challenges completion list
		UserChallengesComplete.append([User, ChallengesComplete])
	
	# Sort the user challenges list
	UserChallengesComplete.sort(key=lambda x: x[1])
	UserChallengesComplete.reverse()
	
	# Return the top 10 users
	return UserChallengesComplete[0:10]
예제 #9
0
파일: Users.py 프로젝트: nint22/CoreCodex
def GetUsersByScores():

    # Get existing users based on scores
    ExistingUsers = Session.query(UsersTable).order_by(sa.desc(UsersTable.UserPoints)).all()

    # Only return the top 10
    return ExistingUsers[0:10]
예제 #10
0
파일: Users.py 프로젝트: nint22/CoreCodex
def GetUsersByChallenges():

    # Get user list
    ExistingUsers = Session.query(UsersTable).all()

    # Create challenge count
    UserChallengesComplete = []

    # For each user, find out how many challenges they have complete...
    for User in ExistingUsers:

        # Total number of challenges complete
        ChallengesComplete = 0

        # For each challenge, save solved count
        for Challenge in Challenges.QueryAllChallenges():
            if Solutions.HasUserSolvedChallenge(User.UserID, Challenge.ChallengeID):
                ChallengesComplete += 1

                # Push back into the user challenges completion list
        UserChallengesComplete.append([User, ChallengesComplete])

        # Sort the user challenges list
    UserChallengesComplete.sort(key=lambda x: x[1])
    UserChallengesComplete.reverse()

    # Return the top 10 users
    return UserChallengesComplete[0:10]
예제 #11
0
def ChallengeQueryID(ChallengeID):
	
	# DEBUGGING CODE: FORCE A CLEAR-CACHE OF THE CHALLENGE BUFFER
	__ChallengeBufferCache = {}
	
	# Is this challenge in our cache?
	if int(ChallengeID) in __ChallengeBufferCache:
		return __ChallengeBufferCache[int(ChallengeID)]
	
	# Else, load from database and place back into the cache
	else:
		
		# Does this challenge exist in the db?
		ExistingChallenges = Session.query(ChallengeDescriptionsTable).filter(ChallengeDescriptionsTable.ChallengeID == ChallengeID).all()
		if len(ExistingChallenges) <= 0:
			return None
		
		# Open and prase the file (or at least attempt)
		Challenge = __ParseChallengeFile(ExistingChallenges[0].ChallengeFileLocation)
		
		# Set target challenge ID and save to the cache
		Challenge.ChallengeID = ChallengeID
		Challenge.ChallengeGroupID = ExistingChallenges[0].ChallengeGroupID
		
		__ChallengeBufferCache[int(ChallengeID)] = Challenge
		
		# Return loaded challenge
		return Challenge
예제 #12
0
def GetAttemptsCount(ChallengeID):
	
	# Query the solutions database for only this challenge and only non-zero results
	SolutionsList = Session.query(UserSolutionsTable).filter(sa.and_(UserSolutionsTable.ResultCode != 0, UserSolutionsTable.ChallengeID == ChallengeID)).all()
	
	# Return number solutions
	return len(SolutionsList)
예제 #13
0
파일: Users.py 프로젝트: nint22/CoreCodex
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 ""
예제 #14
0
파일: Users.py 프로젝트: nint22/CoreCodex
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 ""
예제 #15
0
def HasUserAttemptedChallenge(UserID, ChallengeID):
	
	# Query the list of all attempts by this user for this challenge
	SolutionsList = Session.query(UserSolutionsTable).filter(sa.and_(UserSolutionsTable.UserID == UserID, UserSolutionsTable.ChallengeID == ChallengeID)).all()
	if len(SolutionsList) > 0:
		return True
	else:
		return False
예제 #16
0
파일: Users.py 프로젝트: nint22/CoreCodex
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 ""
예제 #17
0
파일: Users.py 프로젝트: nint22/CoreCodex
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!"
예제 #18
0
파일: Users.py 프로젝트: nint22/CoreCodex
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!"
예제 #19
0
def SolutionsAcceptedUserID(UserID):
	
	# Return nothing if we have an invalid user ID or Challenge ID
	if not UserID:
		return []
	
	# Does this challenge exist in the db?
	AcceptedSolutionsList = Session.query(UserSolutionsTable).filter(sa.and_(UserSolutionsTable.UserID == UserID, UserSolutionsTable.ResultCode == 1)).all()
	return AcceptedSolutionsList
예제 #20
0
def SolutionsUserIDChallengeID(UserID, ChallengeID):
	
	# Return nothing if we have an invalid user ID or Challenge ID
	if not UserID or not ChallengeID:
		return []
	
	# Does this challenge exist in the db?
	SolutionsList = Session.query(UserSolutionsTable).filter(sa.and_(UserSolutionsTable.UserID == UserID, UserSolutionsTable.ChallengeID == ChallengeID)).all()
	return SolutionsList
예제 #21
0
def GetAttemptsCount(ChallengeID):

    # Query the solutions database for only this challenge and only non-zero results
    SolutionsList = Session.query(UserSolutionsTable).filter(
        sa.and_(UserSolutionsTable.ResultCode != 0,
                UserSolutionsTable.ChallengeID == ChallengeID)).all()

    # Return number solutions
    return len(SolutionsList)
예제 #22
0
파일: Users.py 프로젝트: nint22/CoreCodex
def UserQueryName(UserName):

    # Does this username exist in the db?
    ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all()
    if len(ExistingUsers) <= 0:
        return None

        # Pull up this user's information
    return ExistingUsers[0]
예제 #23
0
파일: Users.py 프로젝트: nint22/CoreCodex
def UserQueryName(UserName):
	
	# Does this username exist in the db?
	ExistingUsers = Session.query(UsersTable).filter(UsersTable.UserName == UserName).all()
	if len(ExistingUsers) <= 0:
		return None
	
	# Pull up this user's information
	return ExistingUsers[0]
예제 #24
0
def ChallengesQueryGroupID(ChallengeGroupID):
	
	# Query all challenges, via filter, of the challenge descriptions
	Challenges = Session.query(ChallengeDescriptionsTable).filter(ChallengeDescriptionsTable.ChallengeGroupID == ChallengeGroupID).all()
	
	# Start challenge list
	ChallengeIDList = []
	for Challenge in Challenges:
		ChallengeIDList.append(Challenge.ChallengeID)
	return ChallengeIDList
예제 #25
0
def HasUserSolvedChallenge(UserID, ChallengeID):
	
	# Query the list of all attempts by this user for this challenge
	SolutionsList = Session.query(UserSolutionsTable).filter(sa.and_(UserSolutionsTable.UserID == UserID, UserSolutionsTable.ChallengeID == ChallengeID)).all()
	for Solution in SolutionsList:
		if Solution.ResultCode == 1:
			return True
	
	# All done; nothing found
	return False
예제 #26
0
파일: Users.py 프로젝트: nint22/CoreCodex
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)
예제 #27
0
def SolutionsUserID(UserID):

    # Return nothing if we have an invalid user ID or Challenge ID
    if not UserID:
        return []

    # Does this challenge exist in the db?
    SolutionsList = Session.query(UserSolutionsTable).filter(
        UserSolutionsTable.UserID == UserID).all()
    return SolutionsList
예제 #28
0
def HasUserAttemptedChallenge(UserID, ChallengeID):

    # Query the list of all attempts by this user for this challenge
    SolutionsList = Session.query(UserSolutionsTable).filter(
        sa.and_(UserSolutionsTable.UserID == UserID,
                UserSolutionsTable.ChallengeID == ChallengeID)).all()
    if len(SolutionsList) > 0:
        return True
    else:
        return False
예제 #29
0
파일: Users.py 프로젝트: nint22/CoreCodex
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)
예제 #30
0
파일: Users.py 프로젝트: nint22/CoreCodex
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 ""
예제 #31
0
def SolutionsAcceptedUserID(UserID):

    # Return nothing if we have an invalid user ID or Challenge ID
    if not UserID:
        return []

    # Does this challenge exist in the db?
    AcceptedSolutionsList = Session.query(UserSolutionsTable).filter(
        sa.and_(UserSolutionsTable.UserID == UserID,
                UserSolutionsTable.ResultCode == 1)).all()
    return AcceptedSolutionsList
예제 #32
0
def HasUserSolvedChallenge(UserID, ChallengeID):

    # Query the list of all attempts by this user for this challenge
    SolutionsList = Session.query(UserSolutionsTable).filter(
        sa.and_(UserSolutionsTable.UserID == UserID,
                UserSolutionsTable.ChallengeID == ChallengeID)).all()
    for Solution in SolutionsList:
        if Solution.ResultCode == 1:
            return True

    # All done; nothing found
    return False
예제 #33
0
def GetUserAttemptsCount(ChallengeID):
	
	# Query the solutions database for only this challenge and only non-zero results
	SolutionsList = Session.query(UserSolutionsTable).filter(sa.and_(UserSolutionsTable.ResultCode != 0, UserSolutionsTable.ChallengeID == ChallengeID)).all()

	# Go through the list and count the unique number of users
	UsersList = {}
	for Solution in SolutionsList:
		if not Solution.UserID in UsersList:
			UsersList[Solution.UserID] = 1
	
	# We now have a list of users that have at least attempted the given challenge, now just return the user count
	return len(UsersList)
예제 #34
0
파일: Solver.py 프로젝트: nint22/CoreCodex
def QueryResultID(UserID, SolutionID):
	
	# Pull up all solutions with this ID
	Solutions = Session.query(UserSolutionsTable).filter(UserSolutionsTable.SolutionID == SolutionID).all()
	if len(Solutions) <= 0:
		return None
	
	# Check for permissions (we don't want to make all solutions public)
	elif Solutions[0].UserID != UserID:
		return None
	
	# All good, return solution information
	else:
		return Solutions[0]
예제 #35
0
def ChallengesQuery():
	
	# Start the challenges list
	ChallengeGroups = Session.query(ChallengeGroupsTable).all()
	
	# Start challenge list
	ChallengesList = []
	for ChallengeGroup in ChallengeGroups:
		
		# Add to challenge list
		ChallengesList.append(ChallengesGroupQueryGroupID(ChallengeGroup.ChallengeGroupID))
	
	# Done creating the list, return
	return ChallengesList
예제 #36
0
def GetUserAttemptsCount(ChallengeID):

    # Query the solutions database for only this challenge and only non-zero results
    SolutionsList = Session.query(UserSolutionsTable).filter(
        sa.and_(UserSolutionsTable.ResultCode != 0,
                UserSolutionsTable.ChallengeID == ChallengeID)).all()

    # Go through the list and count the unique number of users
    UsersList = {}
    for Solution in SolutionsList:
        if not Solution.UserID in UsersList:
            UsersList[Solution.UserID] = 1

    # We now have a list of users that have at least attempted the given challenge, now just return the user count
    return len(UsersList)
예제 #37
0
파일: Solver.py 프로젝트: nint22/CoreCodex
def QueryResultID(UserID, SolutionID):

    # Pull up all solutions with this ID
    Solutions = Session.query(UserSolutionsTable).filter(
        UserSolutionsTable.SolutionID == SolutionID).all()
    if len(Solutions) <= 0:
        return None

    # Check for permissions (we don't want to make all solutions public)
    elif Solutions[0].UserID != UserID:
        return None

    # All good, return solution information
    else:
        return Solutions[0]
예제 #38
0
def AchievementsQueryUserID(UserID):
	
	# Note that we have to do a join between these two tables
	# The user's achivements are listed in UserAchivementsTable but their
	# descriptions are in AchivementsTable
	# SELECT *  
	# FROM   Achievements, UserAchievements 
	# WHERE  Achievements.AchievementID = UserAchievements.AchievementID and UserAchievements.UserID = 4
	JoinedTable = Session.query(AchievementsTable, UserAchievementsTable).filter(and_(AchievementsTable.AchievementID == UserAchievementsTable.AchievementID, UserAchievementsTable.UserID == UserID)).all()
	
	# Generate achievements table
	Achievements = []
	for Item in JoinedTable:
		Achievements.append(Item[0])
	return Achievements
예제 #39
0
def ChallengesGroupQueryGroupID(ChallengeGroupID, QueryStats = True):
	
	# Query all challenges group
	ChallengeGroups = Session.query(ChallengeGroupsTable).filter(ChallengeGroupsTable.ChallengeGroupID == ChallengeGroupID).all()
	if len(ChallengeGroups) <= 0:
		return None
	
	# Find the challenge
	ChallengeGroup = ChallengeGroups[0]
	
	# Only compute meta if required
	if QueryStats:
		
		# Add some new members that are associated with this user's specific data
		ChallengeGroup.TotalPoints = 0
		ChallengeGroup.AverageDifficulty = 0
		ChallengeGroup.CompletedChallenges = 0
		ChallengeGroup.ChallengeCount = 0
		
		# For each challenge in this group...
		ChallengesGroup = ChallengesQueryGroupID(ChallengeGroupID)
		for ChallengeID in ChallengesGroup:
			
			# Load challenge meta data
			Challenge = ChallengeQueryID(ChallengeID)
			if Challenge:
				ChallengeGroup.TotalPoints += int(Challenge.Points)
				ChallengeGroup.AverageDifficulty += int(Challenge.Difficulty)
				
				# Check completion (is there at least one accepted solution?)
				# Note that we should only count the unique number of solutions
				# So ignore any solutions that share the same id on a sucessfull solution
				if Solutions.HasUserSolvedChallenge(session.get("UserID"), ChallengeID):
					ChallengeGroup.CompletedChallenges += 1
				
		
		# Save the number of challenges
		ChallengeGroup.ChallengeCount = len(ChallengesGroup)
		if ChallengeGroup.ChallengeCount != 0:
			ChallengeGroup.AverageDifficulty /= ChallengeGroup.ChallengeCount
	
	# Return challenge group meta data
	return ChallengeGroup
예제 #40
0
def AchievementsQueryUserID(UserID):

    # Note that we have to do a join between these two tables
    # The user's achivements are listed in UserAchivementsTable but their
    # descriptions are in AchivementsTable
    # SELECT *
    # FROM   Achievements, UserAchievements
    # WHERE  Achievements.AchievementID = UserAchievements.AchievementID and UserAchievements.UserID = 4
    JoinedTable = Session.query(
        AchievementsTable, UserAchievementsTable).filter(
            and_(
                AchievementsTable.AchievementID ==
                UserAchievementsTable.AchievementID,
                UserAchievementsTable.UserID == UserID)).all()

    # Generate achievements table
    Achievements = []
    for Item in JoinedTable:
        Achievements.append(Item[0])
    return Achievements
예제 #41
0
def GetSolvedCount(ChallengeID, AllowDuplicates):
	
	# Query the solutions database for only this challenge
	SolutionsList = Session.query(UserSolutionsTable).filter(sa.and_(UserSolutionsTable.ResultCode == 1, UserSolutionsTable.ChallengeID == ChallengeID)).all()
	
	# If we are counting the total number of solutions, including duplicates
	if AllowDuplicates:
		return len(SolutionsList)
	
	# If we are only counting the total solved problems (i.e. no duplicate correct answers...)
	else:
		
		# For each solved solution, place the UserID and ChallengeID into a dictionary
		# If the element already exists, ignore it, it is a re-done solution
		SolutionDict = {}
		for Solution in SolutionsList:
			key = str(Solution.UserID) + "_" + str(Solution.ChallengeID)
			SolutionDict[key] = 1
		
		# Return number of keys
		return len(SolutionDict)
예제 #42
0
파일: Users.py 프로젝트: nint22/CoreCodex
def GetUsersByAchievements():

    # Get user list
    ExistingUsers = Session.query(UsersTable).all()

    # Create achievements count
    UserAchievementsCount = []

    # For each user, find out how many achievements they have gotten...
    for User in ExistingUsers:

        # Total number of achievements complete
        AchievementsCount = len(Achievements.AchievementsQueryUserID(User.UserID))

        # Push back into the user challenges completion list
        UserAchievementsCount.append([User, AchievementsCount])

        # Sort the user challenges list
    UserAchievementsCount.sort(key=lambda x: x[1])
    UserAchievementsCount.reverse()

    # Return the top 10 users
    return UserAchievementsCount[0:10]
예제 #43
0
def GetSolvedCount(ChallengeID, AllowDuplicates):

    # Query the solutions database for only this challenge
    SolutionsList = Session.query(UserSolutionsTable).filter(
        sa.and_(UserSolutionsTable.ResultCode == 1,
                UserSolutionsTable.ChallengeID == ChallengeID)).all()

    # If we are counting the total number of solutions, including duplicates
    if AllowDuplicates:
        return len(SolutionsList)

    # If we are only counting the total solved problems (i.e. no duplicate correct answers...)
    else:

        # For each solved solution, place the UserID and ChallengeID into a dictionary
        # If the element already exists, ignore it, it is a re-done solution
        SolutionDict = {}
        for Solution in SolutionsList:
            key = str(Solution.UserID) + "_" + str(Solution.ChallengeID)
            SolutionDict[key] = 1

        # Return number of keys
        return len(SolutionDict)
예제 #44
0
파일: Users.py 프로젝트: nint22/CoreCodex
def GetUsersByAchievements():
	
	# Get user list
	ExistingUsers = Session.query(UsersTable).all()
	
	# Create achievements count
	UserAchievementsCount = []
	
	# For each user, find out how many achievements they have gotten...
	for User in ExistingUsers:
		
		# Total number of achievements complete
		AchievementsCount = len(Achievements.AchievementsQueryUserID(User.UserID))
		
		# Push back into the user challenges completion list
		UserAchievementsCount.append([User, AchievementsCount])
	
	# Sort the user challenges list
	UserAchievementsCount.sort(key=lambda x: x[1])
	UserAchievementsCount.reverse()
	
	# Return the top 10 users
	return UserAchievementsCount[0:10]
예제 #45
0
파일: Users.py 프로젝트: nint22/CoreCodex
def UserGetUserCount():
	
	# Return count
	return len(Session.query(UsersTable).all())
예제 #46
0
def AchievementsQueryAll():

    # Return all achivements
    return Session.query(AchievementsTable).order_by(
        sa.asc(AchievementsTable.AchievementID)).all()
예제 #47
0
파일: Solver.py 프로젝트: nint22/CoreCodex
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
예제 #48
0
파일: Users.py 프로젝트: nint22/CoreCodex
def UserGetUserCount():

    # Return count
    return len(Session.query(UsersTable).all())
예제 #49
0
파일: Solver.py 프로젝트: nint22/CoreCodex
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
예제 #50
0
파일: Users.py 프로젝트: nint22/CoreCodex
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 ""
예제 #51
0
def GetSolutionsChallengeID(ChallengeID):

    # Return all solutions
    return Session.query(UserSolutionsTable).filter(
        UserSolutionsTable.ChallengeID == ChallengeID).all()
예제 #52
0
파일: Users.py 프로젝트: nint22/CoreCodex
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 ""
예제 #53
0
def GetSolutionsChallengeID(ChallengeID):
	
	# Return all solutions
	return Session.query(UserSolutionsTable).filter(UserSolutionsTable.ChallengeID == ChallengeID).all()
예제 #54
0
def init_model(engine):
    Session.configure(bind=engine)
예제 #55
0
def AchievementsQueryAll():
	
	# Return all achivements
	return Session.query(AchievementsTable).order_by(sa.asc(AchievementsTable.AchievementID)).all()
예제 #56
0
def init_model(engine):
	Session.configure(bind=engine)