Example #1
0
def account_view(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse(registration_view))

    PASSWORD_MASK = "********"

    user = request.user
    passenger = user.passenger

    if request.method == 'GET':
        name = user.get_full_name()
        email = user.email
        password = PASSWORD_MASK
        phone = passenger.phone
        billing_info = passenger.billing_info.card_repr[-4:] if hasattr(
            passenger, "billing_info") else None

        title = _("Your Account")
        credit_card_error = request.session.get('credit_card_error', '')

        promo_activations = PromoCodeActivation.objects.filter(
            passenger=passenger)
        return render_to_response("mobile/account_registration.html", locals(),
                                  RequestContext(request))

    elif request.method == 'POST':
        new_email = request.POST.get("email", "").strip() or None
        new_first_name, new_last_name = get_name_parts(
            request.POST.get("name") or None)
        new_password = request.POST.get("password", "").replace(
            PASSWORD_MASK, "") or None
        new_phone = request.POST.get("phone", "") or None

        try:
            user = update_user_details(user,
                                       first_name=new_first_name,
                                       last_name=new_last_name,
                                       email=new_email,
                                       password=new_password,
                                       phone=new_phone)
            if new_password:
                user = authenticate(username=user.username,
                                    password=new_password)
                login(request, user)
        except UpdateUserError, e:
            return JSONResponse({'error': e.message})

        # success
        return JSONResponse({
            'redirect': reverse(account_view),
            'billing_url': (get_token_url(request))
        })
def account_view(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse(registration_view))

    PASSWORD_MASK = "********"

    user = request.user
    passenger = user.passenger

    if request.method == "GET":
        name = user.get_full_name()
        email = user.email
        password = PASSWORD_MASK
        phone = passenger.phone
        billing_info = passenger.billing_info.card_repr[-4:] if hasattr(passenger, "billing_info") else None

        title = _("Your Account")
        credit_card_error = request.session.get("credit_card_error", "")

        promo_activations = PromoCodeActivation.objects.filter(passenger=passenger)
        return render_to_response("mobile/account_registration.html", locals(), RequestContext(request))

    elif request.method == "POST":
        new_email = request.POST.get("email", "").strip() or None
        new_first_name, new_last_name = get_name_parts(request.POST.get("name") or None)
        new_password = request.POST.get("password", "").replace(PASSWORD_MASK, "") or None
        new_phone = request.POST.get("phone", "") or None

        try:
            user = update_user_details(
                user,
                first_name=new_first_name,
                last_name=new_last_name,
                email=new_email,
                password=new_password,
                phone=new_phone,
            )
            if new_password:
                user = authenticate(username=user.username, password=new_password)
                login(request, user)
        except UpdateUserError, e:
            return JSONResponse({"error": e.message})

        # success
        return JSONResponse({"redirect": reverse(account_view), "billing_url": (get_token_url(request))})
def post_login_redirect(request):
    url = reverse("wb_home")

    passenger = Passenger.from_request(request)
    if not passenger:
        url = reverse(registration, kwargs={'step': 'phone'})

    elif not hasattr(passenger, "billing_info"):
        url = get_token_url(request)  # go to billing registration

    elif request.session.get(CURRENT_BOOKING_DATA_KEY):
        # continue booking process, mobile continues by closing child browser
        if request.mobile:
            url = reverse("wb_home")
        else:
            url = reverse("booking_continued")

    return HttpResponseRedirect(url)
def post_login_redirect(request):
    url = reverse("wb_home")

    passenger = Passenger.from_request(request)
    if not passenger:
        url = reverse(registration, kwargs={'step': 'phone'})

    elif not hasattr(passenger, "billing_info"):
        url = get_token_url(request)  # go to billing registration

    elif request.session.get(CURRENT_BOOKING_DATA_KEY):
        # continue booking process, mobile continues by closing child browser
        if request.mobile:
            url = reverse("wb_home")
        else:
            url = reverse("booking_continued")

    return HttpResponseRedirect(url)
Example #5
0
def run_billing_service_test(request):
    failures_counter = "billing_test_failures"
    max_strikes = 3

    success = True
    err_msg = ""

    try:
        for val in [False, True]:
            request.mobile = val
            url = get_token_url(request)
            result = fetch(url)
            if result.status_code != 200:
                success = False
                err_msg = "status_code: %s" % result.status_code

    except Exception, e:
        err_msg = "There was an exception: %s\nTraceback:%s" % (
            e, traceback.format_exc())
        success = False
