示例#1
0
def view_basket(request):
    ensure_session(request)
    try:
        basket = Basket.objects.get(session_id=request.session.session_key)
    except Basket.DoesNotExist:
        if request.session.get('last_order', None):
            return HttpResponseRedirect(reverse('shop:user_orders'))
        else:
            return HttpResponseRedirect(reverse('shop:empty'))
    phone = basket.phone
    full_phone = None
    user = None
    user_id = None
    if phone:
        norm_phone = ShopUserManager.normalize_phone(phone)
        full_phone = ShopUserManager.format_phone(phone)
        try:
            user = ShopUser.objects.get(phone=norm_phone)
            user_id = user.id
        except ShopUser.DoesNotExist:
            pass

    if FACEBOOK_TRACKING:
        notify_initiate_checkout.delay(basket.id, user_id,
                                       request.build_absolute_uri(),
                                       request.META.get('REMOTE_ADDR'),
                                       request.META['HTTP_USER_AGENT'])
    context = {
        'basket': basket,
        'shop_user': user,
        'phone': phone,
        'full_phone': full_phone,
        'wrong_password': request.GET.get('wrong_password', '0') == '1'
    }
    return render(request, 'shop/basket.html', context)
示例#2
0
def authorize(request):
    ensure_session(request)
    basket = get_object_or_404(Basket, session_id=request.session.session_key)
    phone = request.POST.get('phone')
    password = request.POST.get('password')
    data = None

    if password:
        norm_phone = ShopUserManager.normalize_phone(basket.phone)
        user = authenticate(username=norm_phone, password=password)
        if user and user.is_active:
            login(request, user)
            basket.update_session(request.session.session_key)
            data = {
                'user': user,
            }
        else:
            """ Bad password """
            data = {
                'shop_user': ShopUser.objects.get(phone=norm_phone),
                'wrong_password': True
            }

    if phone:
        norm_phone = ShopUserManager.normalize_phone(phone)
        basket.phone = norm_phone
        basket.save()
        user, created = ShopUser.objects.get_or_create(phone=norm_phone)
        if not created:
            """ Such user exists, request password """
            data = {
                'shop_user': user,
            }
        else:
            """ Generate simple password for new user """
            password = randint(1000, 9999)
            request.session['password'] = password
            user.set_password(password)
            user.save()
            send_password.delay(norm_phone, password)
            """ Login new user """
            user = authenticate(username=norm_phone, password=password)
            login(request, user)
            basket.update_session(request.session.session_key)

    if request.user.is_authenticated and not data:
        if request.POST.get('ajax'):
            return JsonResponse({'location': reverse('shop:confirm')})
        else:
            return HttpResponseRedirect(reverse('shop:confirm'))
    else:
        if request.POST.get('ajax'):
            data = {
                'html': render_to_string('shop/_send_order.html', RequestContext(request, data)),
            }
            return JsonResponse(data)
        elif data and 'wrong_password' in data:
            return HttpResponseRedirect(reverse('shop:basket') + '?wrong_password=1')
        else:
            return HttpResponseRedirect(reverse('shop:basket'))
示例#3
0
def update_user(request):
    user = request.user
    if request.method == 'POST':
        form = UserForm(request.POST, user=user)
        if form.is_valid():
            user.name = form.cleaned_data['name']
            user.phone = ShopUserManager.normalize_phone(
                form.cleaned_data['phone'])
            user.email = form.cleaned_data['email']
            user.address = form.cleaned_data['address']
            user.username = form.cleaned_data['username']
            user.save()
    else:
        form = UserForm(user=user)

    context = {
        'user_form': form,
        'invalid': not form.is_valid(),
        'update': not request.GET.get('update') is None
    }
    if request.GET.get('ajax') or request.POST.get('ajax'):
        data = {
            'html': render_to_string('shop/_update_user.html', context,
                                     request),
        }
        return JsonResponse(data)
    else:
        return render(request, 'shop/_update_user.html', context)
示例#4
0
def reset_password(request):
    """
    Generate new password and send it to user by sms
    """
    ensure_session(request)
    phone = request.GET.get('phone', None)
    if phone:
        phone = ShopUserManager.normalize_phone(phone)
    else:
        basket = get_object_or_404(Basket,
                                   session_id=request.session.session_key)
        if basket.phone:
            phone = basket.phone
    if phone:
        password = str(randint(1000, 9999))
        try:
            user = ShopUser.objects.get(phone=phone)
        except ShopUser.DoesNotExist:
            return HttpResponseNotFound()
        user.set_password(password)
        user.permanent_password = False
        user.save()
        try:
            send_password.delay(phone, password)
        except Exception as e:
            mail_admins('Task error',
                        'Failed to send password: %s' % e,
                        fail_silently=True)
    else:
        """ we can not reset password if phone is not known yet """
        return HttpResponseForbidden()
    if request.GET.get('ajax'):
        return JsonResponse(None, safe=False)
    else:
        return HttpResponseRedirect(reverse('shop:basket'))
