def edit_cause_fund(request, fund_id): """ The edit cause (admin) view. :param request: :param cause_id: cause id to edit :return: """ if not request.user.profile.can_manage_causes: return HttpResponseForbidden( "You do not have permission to access that.") fund = get_object_or_404(CauseFund, pk=fund_id) if request.method == 'POST': form = CauseFundForm(request.POST, instance=fund) if form.is_valid(): # if it was a form submission save it form.save() log_user_event(request.user, "Edited {} cause fund".format(fund.name), "admin", form) return HttpResponseRedirect( reverse('manage_cause_funds', kwargs={ 'cause_id': fund.cause.pk, })) else: # otherwise return form with errors return render(request, 'edit_cause_fund.html', {'form': form}) else: # if it's not a form submission, return an empty form form = CauseFundForm(instance=CauseFund.objects.get(pk=fund_id)) return render(request, 'edit_cause_fund.html', {'form': form})
def admin_add_spacebucks(request, member_id, amount): if not request.user.profile.can_see_members_spacebucks: return HttpResponseForbidden(permission_message) if request.method == 'GET': user = User.objects.get(pk=member_id) # Convert from cents amount = round(amount / 100, 2) if amount > 50: return HttpResponseBadRequest("Invalid amount.") transaction = SpaceBucks() transaction.amount = amount transaction.user = user transaction.description = "Manually added by administrator." transaction.transaction_type = "bank" transaction.logging_info = "" transaction.save() log_user_event( request.user, "Manually added ${} to {}.".format(amount, user.profile.get_full_name()), "spacebucks") log_user_event( user, "{} manually added ${} to {}.".format( request.user.profile.get_full_name(), amount, user.profile.get_full_name()), "stripe") return JsonResponse({"success": True}) else: return HttpResponseBadRequest("Invalid request method.")
def manage_cause_funds(request, cause_id): cause = get_object_or_404(Causes, pk=cause_id) if not request.user.profile.can_manage_causes or cause not in request.user.profile.can_manage_cause.all( ): return HttpResponseForbidden( "You do not have permission to access that.") # if we want to add a cause if request.method == 'POST': form = CauseFundForm(request.POST) if form.is_valid(): fund = form.save(commit=False) fund.cause = cause fund.save() log_user_event( request.user, "Created {} cause.".format(form.cleaned_data.get('name')), "admin", form) return HttpResponseRedirect( reverse("manage_cause_funds", kwargs={ 'cause_id': cause.pk, })) else: form = CauseFundForm() funds = CauseFund.objects.filter(cause=cause) return render(request, 'manage_cause_funds.html', { "form": form, "cause": cause, "funds": funds })
def manage_causes(request): if not request.user.profile.can_manage_causes: return HttpResponseForbidden( "You do not have permission to access that.") # if we want to add a cause if request.method == 'POST': form = CauseForm(request.POST) if form.is_valid(): form.save() log_user_event( request.user, "Created {} cause.".format(form.cleaned_data.get('name')), "admin", form) return HttpResponseRedirect(reverse("manage_causes")) else: form = CauseForm() causes = Causes.objects.all() return render(request, 'manage_causes.html', { "form": form, "causes": causes })
def edit_cause(request, cause_id): """ The edit cause (admin) view. :param request: :param cause_id: cause id to edit :return: """ cause = get_object_or_404(Causes, pk=cause_id) if not request.user.profile.can_manage_causes or cause not in request.user.profile.can_manage_cause.all( ): return HttpResponseForbidden( "You do not have permission to access that.") if request.method == 'POST': form = CauseForm(request.POST, instance=cause) if form.is_valid(): # if it was a form submission save it form.save() log_user_event(request.user, "Edited {} cause.".format(cause.name), "admin", form) return HttpResponseRedirect('%s' % (reverse('manage_causes'))) else: # otherwise return form with errors return render(request, 'edit_cause.html', {'form': form}) else: # if it's not a form submission, return an empty form form = CauseForm(instance=Causes.objects.get(pk=cause_id)) return render(request, 'edit_cause.html', {'form': form})
def edit_profile(request): """ The edit user profile view. :param request: :return: """ if request.method == 'POST': user_form = EditUserForm(request.POST, instance=request.user) profile_form = EditProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): # if it was a form submission save it user_form.save() profile_form.save() if request.user.profile.must_update_profile: request.user.profile.must_update_profile = False request.user.profile.save() log_user_event(request.user, "User profile edited.", "profile") return HttpResponseRedirect('%s' % (reverse('profile'))) else: # if it's not a form submission, return an empty form user_form = EditUserForm(instance=request.user) profile_form = EditProfileForm(instance=request.user.profile) return render(request, 'edit_profile.html', { 'user_form': user_form, "profile_form": profile_form })
def send_single_email(user, email, subject, title, message): message = escape(message) message = message.replace("~br~", "<br>") email_vars = {"preheader": "", "title": title, "message": message} email_string = render_to_string('email_without_button.html', {'email': email_vars}) if "SENDGRID_API_KEY" in os.environ: sg = sendgrid.SendGridAPIClient( apikey=os.environ.get('SENDGRID_API_KEY')) from_email = sendgrid.Email(settings.FROM_EMAIL) to_email = sendgrid.Email(email) subject = subject content = Content("text/html", email_string) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code == 202: log_user_event(user, "Sent email with subject: " + subject, "email", "Email content: " + message) return True else: return False log_user_event(user, "Failed to send email with subject: " + subject, "email", "Email content: " + message) raise RuntimeError("No SendGrid API key found in environment variables.")
def admin_grant_interlock(request, interlock_id, member_id): if not request.user.profile.can_manage_access: return HttpResponseForbidden( "You do not have permission to access that.") try: user = User.objects.get(pk=member_id) interlock = Interlock.objects.get(pk=interlock_id) user.profile.interlocks.add(interlock) user.profile.save() log_user_event(user, "Access to {} granted.".format(interlock.name), "profile") log_user_event( request.user, "Access to {} granted for {}.".format( interlock.name, user.profile.get_full_name()), "admin") return JsonResponse({"success": True}) except Exception: return JsonResponse({ "success": False, "reason": "Bad Request. User or interlock not found." })
def delete_door(request, door_id): if not request.user.profile.can_manage_doors: return HttpResponseForbidden("You do not have permission to access that.") door = Doors.objects.get(pk=door_id) log_user_event(request.user, "Deleted {} door.".format(door.name), "admin") door.delete() return HttpResponseRedirect('%s' % (reverse('manage_doors')))
def activate(self): log_user_event(self.user, "Activated member", "profile") if self.state is not "noob": self.user.email_enable_member() self.state = "active" self.save() return True
def delete_interlock(request, interlock_id): if not request.user.profile.can_manage_interlocks: return HttpResponseForbidden("You do not have permission to access that.") interlock = Interlock.objects.get(pk=interlock_id) log_user_event(request.user, "Deleted {} interlock.".format(interlock.name), "admin") interlock.delete() return HttpResponseRedirect('%s' % (reverse('manage_interlocks')))
def reset_password(self): log_user_event(self, "Password reset requested", "profile") self.password_reset_key = uuid.uuid4() self.password_reset_expire = timezone.now() + timedelta(hours=24) self.save() self.email_password_reset("https://portal.hsbne.org" + reverse( 'reset_password', kwargs={'reset_token': self.password_reset_key})) return True
def lock_interlock(request, interlock_id): if not request.user.profile.can_manage_interlocks: return HttpResponseForbidden( "You do not have permission to access that.") interlock = Interlock.objects.get(pk=interlock_id) log_user_event(request.user, "Locked {} interlock via API.".format(interlock.name), "interlock") return JsonResponse({"success": interlock.lock()})
def bump_door(request, door_id): if not request.user.profile.can_manage_doors: return HttpResponseForbidden("You do not have permission to access that.") door = Doors.objects.get(pk=door_id) if door in request.user.profile.doors.all(): log_user_event(request.user, "Bumped {} door via API.".format(door.name), "door") return JsonResponse({"success": door.bump()}) return JsonResponse({"success": False, "message": "You are not authorised to access that door."})
def resend_welcome_email(request, member_id): success = User.objects.get(pk=member_id).email_welcome() log_user_event(request.user, "Resent welcome email.", "profile") if success: return JsonResponse({"message": success}) else: return JsonResponse( {"message": "Couldn't email member, unknown error."})
def sync_xero_accounts(request): from .xerohelpers import sync_xero_accounts success = sync_xero_accounts(User.objects.all().prefetch_related()) log_user_event(request.user, "Resynced xero accounts.", "profile") if success: return JsonResponse({"message": success}) else: return JsonResponse( {"message": "Couldn't sync xero accounts, unknown error."})
def delete_cause_fund(request, fund_id): if not request.user.profile.can_manage_causes: return HttpResponseForbidden( "You do not have permission to access that.") fund = get_object_or_404(CauseFund, pk=fund_id) fund.delete() log_user_event(request.user, "Deleted {} cause fund.".format(fund.name), "admin") return HttpResponse("Success")
def delete_cause(request, cause_id): cause = get_object_or_404(Causes, pk=cause_id) if not request.user.profile.can_manage_causes or cause not in request.user.profile.can_manage_cause.all( ): return HttpResponseForbidden( "You do not have permission to access that.") cause.delete() log_user_event(request.user, "Deleted {} cause.".format(cause.name), "admin") return HttpResponseRedirect(reverse("manage_causes"))
def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) log_user_event(request.user, "User password changed.", "profile") return redirect('profile') else: return render(request, 'change_password.html', {'form': form}) else: form = PasswordChangeForm(request.user) return render(request, 'change_password.html', {'form': form})
def spacebug(request): # Handle submission. if request.method == 'POST': print(request.POST.get("title")) if request.POST.get("title") and request.POST.get("description"): if "PORTAL_TRELLO_API_KEY" in os.environ and "PORTAL_TRELLO_API_TOKEN" in os.environ: issue = request.POST.get('title', '') details = request.POST.get('description', '') url = "https://api.trello.com/1/cards" trelloKey = os.environ.get('PORTAL_TRELLO_API_KEY') trelloToken = os.environ.get('PORTAL_TRELLO_API_TOKEN') querystring = { "name": issue, "desc": details, "pos": "top", "idList": "5529dd886d658fdace75c830", "keepFromSource": "all", "key": trelloKey, "token": trelloToken } response = requests.request("POST", url, params=querystring) if response.status_code == 200: log_user_event( request.user, "Submitted issue: " + issue + " Content: " + details, "generic") return render(request, 'spacebug.html', {'message': "Submission Successful!"}) else: return render( request, 'spacebug.html', {'error': "Sorry but there was a server side error."}) else: return render( request, 'spacebug.html', { 'error': "Sorry but there was a server side error: Trello API is not configured." }) return render(request, 'spacebug.html', {'error': "Invalid form submission..."}) # render template normally return render(request, 'spacebug.html')
def add_door(request): if not request.user.profile.can_manage_doors: return HttpResponseForbidden("You do not have permission to access that.") if request.method == 'POST': form = DoorForm(request.POST) if form.is_valid(): form.save() log_user_event(request.user, "Created {} door.".format(form.cleaned_data['name']), "admin", form) return HttpResponseRedirect(reverse("manage_doors")) else: form = DoorForm() return render(request, 'add_door.html', {"form": form})
def admin_revoke_interlock(request, interlock_id, member_id): if not request.user.profile.can_manage_access: return HttpResponseForbidden("You do not have permission to access that.") try: user = User.objects.get(pk=member_id) interlock = Interlock.objects.get(pk=interlock_id) user.profile.interlocks.remove(interlock) user.profile.save() log_user_event(user, "Access to {} revoked.".format(interlock.name), "profile") log_user_event(request.user, "Access to {} revoked for {}.".format(interlock.name, user.profile.get_full_name()), "admin") return JsonResponse({"success": True}) except ObjectDoesNotExist: return JsonResponse({"success": False, "reason": "No access permission was found."})
def admin_edit_member(request, member_id): """ Part of the process for our ajax requests for the member list. :param request: :param member_id: :return: """ if not request.user.profile.can_see_members_personal_details: return HttpResponseForbidden(permission_message) profile = get_object_or_404(Profile, user=member_id) data = dict() profile_form = AdminEditProfileForm(instance=profile) user_form = AdminEditUserForm(instance=profile.user) form_valid = False if request.method == 'POST': # if it's a form submission pass it to the form profile_form = AdminEditProfileForm(request.POST, instance=profile) user_form = AdminEditUserForm(request.POST, instance=profile.user) if profile_form.is_valid() and user_form.is_valid(): # if it's a valid form submission then save and log it try: profile_form.save() user_form.save() form_valid = True log_user_event( profile.user, request.user.profile.get_full_name() + " edited user profile.", "profile") except IntegrityError: form_valid = False # render the form and return it data["form_is_valid"] = form_valid data['html_form'] = render_to_string('partial_admin_edit_member.html', { 'profile_form': profile_form, 'user_form': user_form, 'member_id': member_id, "profile": profile }, request=request) return JsonResponse(data)
def email_profile_to(self, to_email): causes = self.causes.all() causes_string = "none :(" if causes.count() == 3: causes_string = "{}, {} and {}".format(causes[0], causes[1], causes[2]) elif causes.count() == 2: causes_string = "{} and {}".format(causes[0], causes[1]) elif causes.count() == 1: causes_string = causes[0] message = "{} has just signed up. Their membership level is {} and their selected causes are {}. " \ "Their email is {}.".format(self.get_full_name(), self.member_type, causes_string, self.user.email) email_vars = { "preheader": "", "title": "New member signup", "message": message } email_string = render_to_string('email_without_button.html', {'email': email_vars}) subject = "A new member signed up! ({})".format(self.get_full_name()) if "SENDGRID_API_KEY" in os.environ: sg = sendgrid.SendGridAPIClient( apikey=os.environ.get('SENDGRID_API_KEY')) from_email = sendgrid.Email(settings.FROM_EMAIL) to_email = sendgrid.Email(to_email) content = Content("text/html", email_string) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code == 202: log_user_event(self.user, "Sent email with subject: " + subject, "email", "Email content: " + email_string) return True log_user_event(self.user, "Failed to send email with subject: " + subject, "email", "Email content: " + email_string) return False
def send_group_email(user, emails, subject, title, message): message = escape(message) message = message.replace("~br~", "<br>") email_vars = {"preheader": "", "title": title, "message": message} email_string = render_to_string('email_without_button.html', {'email': email_vars}) emails.append(settings.EXEC_EMAIL) if "SENDGRID_API_KEY" in os.environ: mail = Mail() for to_email in emails: print(to_email) # Create new instance for each email personalization = Personalization() # Add email addresses to personalization instance personalization.add_to(Email(to_email)) # Add personalization instance to Mail object mail.add_personalization(personalization) # Add data that is common to all personalizations mail.from_email = Email(settings.FROM_EMAIL) mail.reply_to = Email(user.email) mail.subject = subject mail.add_content(Content('text/html', email_string)) # Send sg = sendgrid.SendGridAPIClient( apikey=os.environ.get('SENDGRID_API_KEY')) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code == 202: log_user_event(user, "Sent email with subject: " + subject, "email", "Email content: " + email_string) return True else: log_user_event(user, "Failed to send email with subject: " + subject, "email", "Email content: " + email_string) return False else: raise RuntimeError( "No SendGrid API key found in environment variables.")
def __send_email(self, subject, body): if "SENDGRID_API_KEY" in os.environ: sg = sendgrid.SendGridAPIClient( apikey=os.environ.get('SENDGRID_API_KEY')) from_email = sendgrid.Email(settings.FROM_EMAIL) to_email = sendgrid.Email(self.email) subject = subject content = Content("text/html", body) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code == 202: log_user_event(self, "Sent email with subject: " + subject, "email", "Email content: " + body) return True log_user_event(self, "Failed to send email with subject: " + subject, "email", "Email content: " + body) raise RuntimeError( "No SendGrid API key found in environment variables.")
def edit_door(request, door_id): if not request.user.profile.can_manage_doors: return HttpResponseForbidden("You do not have permission to access that.") if request.method == 'POST': form = DoorForm(request.POST, instance=Doors.objects.get(pk=door_id)) if form.is_valid(): # if it was a form submission save it form.save() log_user_event( request.user, "Edited {} door.".format(Doors.objects.get(pk=door_id).name), "admin", form) return HttpResponseRedirect('%s' % (reverse('manage_doors'))) else: # otherwise return form with errors return render(request, 'edit_door.html', {'form': form}) else: # if it's not a form submission, return an empty form form = DoorForm(instance=Doors.objects.get(pk=door_id)) return render(request, 'edit_door.html', {'form': form})
def edit_theme_song(request): if request.method == 'POST': theme_form = ThemeForm(request.POST, request.FILES, instance=request.user.profile) if theme_form.is_valid(): # todo: pass the uploaded file (or removal request) to asterisk # handle_uploaded_file(request.FILES['theme']) theme_form.save() log_user_event(request.user, "User theme updated.", "profile") return HttpResponseRedirect('%s' % (reverse('edit_theme_song'))) else: # if it's not a form submission, return an empty form theme_form = ThemeForm(instance=request.user.profile) return render( request, 'edit_theme_song.html', {"theme_form": theme_form}, )
def deactivate(self): log_user_event(self.user, "Deactivated member", "profile") self.user.email_disable_member() self.state = "inactive" self.save() return True
def starving_hacker_form(request): if request.method == 'POST': starving_form = StarvingHackerForm(request.POST, instance=request.user.profile) if starving_form.is_valid(): # if it was a form submission save it profile = starving_form.save() profile.updated_starving_details = datetime.now() profile.save() log_user_event(request.user, "User edited starving hacker details.", "profile") message = None error = None if profile.is_starving_eligible(): message = "Your application for the starving hacker discount was " \ "successful. Your next invoice " \ "should reflect the discount. If it doesn't, email our treasurer at [email protected]." email = send_single_email(request.user, settings.EXEC_EMAIL, "New Starving Hacker Approved", "New Starving Hacker Approved", "Hi there, a new starving hacker application has been approved for {}. Please " \ "update their membership level in the portal and change their repeating invoice in " \ "Xero to reflect the discount.".format(profile.get_full_name())) else: if profile.special_consideration: error = " Unfortunately, you aren't eligible for the discount based on the information you " \ "provided. As you requested special consideration, the executive will review your " \ "application and get back to you within a few days with the outcome." email = send_single_email(request.user, settings.EXEC_EMAIL, "New Special Consideration Application for Starving Hacker", "New Special Consideration Application for Starving Hacker", "Hi there, a new starving hacker application has been rejected for {}. However," \ "they have requested special consideration. Login to the portal if you'd like " \ "to check their application details. ~br~~br~ Special Consideration Reason: {}".format( request.user.profile.get_full_name(), profile.special_consideration_note)) else: error = " Unfortunately, you aren't eligible for the discount based on the information you " \ "provided. Your attempt has been logged and any additional applications may require proof" \ " of your circumstances." email = send_single_email(request.user, settings.EXEC_EMAIL, "New Starving Hacker Rejected", "New Starving Hacker Rejected", "Hi there, a new starving hacker application has been rejected for {}. Login to the" \ " portal if you'd like to check their application details.".format( request.user.profile.get_full_name())) if not email: return render( request, 'starving_hacker_form.html', { "message": message, "error": "Unable to send email to the executive.", "form": starving_form }) return render(request, 'starving_hacker_form.html', { "message": message, "error": error, "form": starving_form }) return render(request, 'starving_hacker_form.html', { "error": "Error validating form.", "form": starving_form }) else: # if it's not a form submission, return an empty form starving_form = StarvingHackerForm(instance=request.user.profile) return render(request, 'starving_hacker_form.html', {"form": starving_form})