def book_ride(request):
    return JSONResponse({
        'status': 'failed',
        'error': SERVICE_NOT_AVAILABLE_MSG
    })

    passenger = Passenger.from_request(request)
    request_data = simplejson.loads(request.POST.get('data'))
    logging.info(u"book ride: %s\n%s" % (passenger, unicode(simplejson.dumps(request_data), "unicode-escape")))

    result = {
        'status': '',
        'order_id': None,
        'redirect': '',
        'error': '',
        'pickup_dt': None
    }

    if passenger and passenger.user and hasattr(passenger, "billing_info"): # we have logged-in passenger with billing_info - let's proceed
        order_settings = OrderSettings.fromRequest(request)
        ride_id = request_data.get("ride_id")

        new_ride = (ride_id == NEW_ORDER_ID)
        discounted_ride = (ride_id and str(ride_id).startswith(DISCOUNTED_OFFER_PREFIX))

        join_ride = not (new_ride or discounted_ride)
        ride_to_join = SharedRide.by_id(ride_id) if join_ride else None

        order = None
        if ride_to_join:  # check it is indeed a valid candidate
            if is_valid_candidate(ride_to_join, order_settings):
                order = create_order(order_settings, passenger, ride=ride_to_join)
            else:
                logging.warning("tried booking an invalid ride candidate")
                result['error'] = _("Sorry, but this ride has been closed for booking")

        else:  # new or discounted ride, check pickup time isn't before ASAP (minus a couple seconds to allow booking to exactly ASAP)
            if order_settings.pickup_dt <= default_tz_now() + datetime.timedelta(minutes=asap_interval()) - datetime.timedelta(seconds=10):
                logging.warning("tried booking to expired pickup time %s" % order_settings.pickup_dt)
                result['error'] = _("Please choose a later pickup time")
            else:
                if discounted_ride:
                    cached_discount_data = memcache.get(ride_id, namespace=DISCOUNTED_OFFERS_NS)
                    discount_data = DiscountData.load(cached_discount_data)
                    logging.info("[book_ride] discount_data = %s" % discount_data)
                    order = create_order(order_settings, passenger, discount_data=discount_data)
                else:
                    order = create_order(order_settings, passenger)


        if order:
            result['status'] = 'success'
            result['order_id'] = order.id
            result['pickup_formatted'] = order.from_raw
            result['pickup_dt'] = to_js_date(order.depart_time)
            result["price"] = order.get_billing_amount()

            ride_orders = [order] + ( list(ride_to_join.orders.all()) if ride_to_join else [] )
            result["passengers"] = [{'name': o.passenger.name, 'picture_url': o.passenger.picture_url, 'is_you': o==order} for o in ride_orders for seat in range(o.num_seats)]
            result["seats_left"] = MAX_SEATS - sum([o.num_seats for o in ride_orders])

            deferred.defer(join_offer_and_order, order, request_data)

        else:
            result['status'] = 'failed'

    else:  # not authorized for booking, save current booking state in session
        set_current_booking_data(request)

        if passenger and not hasattr(passenger, "billing_info"):
            result['status'] = 'billing_failed'
            result['redirect'] = get_token_url(request) # go to billing
        else:
            result['status'] = 'auth_failed'

    logging.info("book ride result: %s" % result)
    return JSONResponse(result)