示例#5
0
def update_user(request):
    user = request.user
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            user.name = form.cleaned_data['name']
            user.phone = ShopUserManager.normalize_phone(form.cleaned_data['phone'])
            user.email = form.cleaned_data['email']
            user.address = form.cleaned_data['address']
            user.save()
    else:
        form = UserForm(initial=model_to_dict(user))

    context = {
       'user_form': form,
       'invalid': not form.is_valid(),
       'update': not request.GET.get('update') is None
    }
    if request.GET.get('ajax') or request.POST.get('ajax'):
        data = {
            'html': render_to_string('shop/_update_user.html', RequestContext(request, context)),
        }
        return JsonResponse(data)
    else:
        return render(request, 'shop/_update_user.html', context)
示例#6
0
def reset_password(request):
    """
    Generate new password and send it to user by sms
    """
    ensure_session(request)
    phone = request.GET.get('phone', None)
    if phone:
        phone = ShopUserManager.normalize_phone(phone)
    else:
        basket = get_object_or_404(Basket, session_id=request.session.session_key)
        if basket.phone:
            phone = basket.phone
    if phone:
        password = randint(1000, 9999)
        try:
            user = ShopUser.objects.get(phone=phone)
        except ShopUser.DoesNotExist:
            return HttpResponseNotFound()
        user.set_password(password)
        user.save()
        send_password.delay(phone, password)
    else:
        """ we can not reset password if phone is not known yet """
        return HttpResponseForbidden()
    if request.GET.get('ajax'):
        return JsonResponse(None, safe=False)
    else:
        return HttpResponseRedirect(reverse('shop:basket'))
示例#7
0
def login_user(request):
    """
    Login user preserving his basket
    """
    if request.method == 'POST':
        try:
            basket = Basket.objects.get(session_id=request.session.session_key)
        except Basket.DoesNotExist:
            basket = None
        phone = request.POST.get('phone')
        norm_phone = ShopUserManager.normalize_phone(phone)
        password = request.POST.get('password')
        next_url = request.POST.get('next')
        if norm_phone and password:
            user = authenticate(username=norm_phone, password=password)
            if user and user.is_active:
                login(request, user)
                if basket:
                    basket.update_session(request.session.session_key)
                    basket.phone = user.phone
                    basket.save()
                if next_url:
                    return HttpResponseRedirect(next_url)
                else:
                    return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
        context = {
            'phone': phone,
            'next': next_url,
            'wrong_password': True
        }
    else:
        context = {
            'next': request.GET.get('next')
        }
    return render(request, 'shop/login.html', context)
示例#8
0
def view_basket(request):
    ensure_session(request)
    try:
        basket = Basket.objects.get(session_id=request.session.session_key)
    except Basket.DoesNotExist:
        return HttpResponseRedirect(reverse('shop:empty'))
    phone = basket.phone
    full_phone = None
    user = None
    if phone:
        norm_phone = ShopUserManager.normalize_phone(phone)
        full_phone = ShopUserManager.format_phone(phone)
        try:
            user = ShopUser.objects.get(phone=norm_phone)
        except ShopUser.DoesNotExist:
            pass
    context = {
        'basket': basket,
        'shop_user': user,
        'phone': phone,
        'full_phone': full_phone,
        'wrong_password': request.GET.get('wrong_password', '0') == '1'
    }
    return render(request, 'shop/basket.html', context)
