def dash(): if not request.cookies.get( 'userid' ): # Repeated for every route, checks if the user is signed / has a userid in the coookies return redirect( url_for('index', msg="Please sign in to see your dashboard") ) # Redirects them if it doesn't exist userData = getUserData(request.cookies.get( "userid")) # Gets dictionary of the user's usertable data groupData = getUserGroups( request.cookies.get("userid") ) # Get all the user's groups in order to show them in the dropdown files = file_query( {"archived": False}) # Retrieve all user's files in order to show in file list unread = getUnreadComments( files, request.cookies.get("userid") ) # Gets any unread comments, to display in the notifications pane return render_template("dashboard.html", user=userData, groups=groupData, files=files, unreadComments=unread)
def newFilePage(): if not request.cookies.get("userid"): return redirect( url_for( 'index', msg="You are not signed in, please sign in to see this page")) userGroups = getUserGroups(request.cookies.get("userid")) userData = getUserData(request.cookies.get("userid")) return render_template("newfile.html", userGroups=userGroups, user=userData)
def getGroups(): """ Returns the groups that the user is a part of """ isBrowser = 'python-requests' not in request.headers.get('User-Agent') if request.cookies.get("userid"): userid = request.cookies.get('userid') try: # Query all groups that the user belongs to in psql groups = getUserGroups(userid) rs = [] print('\n\nGetting groups for user: '******' query...') for g in range(len(groups)): group = groups[g] print('Group', str(g + 1) + ':', group) rs.append(group) resp = make_response( json.dumps({ "code": 200, "msg": "Here are the groups you are a member of", "rows": rs })) resp.set_cookie("userid", userid) return resp except Exception as e: print(print_exc()) if isBrowser: return redirect( url_for('errors.error', code=500, msg=print_exc())) else: return json.dumps({ "code": 500, "msg": "Something went wrong when querying the groups." }), 500 else: if isBrowser: return redirect(url_for('errors.error', code=403, msg=print_exc())) else: return json.dumps({ "code": 403, "msg": "You must be signed in to do this", "exc": print_exc() }), 403
def file(id: str): if not request.cookies.get("userid"): return redirect( url_for( 'index', msg="You are not signed in, please sign in to see this page.")) fileData = file_query( {"fileid": id} ) # Gets list of files associated with file id provided in url, although should only be one if not fileData: # Checks if any file is returned from the file query return redirect( url_for('dash', msg="Sorry, you do not have access to this file")) else: fileData = fileData[ 0] # Should only be one, so fetches the first index userData = getUserData(request.cookies.get("userid")) userGroups = getUserGroups( userData["userid"] ) # Gets groups in order for admins to give other group's file access isLeader = leaderCheck(fileData["groups"], userData["userid"]) or userData["admin"] readUnreadComments( id, userData["userid"] ) # Marks any comment in the file that isn't read as read fileComments = getComments( id ) # Fetches the files comments, with all of them read by current user return render_template("file.html", file=fileData, isLeader=isLeader, comments=fileComments, userGroups=userGroups, archive=False)
def archivedFile(id: str): if not request.cookies.get("userid"): return redirect( url_for( 'index', msg="You are not signed in, please sign in to see this page.")) file = file_query({"fileid": id, "archived": True}) if not file: return redirect( url_for('dash', msg="Sorry, you do not have access to this file")) userGroups = getUserGroups(request.cookies.get("userid")) fileComments = getComments( id, True ) # Fetches the files comments, with all of them read by current user return render_template("file.html", file=file[0], isLeader=True, userGroups=userGroups, comments=fileComments, archive=True)
def getUsersInGroups(): """ Gets all the users that a group with the given groupid or groupname contain """ isBrowser = 'python-requests' not in request.headers.get('User-Agent') data = request.form if isBrowser else json.loads(request.data) if request.cookies.get("userid"): userid = request.cookies.get('userid') try: # If groupid doesn't exist in query then get the groupid from the groupname if 'groupid' not in data: data['groupid'] = getGroupDataFromName( data['groupname']).serialise()['groupid'] groupid = data['groupid'] groups = getUserGroups(userid) groupids = [group['groupid'] for group in groups] if groupid not in groupids: if isBrowser: return redirect( url_for('errors.error', code=401, msg=print_exc())) else: return json.dumps({ "code": 401, "msg": "You cannot query a group you are not a member of" }), 401 group_users = getGroupUsers(groupid) rs = [] print('\n\nGetting users in group: ' + groupid + ' for user: '******'userid'] = str(user['userid']) # lastlogin key is datetime object so convert to string user['lastlogin'] = str(user['lastlogin']) print('User', str(u + 1) + ':', user) rs.append(user) resp = make_response( json.dumps({ "code": 200, "msg": "Here are the users in the requested group", "rows": rs })) resp.set_cookie("userid", userid) return resp except Exception as e: print(print_exc()) if isBrowser: return redirect( url_for('errors.error', code=500, msg=print_exc())) else: return json.dumps({ "code": 500, "msg": "Something went wrong when querying the groups." }), 500 else: if isBrowser: return redirect(url_for('errors.error', code=403, msg=print_exc())) else: return json.dumps({ "code": 403, "msg": "You must be signed in to do this", "exc": print_exc() }), 403
def generateReport(groupname=None): """ JSON requires either groupid or email of a user and userid inside cookie. - If only email is specified then a report is generated on user. Querying - If only groupid is specified then a report is generated on user (also now accepts groupname) - If both then a report is generated on the user's activity within said group """ isBrowser = "email" in request.form or "groupid" in request.form data = request.form if isBrowser else json.loads(request.data) data = dict(data) cookie_userid = request.cookies.get('userid') if cookie_userid: try: # First check if user requesting report has the permission to do this. If the user is admin then # skip over this bit if 'groupname' in data: data['groupid'] = str(getGroupDataFromName(data['groupname']).groupid) user_groups = getUserGroups(cookie_userid) print("Generating a report for " + cookie_userid + " subject:", data) user_info = getUserData(cookie_userid) permission = True if not user_info['admin']: user_groupleader = next((group for group in user_groups if group['groupleaderid'] == cookie_userid), None) if 'groupid' in data: if user_groupleader is None: permission = False else: data['groupid'] = None if 'email' in data: if next((user for user in getGroupUsers(user_groupleader['groupid']) if getUserData(user['userid'])['email'] == data['email']), None) is None: permission = False else: data['email'] = None if not permission: if isBrowser: return redirect(url_for('dash', msg="Sorry you are not permitted to complete this action")) else: return json.dumps({ "code": 401, "msg": "You don't have permission to complete this action!" }), 401 if isBrowser: return send_file( generatePdfFromHtml(generateReportHTML(data.get("groupid"), data.get("email"))), attachment_filename=groupname + ".pdf" ) else: return json.dumps({ "code": 200, "msg": "Report has been created!", "report": generateReportHTML(data.get("groupid"), data.get("email")) }) except Exception as e: print(print_exc()) if isBrowser: return redirect(url_for("group", id=data["groupid"], msg="Something went wrong while generating your report")) else: return json.dumps({ "code": 500, "msg": "Something went wrong when generating report." }), 500 else: if isBrowser: return redirect(url_for("index", msg="You must be signed in to do this")) else: return json.dumps({ "code": 403, "msg": "You must be signed in to do this", }), 403
def generateReportHTML(groupid: str, email: str) -> str: """ Generate the report file in memory and returns the markdown string in html using markdown package - groupid: if not none then create a group report - email: if not none then create a user report - returns: if both params are not none then report on user inside group, otherwise as above """ # Create the StringIO object to store the report file in memory report = io.StringIO() title = "# Report on " + (("group \"" + getGroupData(groupid)['groupname'] + "\"") if groupid is not None and email is None else ("user \"" + getUserDataFromEmail(email)['username'] + "\"") + (" in group \"" + getGroupData(groupid)['groupname'] + "\"" if email is not None and groupid is not None else "")) report.write(title + '\n\n---\n\n') user_list_prefix = "" users_in_group = [] if groupid is not None and email is None: users_in_group = getGroupUsers(groupid) users_heading = "## Users in group\n\n" user_list_prefix = "1. " tabulations = "\t" report.write(users_heading) if email is not None: users_in_group.append(getUserDataFromEmail(email)) user_list_prefix = "## " tabulations = "" # Write user's info to report for user in users_in_group: user_info = user_list_prefix + "Info on user \"" + user['username'] + "\"\n\n" + tabulations + "- User ID: " + str(user['userid']) + "\n" + tabulations + "- Email: " + user['email'] + "\n" + tabulations + "- Last login: "******"\n" + tabulations + "- Admin: " + ("Yes" if user['admin'] else "No") + "\n\n" report.write(user_info) # Write group details if groupid or groupid and email is not None if groupid is not None or (groupid is not None and email is not None): group = getGroupData(groupid) group_info = "## Info on group \"" + group['groupname'] + "\"\n\n- Group ID: " + groupid + "\n- Groupleader: " + getUserData(group['groupleader']['userid'])['username'] + " (ID: " + str(getUserData(group['groupleader']['userid'])['userid']) + ")\n\n" report.write(group_info) # Display all the files belonging to the group if groupid is not none if groupid is not None and email is None: group = getGroupData(groupid) report.write("## Files belonging to \"" + group['groupname'] + "\"\n\n") files_in_group = file_query({'groupid': groupid}) if len(files_in_group) > 0: for file in files_in_group: file_info = "1. Filename: \"" + file['filename'] + "\"\n\t- File ID: " + file['fileid'] + "\n\t- Extension: " + file['extension'] + "\n\t- Comments:\n" report.write(file_info) # Then display a list of all comments relating to the file comments = getComments(file['fileid']) if len(comments) > 0: for comment in comments: comment_info = "\t\t1. \"" + comment['comment'] + "\"\n\t\t\t- By: " + comment['user']['username'] + "\n\t\t\t- Written on: " + str(comment['date']) + "\n\t\t\t- Read: " + ("Yes" if comment['read'] else "No") + "\n" report.write(comment_info) else: report.write("\t\t- No comments for this file\n") report.write("\t- Versions:\n") # Display version info versions = file['versions'] version_info = "" if len(versions) > 0: for version in versions.keys(): version = versions[version] version_info += "\t\t1. \"" + version['title'] + "\" (Hash: " + version['versionhash'] + ")\n\t\t\t- Uploaded on: " + version['uploaded'] + "\n\t\t\t- Author: " + str(version['author']['username']) + "\n" report.write(version_info) else: report.write("\t\t- No versions found\n") report.write("\n") else: report.write("No files for this group\n\n") # Display all file versions that the user with email has created. If groupid is not none then it will only display file versions from that group if email is not None: user = getUserDataFromEmail(email) group = getGroupData(groupid) if groupid is not None else None report.write("## File versions belonging to \"" + user['username'] + "\"" + ((" in group \"" + group['groupname'] + "\"\n\n") if group is not None else "\n\n")) groups_to_find_versions = [] if groupid is None: # Find all the groups that the user is in groups_to_find_versions = [getGroupData(group['groupid']) for group in getUserGroups(user['userid'])] else: # Add only the group that is specified by groupid groups_to_find_versions = [group] versions_user_has_authored = {} # Find all versions inside the group['files'] that the user in question has authored for group in groups_to_find_versions: for file in group['files']: # Create a more succint file dictionary used later small_file = {} small_file['filename'] = file['filename'] small_file['versions'] = [] found_something = False for version in file['versions'].keys(): version = file['versions'][version] if version['author']['email'] == email: found_something = True print('found version', version) small_file['versions'].append(version) # Only add small file if it contains versions related to the user if found_something: versions_user_has_authored[file['fileid']] = small_file # Display version data found if len(versions_user_has_authored) > 0: for fileid in versions_user_has_authored.keys(): file = versions_user_has_authored[fileid] version_info = "1. For \"" + file['filename'] + "\" (File ID: " + fileid + ") they created:\n" for version in file['versions']: version_info += "\t2. \"" + version['title'] + "\"\n\t\t- Hash: " + version['versionhash'] + "\n\t\t- Version ID: " + version['versionid'] + "\n\t\t- Uploaded: " + str(version['uploaded']) + "\n\t\t- Author: " + version['author']['username'] + "\n" report.write(version_info) report.write("\n") else: report.write("User has authored no versions" + (" inside this group\n\n" if groupid is not None else "\n\n")) return markdown.markdown(report.getvalue()).replace("\n", "")