def registration_view(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse(account_view))

    if request.method == "GET":
        BIEvent.log(BIEventType.REGISTRATION_START, request=request)

        title = _("Join WAYbetter")
        return render_to_response("mobile/account_registration.html", locals(), RequestContext(request))

    elif request.method == "POST":
        email = request.POST.get("email")
        phone = request.POST.get("phone")

        try:
            validate_email(email)
        except ValidationError:
            return JSONResponse({"error": _("Invalid email")})

        # fail if email is registered
        if User.objects.filter(username=email).count() > 0:
            notify_by_email("Help! I can't register!", msg="email %s already registered\n%s" % (email, phone))
            return JSONResponse(
                {"account_exists": True, "error": _("This email address was registered by another user.")}
            )

        # fail if phone is registered to more than 1 passenger
        country = Country.objects.get(code=settings.DEFAULT_COUNTRY_CODE)
        existing_passengers = Passenger.objects.filter(phone=phone, country=country)
        if len(existing_passengers) > 1:
            notify_by_email(
                "Help! I can't register!",
                msg="phone %s registered to multiple passengers\n%s" % (phone, existing_passengers),
            )
            return JSONResponse(
                {
                    "failed": True,
                    "error": _(
                        "This phone number is registered to multiple passengers. Please contact support for help."
                    ),
                }
            )

        # fail if phone is registered to 1 passenger but this passenger has a user
        existing_passengers_users = [existing_passenger.user for existing_passenger in existing_passengers]
        if any(existing_passengers_users):
            notify_by_email(
                "Help! I can't register!",
                msg="phone %s already registered to another user\n%s\n%s" % (phone, email, existing_passengers_users),
            )
            return JSONResponse(
                {
                    "failed": True,
                    "error": _("This phone number was registered by another user. Please contact support for help."),
                }
            )

        # by now we know:
        # 1. email is not registered; we will create a new user
        # 2. phone is not registered; we will create a new passenger
        #   OR
        # 3. phone registered to a passenger with NO user; we will keep the passenger and create a user for her
        passenger = existing_passengers[0] if existing_passengers else None
        user = register_new_user(request, passenger)
        if user:
            redirect = settings.CLOSE_CHILD_BROWSER_URI
            return JSONResponse({"redirect": redirect, "billing_url": (get_token_url(request))})
        else:
            return JSONResponse({"error": _("Registration failed")})

    else:
        return HttpResponseNotAllowed(request.method)
def get_billing_url(request):
    return JSONResponse({"billing_url": (get_token_url(request))})
Example #9
0
def registration_view(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse(account_view))

    if request.method == 'GET':
        BIEvent.log(BIEventType.REGISTRATION_START, request=request)

        title = _("Join WAYbetter")
        return render_to_response("mobile/account_registration.html", locals(),
                                  RequestContext(request))

    elif request.method == 'POST':
        email = request.POST.get("email")
        phone = request.POST.get("phone")

        try:
            validate_email(email)
        except ValidationError:
            return JSONResponse({'error': _("Invalid email")})

        # fail if email is registered
        if User.objects.filter(username=email).count() > 0:
            notify_by_email("Help! I can't register!",
                            msg="email %s already registered\n%s" %
                            (email, phone))
            return JSONResponse({
                'account_exists':
                True,
                'error':
                _("This email address was registered by another user.")
            })

        # fail if phone is registered to more than 1 passenger
        country = Country.objects.get(code=settings.DEFAULT_COUNTRY_CODE)
        existing_passengers = Passenger.objects.filter(phone=phone,
                                                       country=country)
        if len(existing_passengers) > 1:
            notify_by_email(
                "Help! I can't register!",
                msg="phone %s registered to multiple passengers\n%s" %
                (phone, existing_passengers))
            return JSONResponse({
                'failed':
                True,
                'error':
                _("This phone number is registered to multiple passengers. Please contact support for help."
                  )
            })

        # fail if phone is registered to 1 passenger but this passenger has a user
        existing_passengers_users = [
            existing_passenger.user
            for existing_passenger in existing_passengers
        ]
        if any(existing_passengers_users):
            notify_by_email(
                "Help! I can't register!",
                msg="phone %s already registered to another user\n%s\n%s" %
                (phone, email, existing_passengers_users))
            return JSONResponse({
                'failed':
                True,
                'error':
                _("This phone number was registered by another user. Please contact support for help."
                  )
            })

        # by now we know:
        # 1. email is not registered; we will create a new user
        # 2. phone is not registered; we will create a new passenger
        #   OR
        # 3. phone registered to a passenger with NO user; we will keep the passenger and create a user for her
        passenger = existing_passengers[0] if existing_passengers else None
        user = register_new_user(request, passenger)
        if user:
            redirect = settings.CLOSE_CHILD_BROWSER_URI
            return JSONResponse({
                'redirect': redirect,
                'billing_url': (get_token_url(request))
            })
        else:
            return JSONResponse({'error': _("Registration failed")})

    else:
        return HttpResponseNotAllowed(request.method)
Example #10
0
def get_billing_url(request):
    return JSONResponse({'billing_url': (get_token_url(request))})