示例#9
0
def register_user(request):
    if request.method == 'POST':
        phone = request.POST.get('phone')
        norm_phone = ShopUserManager.normalize_phone(phone)
        next_url = request.POST.get('next')
        if norm_phone:
            try:
                user = ShopUser.objects.get(phone=norm_phone)
                context = {
                    'phone': phone,
                    'email': request.POST.get('email'),
                    'name': request.POST.get('name'),
                    'username': request.POST.get('username'),
                    'next': next_url,
                    'error':
                    'Пользователь с таким телефоном уже зарегистрирован'
                }
            except ShopUser.DoesNotExist:
                # create user, it will be authorized later by login
                try:
                    user = ShopUser(phone=norm_phone)
                    user.email = request.POST.get('email')
                    user.name = request.POST.get('name')
                    user.username = request.POST.get('username')
                    user.save()
                    params = {
                        'phone': norm_phone,
                        'next': next_url,
                        'reg': request.POST.get('reg') or '1'
                    }
                    return HttpResponseRedirect(
                        reverse('shop:login') + '?' + urlencode(params))
                except IntegrityError:
                    logger.exception("An error occurred")
                    context = {
                        'phone': phone,
                        'email': request.POST.get('email'),
                        'name': request.POST.get('name'),
                        'username': request.POST.get('username'),
                        'next': next_url,
                        'error':
                        'Пользователь с таким именем уже зарегистрирован'
                    }
    else:
        context = {'next': request.GET.get('next')}
    return render(request, 'shop/register.html', context)
示例#10
0
def login_user(request):
    """
    Login user preserving his basket
    """
    norm_phone = None
    password = None
    reg = None

    if request.method == 'POST':
        phone = request.POST.get('phone')
        password = request.POST.get('password')
        next_url = request.POST.get('next')
        reg = request.POST.get('reg')
    else:
        phone = request.GET.get('phone')
        next_url = request.GET.get('next')
        reg = request.GET.get('reg')

    if phone:
        norm_phone = ShopUserManager.normalize_phone(phone)

    if norm_phone and password:
        try:
            basket = Basket.objects.get(session_id=request.session.session_key)
        except MultipleObjectsReturned:
            basket = None
        except Basket.DoesNotExist:
            basket = None
        user = authenticate(username=norm_phone, password=password)
        if user and user.is_active:
            permanent_password = request.POST.get('permanent_password')
            if permanent_password:
                user.set_password(permanent_password)
                user.permanent_password = True
                user.save()
            login(request, user)
            if basket:
                basket.update_session(request.session.session_key)
                basket.phone = user.phone
                basket.save()
            if next_url:
                return HttpResponseRedirect(next_url)
            else:
                return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
        try:
            user = ShopUser.objects.get(phone=norm_phone)
        except ShopUser.DoesNotExist:
            user = None
        context = {
            'phone': phone,
            'shop_user': user,
            'next': next_url,
            'reg': reg,
            'wrong_password': True
        }
    elif norm_phone:
        try:
            user = ShopUser.objects.get(phone=norm_phone)
            if not user.permanent_password:
                """ Generate new password for user """
                password = str(randint(1000, 9999))
                user.set_password(password)
                user.save()
                try:
                    if reg != '1':
                        send_password.delay(norm_phone, password)
                except Exception as e:
                    mail_admins('Task error',
                                'Failed to send password: %s' % e,
                                fail_silently=True)
            context = {
                'phone': phone,
                'shop_user': user,
                'reg': reg,
                'next': next_url
            }
        except ShopUser.DoesNotExist:
            context = {
                'phone': phone,
                'next': next_url,
                'reg': reg,
                'error': 'Пользователь с таким телефоном не зарегистрирован'
            }
    else:
        context = {'reg': reg, 'next': request.GET.get('next')}
    return render(request, 'shop/login.html', context)
示例#11
0
def authorize(request):
    ensure_session(request)
    basket = get_object_or_404(Basket, session_id=request.session.session_key)
    phone = request.POST.get('phone')
    password = request.POST.get('password')
    data = None

    if password:
        norm_phone = ShopUserManager.normalize_phone(basket.phone)
        user = authenticate(username=norm_phone, password=password)
        if user and user.is_active:
            login(request, user)
            basket.update_session(request.session.session_key)
            """
            We disabled this because Nikolay wants order to be registered as soon as user authenticates
            data = {
                'user': user,
            }
            """
        else:
            """ Bad password """
            data = {
                'shop_user': ShopUser.objects.get(phone=norm_phone),
                'wrong_password': True
            }

    if phone:
        norm_phone = ShopUserManager.normalize_phone(phone)
        basket.phone = norm_phone
        basket.save()
        user, created = ShopUser.objects.get_or_create(phone=norm_phone)
        if not user.permanent_password:
            """ Generate new password for user """
            password = str(randint(1000, 9999))
            user.set_password(password)
            user.save()
        if created:
            """ Login new user """
            user = authenticate(username=norm_phone, password=password)
            login(request, user)
            basket.update_session(request.session.session_key)
            request.session['password'] = password
        else:
            """ User exists, request password """
            if not user.permanent_password:
                try:
                    send_password.delay(norm_phone, password)
                except Exception as e:
                    mail_admins('Task error',
                                'Failed to send password: %s' % e,
                                fail_silently=True)
            data = {
                'shop_user': user,
            }

    if request.user.is_authenticated and not data:
        if request.POST.get('ajax'):
            return JsonResponse({'location': reverse('shop:confirm')})
        else:
            return HttpResponseRedirect(reverse('shop:confirm'))
    else:
        if request.POST.get('ajax'):
            data = {
                'html': render_to_string('shop/_send_order.html', data,
                                         request),
            }
            return JsonResponse(data)
        elif data and 'wrong_password' in data:
            return HttpResponseRedirect(
                reverse('shop:basket') + '?wrong_password=1')
        else:
            return HttpResponseRedirect(reverse('shop:basket'))
