def change_password(): if check.logged_in(): form = PasswordForm() if form.validate_on_submit(): user = User(session.get("user_id", "")) password = form.data["old_password"] password_hash = user.password if current_app.config['bcrypt'].check_password_hash( password_hash, password): user.update_password( current_app.config['bcrypt'].generate_password_hash( form.data["new_password"]).decode('utf-8')) return render_template( 'change_password.html', form=form, success="Your password has been updated.") else: return render_template('change_password.html', form=form, error="Incorrect password.") else: if request.method == "POST": return render_template( 'change_password.html', form=form, error="Invalid field, please check again.") else: return render_template('change_password.html', form=form) else: flash({ 'text': "You have to sign in to change your password.", 'type': 'is-warning' }) return redirect("/user/login")
def tag_moderate_remove_mod(tag_name): """Form processor for removing existing moderators """ try: tag = Tag(tag_name) except: error_context = { 'error_name': "404 Not Found", 'error_info': "The tag you tried to access does not exist, but you can create this tag." } return render_template('error.html', **error_context) if not check.logged_in(): error_context = { 'error_name': "Forbidden", 'error_info': "You may not access this page without logging in" } return render_template('error.html', **error_context) if not TagModerator.is_mod(session['user_id'], tag.id): error_context = { 'error_name': "Access Denied", 'error_info': "You are not a moderator of this tag" } return render_template('error.html', **error_context) form = TagModForm(csrf_enabled=False) if form.validate_on_submit(): username_to_remove = form.user.data if username_to_remove: try: user = User.get_from_username(username_to_remove) except: flash('User does not exist') return redirect( url_for('tag_pages.tag_moderate', tag_name=tag_name)) if not user: flash('User does not exist') return redirect( url_for('tag_pages.tag_moderate', tag_name=tag_name)) if not TagModerator.is_mod(user.id, tag.id): flash('Specified user is not a mod') return redirect( url_for('tag_pages.tag_moderate', tag_name=tag_name)) if user.id == session['user_id']: flash('You may not delete yourself as a mod') return redirect( url_for('tag_pages.tag_moderate', tag_name=tag_name)) tag.mod_remove_user(user.id) flash('User removed as mod successfully') return redirect( url_for('tag_pages.tag_moderate', tag_name=tag_name)) else: flash('Invalid Input') return redirect( url_for('tag_pages.tag_moderate', tag_name=tag_name)) return redirect(url_for('tag_pages.tag_moderate', tag_name=tag_name))
def tag_moderate_edit_info(tag_name): try: tag = Tag(tag_name) except: error_context = { 'error_name': "404 Not Found", 'error_info': "The tag you tried to access does not exist, but you can create this tag." } return render_template('error.html', **error_context) if not check.logged_in(): error_context = { 'error_name': "Forbidden", 'error_info': "You may not access this page without logging in" } return render_template('error.html', **error_context) if not TagModerator.is_mod(session['user_id'], tag.id): error_context = { 'error_name': "Access Denied", 'error_info': "You are not a moderator of this tag" } return render_template('error.html', **error_context) form = TagEditForm(csrf_enabled=False) if form.validate_on_submit(): tag.description = form.description.data tag.rules = form.rules.data tag.save() flash('Tag info saved') return redirect(url_for('tag_pages.tag_moderate', tag_name=tag_name))
def login(): if check.logged_in(): return redirect("/") form = LoginForm() if form.validate_on_submit(): username = form.data["username"] user = User.get_from_username(username) if user is not None: if user.is_banned is True: flash({ 'text': "You are banned from Accio, you can not sign in.", 'type': "error" }) return redirect("/") password = form.data["password"] password_hash = user.password if current_app.config['bcrypt'].check_password_hash( password_hash, password): session['user_id'] = user.id flash({ 'text': "You have successfully logged in.", 'type': "success" }) return redirect("/") else: return render_template("login.html", form=form, error="Incorrect password.") else: return render_template("login.html", form=form, error="Incorrect username or password.") return render_template("login.html", form=form)
def index(): id = session.get("user_id", "") return render_template("index.html", id=id, loggedin=check.logged_in(), tags=Tag.get_all(), pagination=Post.paginate( int(request.args.get('page') or 1)))
def generate_context(self): return { 'id': self.id, 'user': User(self.user_id).username, 'user_id': self.user_id, 'date': self.date, 'vote': self.current_vote, 'content': self.content_html, 'is_op': check.logged_in() and (self.user_id == session['user_id']) }
def post_submit(): """ This view is for submitting posts. An account is required for submitting posts. Get parameters supply the tag name, e.g. a link from the tag page to post with that tag. Post request receive the form submission """ # Forbid submission of post if user is not logged in if not check.logged_in(): error_context = { 'error_name': "403 Forbidden", 'error_info': "You may not post without an account. Please log in or create an account" } return render_template('error.html', **error_context) # User is logged in, show text submission form else: form = TextPostForm() if form.validate_on_submit(): post = Post() post.user_id = int(session['user_id']) post.date = datetime.now() post.title = form.title.data post.content_type = form.content_type.data post.content = form.content.data post.content_html = md.render(form.content.data) # TODO: Implement external links post.is_external = False post.current_vote = 0 post.is_banned = False post.comment_count = 0 # TODO: Implement tag existance check # This should be done with custom validator after tags are created try: tag = Tag(form.tag.data) print(form.tag.data) post.tag_id = tag.id except NotImplementedError as error: error_context = { 'error_name': "INVALID TAG", 'error_info': "the tag you entered is invalid" } return render_template('error.html', **error_context) post.save() flash('Post created sucessfully') return redirect(url_for('post_pages.post_view', post_id=post.id)) else: return render_template('post_text_submit.html', form=form)
def report_post(is_comment, reported_id): create_report = False if not check.logged_in(): return redirect("/") else: form = ReportForm(request.form) if form.validate_on_submit(): try: #If reported object is a post if is_comment == 0: reported_post = Post(reported_id) if len( Report.get_user_prev_report( session.get("user_id", ""), reported_id)) > 0: return redirect("/post/" + str(reported_id)) else: reported_comment = Comment(reported_id) if len( Report.get_user_prev_report( session.get("user_id", ""), reported_id)) > 0: return redirect("/post/" + str(reported_comment.post_id)) report = Report() report.submitting_user_id = session.get("user_id", "") report.violated_rule = form.data["violated_rule"] report.date = datetime.utcnow() report.reason_description = form.data["reason_description"] report.is_comment = is_comment report.action_taken = None report.is_dismissed = False report.post_id = reported_id if is_comment == 0 else None report.comment_id = reported_id if is_comment == 1 else None report.save() flash({ 'text': "You have created a report.", 'type': "success" }) return redirect("/") except NotImplementedError as error: return render_template("error.html", error_type="Failed", error_info=str(error)) else: if request.method == "POST": return render_template( 'report.html', form=form, error="Invalid field, please check again.") else: return render_template('report.html', form=form)
def register(): if check.logged_in(): return redirect("/") else: form = RegistrationForm(request.form) if form.validate() == False: print(form.errors) if form.validate_on_submit(): username = form.data["username"] email = form.data["email"] unique_check = User.unique_user_check(username, email) if unique_check: new_user = User() new_user.first_name = form.data["firstname"] new_user.last_name = form.data["lastname"] new_user.username = form.data["username"] new_user.birth_date = form.data["birth_date"] new_user.email = form.data["email"] password_hash = current_app.config[ 'bcrypt'].generate_password_hash( form.data["password"]).decode('utf-8') new_user.password = password_hash new_user.is_admin = False new_user.is_banned = False new_user.date = datetime.utcnow() new_user.save() flash({ 'text': "You have successfully signed up!", 'type': "success" }) return redirect("/") else: return render_template( 'register.html', form=form, error= "This username or e-mail is already in use, please try another one." ) else: if request.method == "POST": return render_template('register.html', form=form, error=", field, please check again.") else: return render_template('register.html', form=form) return render_template('register.html', form=form)
def delete_report(submitter_id, id): if not check.logged_in(): flash({'text': "Please sign in.", 'type': "error"}) return redirect("/") else: if submitter_id == session.get("user_id", ""): report = Report(id) report.delete() flash({'text': "You have deleted a report.", 'type': "success"}) return redirect("/user/profile/" + str(submitter_id)) else: flash({ 'text': "You can not delete another user's report.", 'type': "error" }) return redirect("/")
def show_reports(id): if check.logged_in(): if id == session.get("user_id", ""): return render_template('user_reports.html', report_list=Report.get_user_all_reports(id)) else: flash({ 'text': "You can not view another user's reports", 'type': "error" }) return redirect("../") else: flash({ 'text': "You have to sign in to view your reports.", 'type': "error" }) return redirect("/")
def tag_moderate(tag_name): """Main moderation view for tags""" if not check.logged_in(): error_context = { 'error_name': "Forbidden", 'error_info': "You may not access this page without logging in" } return render_template('error.html', **error_context) try: tag = Tag(tag_name) except: error_context = { 'error_name': "404 Not Found", 'error_info': "The tag you tried to access does not exist, but you can create this tag." } return render_template('error.html', **error_context) if not TagModerator.is_mod(session['user_id'], tag.id): error_context = { 'error_name': "Access Denied", 'error_info': "You are not a moderator of this tag" } return render_template('error.html', **error_context) add_mod_form = TagModForm(csrf_enabled=False) remove_mod_form = TagModForm(csrf_enabled=False) edit_tag_form = TagEditForm(description=tag.description, rules=tag.rules, csrf_enabled=False) context = { 'title': tag.title, 'is_banned': tag.is_banned, 'mods': tag.list_mods() } return render_template('tag_mod.html', add_mod_form=add_mod_form, remove_mod_form=remove_mod_form, edit_tag_form=edit_tag_form, **context)
def profile_page(id): try: admin = False ban = False self_profile = False if check.logged_in(): if id == session.get("user_id", ""): self_profile = True if admin_check.admin_logged_in(): admin = True user = User(id) if user.is_banned == True: ban = True parent_list = [] for vote in Vote.get_user_total_votes(user.id): if vote.is_comment == 1: parent_list.append(Comment(vote.comment_id)) elif vote.is_comment == 0: parent_list.append(Post(vote.post_id)) return render_template('profile.html', id=user.id, username=user.username, first_name=user.first_name, last_name=user.last_name, birth_date=user.birth_date, creation_date=user.date, posts=Post.get_user_post(user.id), email=user.email, self_profile=self_profile, total_votes=Vote.get_user_total_votes(user.id), comments=Comment.get_user_total_comments( user.id), reports=Report.get_user_all_reports(user.id), parent_list=parent_list, admin=admin, ban=ban) except NotImplementedError as error: flash("Error: " + str(error)) return redirect("/")
def comment_edit(comment_id): # check if post exists try: comment = Comment(comment_id) except: error_context = { 'error_name': "404 Not Found", 'error_info': "The comment you tried to access does not exist" } return render_template('error.html', **error_context) # check if user is logged in if not check.logged_in(): error_context = { 'error_name': "Unauthorized", 'error_info': "You must log in first" } return render_template('error.html', **error_context) # check if user is OP if not (comment.user_id == session['user_id']): error_context = { 'error_name': "Unauthorized", 'error_info': "You are not the original poster of this comment" } return render_template('error.html', **error_context) # get POST input form = CommentForm(content=comment.content) if form.validate_on_submit(): comment.content = form.content.data comment.content_html = md.render(form.content.data) comment.save() flash("Comment edited successfully") return redirect( url_for('post_pages.post_view', post_id=comment.post_id)) return render_template('post_text_edit.html', form=form, body=comment.content, name="Comment")
def comment_delete(comment_id): try: comment = Comment(comment_id) except: error_context = { 'error_name': "404 Not Found", 'error_info': "The comment you tried to access does not exist" } return render_template('error.html', **error_context) # check if user is logged in if not check.logged_in(): error_context = { 'error_name': "Unauthorized", 'error_info': "You must log in first" } return render_template('error.html', **error_context) # check if user is OP if not (comment.user_id == session['user_id']): error_context = { 'error_name': "Unauthorized", 'error_info': "You are not the original poster" } return render_template('error.html', **error_context) form = DeleteForm() if form.validate_on_submit(): if form.yes.data: comment.delete() flash("Comment deleted succesfully") return redirect('/') else: flash("Comment deletion cancelled") return redirect( url_for('post_pages.post_view', post_id=comment.post_id)) return render_template('post_delete.html', form=form, name="Comment")
def tag_create(): if not check.logged_in(): error_context = { 'error_name': "403 Forbidden", 'error_info': "You may not create a tag without an account. Please log in or create an account" } return render_template('error.html', **error_context) else: form = TagCreationForm() if form.validate_on_submit(): tag = Tag() mod = TagModerator() # TODO: tag name sanitization tag.title = form.title.data tag.date = datetime.now() tag.subscriber_amount = 0 tag.is_banned = False tag.description = form.description.data tag.rules = form.rules.data tag.save() # exact same date of creation denotes original creator mod.date = tag.date mod.user_id = int(session['user_id']) mod.tag_id = tag.id mod.save() flash('New tag created') # TODO: Redirect to tag page return render_template('tag_create.html', form=form) else: return render_template('tag_create.html', form=form)
def post_view(post_id): # get post info by id, # render post block # TO DO AFTER: # expose comment input # get all comments # group comments (nesting) # sort comments by opt """ Expand this DOCSTRING """ try: # get post object with all comments post = Post(post_id, True) except: error_context = { 'error_name': "404 Not Found", 'error_info': "The post you tried to access does not exist" } return render_template('error.html', **error_context) form = CommentForm() if form.validate_on_submit(): if not check.logged_in(): error_context = { 'error_name': "403 Forbidden", 'error_info': "You may not comment without an account. Please log in or create an account" } return render_template('error.html', **error_context) # create comment comment = Comment() comment.user_id = session['user_id'] comment.post_id = post_id comment.content_type = 'text' comment.content = form.content.data comment.content_html = md.render(form.content.data) comment.is_external = False comment.date = datetime.now() comment.current_vote = 0 comment.save() post.comment_count += 1 post.save() flash('Comment created successfuly') # reload page with the new comment return redirect(url_for('post_pages.post_view', post_id=post_id)) context = post.generate_context() # sets flag if viewer is logged in context['is_logged_in'] = check.logged_in() # sets flag if viewer is the original poster (a.k.a OP) context['is_op'] = context['is_logged_in'] and (post.user_id == session['user_id']) if not context['is_op']: context['is_op'] = context['is_logged_in'] and TagModerator.is_mod( session['user_id'], post.tag_id) return render_template('post.html', **context, form=form)
def vote_post(parent_id, vote_type, parent_type): if check.logged_in(): if (parent_type == 0 or parent_type == 1) and (vote_type == 0 or vote_type == 1): ## parent type = 0 post ## parent type = 1 comment create_vote = False delete_vote = False try: if parent_type == 0: parent = Post(parent_id) user_vote = Vote.get_user_post_vote( session.get("user_id", ""), parent_id) elif parent_type == 1: parent = Comment(parent_id) user_vote = Vote.get_user_comment_vote( session.get("user_id", ""), parent_id) if not user_vote: #User did not vote this post before if (vote_type == 1 ): #If upvote increment the count, else decrement. parent.current_vote += 1 else: parent.current_vote -= 1 parent.save() create_vote = True else: #User voted this post before if user_vote[0].vote: #Previous vote was upvote if vote_type == 0: #User wants to change the vote to downwote parent.current_vote -= 2 user_vote[0].last_update_time = datetime.utcnow() user_vote[0].save() else: parent.current_vote -= 1 #User takes the vote back by clicking twice delete_vote = True #Vote will be delete else: #Previous vote was downvote if vote_type == 0: #Current vote is downvote parent.current_vote += 1 #Vote will be deleted since it was clicked twice delete_vote = True else: parent.current_vote += 2 #User wants to chane the vote to upvote user_vote[0].last_update_time = datetime.utcnow() user_vote[0].save() if delete_vote: user_vote[0].delete() else: user_vote[0].vote = bool(vote_type) user_vote[0].save() parent.save() #New vote gets created and sended as a JSON object if create_vote: vote = Vote() vote.date = datetime.utcnow() vote.is_comment = bool(parent_type) vote.vote = bool(vote_type) vote.vote_ip = request.remote_addr vote.last_update_time = datetime.utcnow() vote.user_id = session.get("user_id", "") vote.post_id = parent_id if parent_type == 0 else None vote.comment_id = parent_id if parent_type == 1 else None vote.save() return jsonify({ 'success': 'Successfuly voted!', 'final_vote': parent.current_vote }) except NotImplementedError as error: return jsonify({'error': str(error)}) return jsonify({'error': 'Invalid vote.'})