def update_question(request, username, question_id): """ Update a single answer for a particular profile question of a particular user """ profile = UserProfile.get_user_profile_from_username(username) # Make sure that the profile exists if profile: user = profile.user else: return form_failure_notification('User does not exist') # Make sure that a user is only able to update his profile and nobody else's. if request.user != user: return form_failure_notification('Uh oh! Something went wrong!') if request.method == 'POST': profile_answer_form = ProfileAnswerForm(request.POST) if profile_answer_form.is_valid(): new_answer = request.POST.get('answer', '') profile_answer = ProfileAnswer.get_answer(user, ProfileQuestion.objects.get(id=question_id)) profile_answer.answer = new_answer profile_answer.save() return ajax_http(form_success_notification('Question successfully updated')) else: return ajax_http(form_failure_notification('Answer too long'))
def request_to_buy(request): user = request.user try: ticket = Ticket.objects.get(pk=request.POST.get('ticket_id')) except Ticket.DoesNotExist: raise Http404() # Do this validation again... if not Request.can_request(ticket, user) or Request.requested_other_ticket_same_time(user, ticket): return ajax_http(False, 400) if ticket.poster == user: logging.warning('User cannot request to buy their own ticket') return ajax_http(False, 400) # Get the token and card that stripe sent us token = request.POST.get('token') card_id = request.POST.get('card_id') if not token or not card_id: logging.info('Request to buy submitted without Stripe token for {}'.format(user)) return ajax_other_message('Your request was unable to be processed. Our developers are on it!', 400) try: customer, card = create_customer_and_card(user, token, card_id) except StripeError as e: logging.critical('Request creation failed') return ajax_other_message('Your request was unable to be processed. Our developers are on it', 400) Request.objects.create_request(ticket, user, card) return ajax_other_message('Your request to buy has been submitted. ' 'Your card will be charged if the seller accepts your request.', 200)
def login_redirect(request): # If the user is already logged in, they're doing something they aren't supposed to. Send them a 405. if request.user.is_authenticated(): return redirect("/") if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): email = login_form.cleaned_data.get("email") password = login_form.cleaned_data.get("password") # We actually do this authenticate function twice, once in LoginForm and once here. # The code is cleaner this way, despite the extra DB hits. user = authenticate(email=email, password=password) auth_login(request, user) activate(user.timezone()) # Configure time zone return ajax_http({"redirect_href": "/"}, status=200) else: return ajax_http( { "notification_type": "alert-danger", "notification_content": render_to_string( "user_profile/forgot_password.html", "", RequestContext(request) ), }, status=400, ) return render(request, "registration/login_redirect.html", {"form_settings": login_form_settings})
def login_redirect(request): #If the user is already logged in, they're doing something they aren't supposed to. Send them a 405. if request.user.is_authenticated(): return redirect('/') if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): email = login_form.cleaned_data.get('email') password = login_form.cleaned_data.get('password') # We actually do this authenticate function twice, once in LoginForm and once here. # The code is cleaner this way, despite the extra DB hits. user = authenticate(email=email, password=password) auth_login(request, user) activate(user.timezone()) # Configure time zone return ajax_http({'redirect_href': '/'}, status=200) else: return ajax_http( { 'notification_type': 'alert-danger', 'notification_content': render_to_string('user_profile/forgot_password.html', '', RequestContext(request)) }, status=400, ) return render(request, 'registration/login_redirect.html', {'form_settings': login_form_settings})
def update_question(request, username, question_id): """ Update a single answer for a particular profile question of a particular user """ profile = UserProfile.get_user_profile_from_username(username) # Make sure that the profile exists if profile: user = profile.user else: return form_failure_notification('User does not exist') # Make sure that a user is only able to update his profile and nobody else's. if request.user != user: return form_failure_notification('Uh oh! Something went wrong!') if request.method == 'POST': profile_answer_form = ProfileAnswerForm(request.POST) if profile_answer_form.is_valid(): new_answer = request.POST.get('answer', '') profile_answer = ProfileAnswer.get_answer( user, ProfileQuestion.objects.get(id=question_id)) profile_answer.answer = new_answer profile_answer.save() return ajax_http( form_success_notification('Question successfully updated')) else: return ajax_http(form_failure_notification('Answer too long'))
def valid_ticket(request): """ This function just checks if a ticket a user wishes to create has valid data. """ if request.method == 'GET': valid_ticket_form = ValidTicketForm(request.GET) if valid_ticket_form.is_valid(): return ajax_http(True, 200) return ajax_http(**non_field_errors_notification(valid_ticket_form)) return ajax_http(False, 400)
def valid_ticket(request): """ This function just checks if a ticket a user wishes to create has valid data. """ if request.method == 'GET': valid_ticket_form = ValidTicketForm(request.GET) if valid_ticket_form.is_valid(): return ajax_http(True, 200) return ajax_http(**non_field_errors_notification(valid_ticket_form)) return ajax_http(False, 400)
def customer_exists(request): """ Return whether a Stripe customer record exists for the requesting user """ if request.user.is_anonymous(): return ajax_http(False, 400) elif Customer.get_customer_from_user(request.user): return ajax_http(True, 200) else: return ajax_http(False, 400)
def login(request): # If the user is already logged in, redirect him to the homepage if request.user.is_authenticated(): return ajax_http({'isSuccessful': True, 'redirect_href': '/'}, ) # If the form has been submitted by the user if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): email = login_form.cleaned_data.get('email') password = login_form.cleaned_data.get('password') try: # We actually do this authenticate function twice, once in LoginForm and once here. # The code is cleaner this way, despite the extra DB hits. user = authenticate(email=email, password=password) except Exception as e: print("I/O error({0}): {1}".format(e.errno, e.strerror)) raise if not user.is_confirmed: EmailConfirmationLink.objects.create_email_confirmation(user) return ajax_http( { 'notification_type': 'alert-danger', 'notification_content': 'You need to confirm your email address. We just sent you another link!' }, status=400, ) auth_login(request, user) activate(user.timezone()) # Configure time zone return ajax_http({'isSuccessful': True}, status=200, request=request) else: return ajax_http( { 'notification_type': 'alert-danger', 'notification_content': 'Wrong username or password! <a href="{}">Click to reset your password</a>' .format(reverse('create_forgot_password')) }, status=400, ) return render(request, 'registration/login.html', {'form_settings': login_form_settings})
def send_message(request): if request.method == 'POST': send_message_form = SendMessageForm(request.POST, request=request) if send_message_form.is_valid(): sender = request.user ticket = send_message_form.cleaned_data.get('ticket') other_user = send_message_form.cleaned_data.get('other_user') body = send_message_form.cleaned_data.get('body') Message.objects.create_message(sender, other_user, ticket, body) return ajax_http(form_success_notification('Your message was sent successfully!')) else: return ajax_http(non_field_errors_notification(send_message_form))
def submit_ticket(request): # If the form has been submitted by the user if request.method == 'POST': submit_ticket_form = SubmitTicketForm(request.POST) #Determine which form the user submitted. if submit_ticket_form.is_valid(): user = request.user title = submit_ticket_form.cleaned_data.get('title') price = submit_ticket_form.cleaned_data.get('price') location_raw = submit_ticket_form.cleaned_data.get('location_raw') location = submit_ticket_form.cleaned_data.get('location') venue = submit_ticket_form.cleaned_data.get('venue') start_datetime = submit_ticket_form.cleaned_data.get( 'start_datetime') ticket_type = submit_ticket_form.cleaned_data.get('ticket_type') payment_method = submit_ticket_form.cleaned_data.get( 'payment_method', 'G') # TODO Assume good faith since # lean launch won't have secure about = submit_ticket_form.cleaned_data.get( 'about') or '' # Might be empty token = submit_ticket_form.cleaned_data.get('token') card_id = submit_ticket_form.cleaned_data.get('card_id') try: customer, card = create_customer_and_card(user, token, card_id) except StripeError as e: logging.critical('Ticket creation failed') return ajax_other_message( 'Uh oh, it looks like our server broke! Our developers are on it.', 400) Ticket.objects.create_ticket( poster=request.user, price=price, title=title, about=about, start_datetime=start_datetime, location_raw=location_raw, location=location, ticket_type=ticket_type, payment_method=payment_method, card=card, status='P', venue=venue, ) return ajax_popup_notification( 'success', 'Your ticket was successfully submitted! ' 'It will become visible to others shortly.', 200) # If the user ignored out javascript validation and sent an invalid form, send back an error. # We don't actually specify what the form error was (unless it was a non_field error that we couldn't validate # on the front end). This is okay because our app requires JS to be enabled. # If the user managed to send us an aysynch request xwith JS disabled, they aren't using the site as designed. # eg., possibly a malicious user. No need to repeat the form pretty validation already done on the front end. else: return ajax_http( **non_field_errors_notification(submit_ticket_form)) return render(request, 'tickets/submit_ticket.html', {'form_settings': ticket_submit_form_settings})
def login(request): # If the user is already logged in, redirect him to the homepage if request.user.is_authenticated(): return ajax_http({"isSuccessful": True, "redirect_href": "/"}) # If the form has been submitted by the user if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): email = login_form.cleaned_data.get("email") password = login_form.cleaned_data.get("password") try: # We actually do this authenticate function twice, once in LoginForm and once here. # The code is cleaner this way, despite the extra DB hits. user = authenticate(email=email, password=password) except Exception as e: print("I/O error({0}): {1}".format(e.errno, e.strerror)) raise if not user.is_confirmed: EmailConfirmationLink.objects.create_email_confirmation(user) return ajax_http( { "notification_type": "alert-danger", "notification_content": "You need to confirm your email address. We just sent you another link!", }, status=400, ) auth_login(request, user) activate(user.timezone()) # Configure time zone return ajax_http({"isSuccessful": True}, status=200, request=request) else: return ajax_http( { "notification_type": "alert-danger", "notification_content": 'Wrong username or password! <a href="{}">Click to reset your password</a>'.format( reverse("create_forgot_password") ), }, status=400, ) return render(request, "registration/login.html", {"form_settings": login_form_settings})
def submit_ticket(request): # If the form has been submitted by the user if request.method == 'POST': submit_ticket_form = SubmitTicketForm(request.POST) #Determine which form the user submitted. if submit_ticket_form.is_valid(): user = request.user title = submit_ticket_form.cleaned_data.get('title') price = submit_ticket_form.cleaned_data.get('price') location_raw = submit_ticket_form.cleaned_data.get('location_raw') location = submit_ticket_form.cleaned_data.get('location') venue = submit_ticket_form.cleaned_data.get('venue') start_datetime = submit_ticket_form.cleaned_data.get('start_datetime') ticket_type = submit_ticket_form.cleaned_data.get('ticket_type') payment_method = submit_ticket_form.cleaned_data.get('payment_method', 'G') # TODO Assume good faith since # lean launch won't have secure about = submit_ticket_form.cleaned_data.get('about') or '' # Might be empty token = submit_ticket_form.cleaned_data.get('token') card_id = submit_ticket_form.cleaned_data.get('card_id') try: customer, card = create_customer_and_card(user, token, card_id) except StripeError as e: logging.critical('Ticket creation failed') return ajax_other_message('Uh oh, it looks like our server broke! Our developers are on it.', 400) Ticket.objects.create_ticket(poster=request.user, price=price, title=title, about=about, start_datetime=start_datetime, location_raw=location_raw, location=location, ticket_type=ticket_type, payment_method=payment_method, card=card, status='P', venue=venue, ) return ajax_popup_notification('success', 'Your ticket was successfully submitted! ' 'It will become visible to others shortly.', 200) # If the user ignored out javascript validation and sent an invalid form, send back an error. # We don't actually specify what the form error was (unless it was a non_field error that we couldn't validate # on the front end). This is okay because our app requires JS to be enabled. # If the user managed to send us an aysynch request xwith JS disabled, they aren't using the site as designed. # eg., possibly a malicious user. No need to repeat the form pretty validation already done on the front end. else: return ajax_http(**non_field_errors_notification(submit_ticket_form)) return render(request, 'tickets/submit_ticket.html', {'form_settings': ticket_submit_form_settings} )
def can_delete_ticket(request, ticket_id): # Make sure that ticket exists try: ticket = Ticket.objects.get(pk=ticket_id) except Ticket.DoesNotExist: return ajax_other_message("That ticket doesn't exist", 400) if not ticket.can_delete(): return ajax_other_message("We're sorry. You cannot delete this ticket. Perhaps it has already been sold or " "cancelled. If you have any questions please contact us at [email protected].", 400) return ajax_http(True, 200)
def can_delete_ticket(request, ticket_id): # Make sure that ticket exists try: ticket = Ticket.objects.get(pk=ticket_id) except Ticket.DoesNotExist: return ajax_other_message("That ticket doesn't exist", 400) if not ticket.can_delete(): return ajax_other_message( "We're sorry. You cannot delete this ticket. Perhaps it has already been sold or " "cancelled. If you have any questions please contact us at [email protected].", 400) return ajax_http(True, 200)
def messages_hidden_toggle(request): """ Mark all messages between two users for a particular ticket as read for the user that calls this url. """ if request.method == 'POST': toggle_message_form = EditMessageForm(request.POST, request=request) if toggle_message_form.is_valid(): sender_id = request.user.id other_user_id = toggle_message_form.cleaned_data.get('other_user_id') ticket_id = toggle_message_form.cleaned_data.get('ticket_id') if Message.mark_conversation_hidden_toggle(sender_id, ticket_id, other_user_id, True): return ajax_http({'isSuccessful': True}, status=200) else: return ajax_http({'isSuccessful': False}, status=400, ) return ajax_http({'isSuccessful': False}, status=400)
def signup(request): # If the user is already logged in, they're doing something they aren't supposed to. Send them a 405. if request.user.is_authenticated(): return HttpResponseNotAllowed(["POST"]) # If the form has been submitted by the user if request.method == "POST": signup_form = SignupForm(request.POST, request=request) # Determine which form the user submitted. if signup_form.is_valid(): password = signup_form.cleaned_data.get("password") email = signup_form.cleaned_data.get("email") first_name = signup_form.cleaned_data.get("first_name") last_name = signup_form.cleaned_data.get("last_name") birthdate = signup_form.cleaned_data.get("birthdate") location = signup_form.cleaned_data.get("location") # Creates the user profile as well. Saves both objects to the database. User.objects.create_user( email=email, password=password, first_name=first_name, last_name=last_name, location=location, birthdate=birthdate, ) return ajax_popup_notification( "success", "One last step before you can log in! " "We sent you a confirmation email that should " "arrive in the next few minutes. " "Just click the link inside. " "Don't forget to check your spam folder too.", status=200, ) # If the user ignored out javascript validation and sent an invalid form, send back an error. # We don't actually specify what the form error was. This is okay because our app requires JS to be enabled. # If the user managed to send us an asynch request with JS disabled, they aren't using the site as designed. # eg., possibly a malicious user. No need to repeat the form pretty validation already done on the front end. else: return ajax_http(False, 400) # These need to go here instead of in the settings file to avoid circular dependencies signup_form_settings["ZIP_CODE_REMOTE_URL"] = reverse("valid_zip_code") signup_form_settings["EMAIL_REMOTE_URL"] = reverse("valid_email") return render(request, "registration/signup.html", {"form_settings": signup_form_settings})
def signup(request): #If the user is already logged in, they're doing something they aren't supposed to. Send them a 405. if request.user.is_authenticated(): return HttpResponseNotAllowed(['POST']) # If the form has been submitted by the user if request.method == 'POST': signup_form = SignupForm(request.POST, request=request) #Determine which form the user submitted. if signup_form.is_valid(): password = signup_form.cleaned_data.get('password') email = signup_form.cleaned_data.get('email') first_name = signup_form.cleaned_data.get('first_name') last_name = signup_form.cleaned_data.get('last_name') birthdate = signup_form.cleaned_data.get('birthdate') location = signup_form.cleaned_data.get('location') # Creates the user profile as well. Saves both objects to the database. User.objects.create_user( email=email, password=password, first_name=first_name, last_name=last_name, location=location, birthdate=birthdate, ) return ajax_popup_notification( 'success', "One last step before you can log in! " "We sent you a confirmation email that should " "arrive in the next few minutes. " "Just click the link inside. " "Don't forget to check your spam folder too.", status=200) # If the user ignored out javascript validation and sent an invalid form, send back an error. # We don't actually specify what the form error was. This is okay because our app requires JS to be enabled. # If the user managed to send us an asynch request with JS disabled, they aren't using the site as designed. # eg., possibly a malicious user. No need to repeat the form pretty validation already done on the front end. else: return ajax_http(False, 400) # These need to go here instead of in the settings file to avoid circular dependencies signup_form_settings['ZIP_CODE_REMOTE_URL'] = reverse('valid_zip_code') signup_form_settings['EMAIL_REMOTE_URL'] = reverse('valid_email') return render(request, 'registration/signup.html', {'form_settings': signup_form_settings})
def can_message(request): ticket_id = request.GET.get('ticket_id', None) other_user_id = request.GET.get('other_user_id', None) if not ticket_id or not other_user_id: return ajax_popup_notification('Uh oh, something went wrong', 400) try: ticket = Ticket.objects.get(pk=ticket_id) except Ticket.DoesNotExist: return ajax_popup_notification('danger', "Uh oh, something went wrong", 400) try: other_user = User.objects.get(pk=other_user_id) except User.DoesNotExist: return ajax_popup_notification('danger', "Uh oh, something went wrong", 400) if Message.can_message(ticket, request.user, other_user): return ajax_http(True, 200) else: return ajax_popup_notification('danger', 'You are not allowed to message this user about this ticket.' 'Chances are it was already sold.', 400)
def create_email_confirmation_link(request): EmailConfirmationLink.objects.create_email_confirmation(request.user) return ajax_http(form_success_notification("An email is already on its way. Just click the link inside."))
def create_email_confirmation_link(request): EmailConfirmationLink.objects.create_email_confirmation(request.user) return ajax_http( form_success_notification( "An email is already on its way. Just click the link inside."))
def submit(request): log = logging.getLogger('logentries') log.setLevel(logging.INFO) handler = LogentriesHandler('28379e13-d9b8-434f-a233-7ec9369d2fcb') log.addHandler(handler) if request.method == 'POST': log.info("executing views.submit()"); try: contact_form = ContactForm(request.POST) except Exception as e: #log.error("ContactForm exception error({0}): {1}".format(e.errno, e.strerror)) log.error("ContactForm exception error") raise #log.info("contactForm() isvalid({0}) -> body: '{1}' email: '{2}' subject: '{3}'.".format(contact_form.is_valid(), contact_form.body, contact_form.from_email_address, contact_form.subject_type)); if contact_form.is_valid(): try: subject_type = contact_form.cleaned_data.get('subject_type') subject_type = reverse_category_lookup(subject_type, contact_form_settings.get('SUBJECT_TYPES')) body = contact_form.cleaned_data.get('body') from_email_address = contact_form.cleaned_data.get('from_email_address') except Exception as e: #log.error("contact_form.is_valid() error({0}): {1}".format(e.errno, e.strerror)) log.error("contact_form.is_valid()") raise try: # Send an email to [email protected] with the user's message send_email(SOCIAL_EMAIL_ADDRESS, subject_type, body, from_email=from_email_address ) except Exception as e: log.error("SOCIAL_EMAIL_ADDRESS error" ) #log.error("SOCIAL_EMAIL_ADDRESS error({0}): {1}".format(e.errno, e.strerror)) raise try: # Also shoot the user who contacted us an email to let them know we'll get back to them soon. send_email(from_email_address, FEEDBACK_SUBMISSION_RESPONSE_SUBJECT, '', FEEDBACK_SUBMISSION_RESPONSE_TEMPLATE, ) except Exception as e: log.error("from_email_address error") #log.error("from_email_address error({0}): {1}".format(e.errno, e.strerror)) raise # Notice that we always return True. If the email failed to send, we need to figure it out on our side. # There is nothing additional for the client to do. return ajax_popup_notification('success','We got your message! ' 'Someone should respond to you within 24 hours.', 200) # If the user ignored out javascript validation and sent an invalid form, send back an error. # We don't actually specify what the form error was. This is okay because our app requires JS to be enabled. # If the user managed to send us an aysynch request with JS disabled, they aren't using the site as designed. # eg., possibly a malicious user. No need to repeat the form pretty validation already done on the front end. else: return ajax_http(False) else: contact_form = ContactForm() return render(request, 'contact/contact_form.html', {'contact_form': contact_form, 'form_settings': contact_form_settings, } )