示例#12
0
def update_user_bonuses(self):
    reload_maybe()
    bonused_users = set(
        ShopUser.objects.filter(bonuses__gt=0).values_list('id', flat=True))
    filename = 'БонусныеБаллыИнфо.txt'
    url = 'https://cloud-api.yandex.net/v1/disk/resources?path={}'.format(
        quote('disk:/' + filename))
    headers = {
        'Authorization':
        'OAuth {token}'.format(token=config.sw_bonuses_ydisk_token),
        'Content-Type':
        'application/json; charset=utf-8'
    }
    request = Request(url, None, headers)
    try:
        response = urlopen(request)
        result = json.loads(response.read().decode('utf-8'))
        bonus_file = result.get('file', None)
        bonus_md5 = result.get('md5', None)
        if not bonus_file:
            log.error('No file')
            raise self.retry(countdown=3600, max_retries=4)  # 1 hour
        log.info('Getting file %s' % bonus_file)
        request = Request(bonus_file, None, headers)
        response = urlopen(request)
        result = response.read()
        md5 = hashlib.md5(result).hexdigest()
        if md5 != bonus_md5:
            log.error('MD5 checksums differ')
            raise self.retry(countdown=3600, max_retries=4)  # 1 hour
        num = 0
        records = csv.DictReader(io.StringIO(result.decode('windows-1251')),
                                 delimiter=';')
        log.info('Processing file')
        for line in records:
            try:
                if line['ШтрихКод'] and line['КоличествоБаллов']:
                    bonuses = float(line['КоличествоБаллов'].replace(
                        '\xA0', '').replace(' ', '').replace(',', '.'))
                    if bonuses < 0:
                        continue
                    user, created = ShopUser.objects.get_or_create(
                        phone=ShopUserManager.normalize_phone(
                            line['ШтрихКод']))
                    user.bonuses = int(bonuses)
                    if not created:
                        bonused_users.discard(user.id)
                    if line['КСписанию']:
                        expiring_bonuses = float(line['КСписанию'].replace(
                            '\xA0', '').replace(' ', '').replace(',', '.'))
                        user.expiring_bonuses = int(expiring_bonuses)
                        if line['ДатаСписания']:
                            expiration_date = datetime.strptime(
                                line['ДатаСписания'], '%d.%m.%Y %H:%M:%S')
                            user.expiration_date = timezone.make_aware(
                                expiration_date)
                    if not user.name:
                        name = line['ФИО']
                        if name and not name.startswith('Держатель карты'):
                            name = re.sub(r'[:,]?\s?(?:Штрихкод)?:?\s?\d+', '',
                                          name)
                            user.name = name.title()
                    user.save()
                    num = num + 1
            except ValueError:
                log.error("Wrong bonus number '%s' for '%s'" %
                          (line['КоличествоБаллов'], line['ШтрихКод']))
        for user_id in bonused_users:
            user = ShopUser.objects.get(pk=user_id)
            user.bonuses = 0
            user.save()
            num = num + 1
        return num
    except HTTPError as e:
        content = e.read()
        error = json.loads(content.decode('utf-8'))
        message = error.get(
            'message', 'Неизвестная ошибка взаимодействия с Яндекс.Диском')
        log.error(message)
        raise self.retry(countdown=60 * 10, max_retries=12,
                         exc=e)  # 10 minutes
    return 0
示例#13
0
def format_phone(value):
    result = ShopUserManager.format_phone(value)
    return mark_safe(result)
示例#14
0
def format_phone(value):
    result = ShopUserManager.format_phone(value)
    return mark_safe(result)