Permalink
Browse files

endd

  • Loading branch information...
ButuzGOL committed Apr 22, 2010
1 parent 411199f commit 0c051f64f3f24ea47ddeb9e52bdbee6fa147c44d

Large diffs are not rendered by default.

Oops, something went wrong.
View
@@ -1,8 +1,24 @@
from django import forms
from ecomstore.accounts.models import UserProfile
+from django.contrib.auth.forms import UserCreationForm
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
exclude = ('user',)
+
+class RegistrationForm(UserCreationForm):
+ password1 = forms.RegexField(label="Password", regex=r'^(?=.*\W+).*$',
+ help_text='Password must be six characters \
+ long and contain at least one \
+ non-alphanumeric character.',
+ widget=forms.PasswordInput, min_length=6,
+ #render_value=False
+ )
+ password2 = forms.RegexField(label="Password confirmation",
+ regex=r'^(?=.*\W+).*$',
+ widget=forms.PasswordInput, min_length=6,
+ #render_value=False
+ )
+ email = forms.EmailField(max_length="50")
View
@@ -3,16 +3,21 @@
from django.shortcuts import render_to_response, get_object_or_404
from django.core import urlresolvers
from django.http import HttpResponseRedirect
+from ecomstore.accounts.forms import UserProfileForm, RegistrationForm
from ecomstore.checkout.models import Order, OrderItem
from django.contrib.auth.decorators import login_required
def register(request, template_name="registration/register.html"):
if request.method == 'POST':
postdata = request.POST.copy()
- form = UserCreationForm(postdata)
+ #form = UserCreationForm(postdata)
+ form = RegistrationForm(postdata)
if form.is_valid():
- form.save()
+ user = form.save(commit=False)
+ user.email = postdata.get('email','')
+ user.save()
+ #form.save()
un = postdata.get('username', '')
pw = postdata.get('password1', '')
from django.contrib.auth import login, authenticate
@@ -22,7 +27,8 @@ def register(request, template_name="registration/register.html"):
url = urlresolvers.reverse('my_account')
return HttpResponseRedirect(url)
else:
- form = UserCreationForm()
+ form = RegistrationForm()
+ #form = UserCreationForm()
page_title = 'User Registration'
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
View
@@ -0,0 +1,14 @@
+import os, sys
+# path to directory of the .wsgi file ('apache/')
+wsgi_dir = os.path.abspath(os.path.dirname(__file__))
+# path to project root directory (parent of 'apache/')
+project_dir = os.path.dirname(wsgi_dir)
+# add project directory to system’s PATH
+sys.path.append(project_dir)
+# add the settings.py file to your system's PATH
+project_settings = os.path.join(project_dir,'settings')
+# explicitly define the DJANGO_SETTINGS_MODULE
+os.environ['DJANGO_SETTINGS_MODULE'] = 'ecomstore.settings'
+
+import django.core.handlers.wsgi
+application = django.core.handlers.wsgi.WSGIHandler()
View
No changes.
View
@@ -0,0 +1,36 @@
+from ecomstore.billing.models import Card
+from django import forms
+from datetime import datetime
+
+month_choice = [ ]
+
+# month_choice.append(('','- Month -'))
+for i in range(1, 13):
+ if len(str(i)) == 1:
+ numeric = '0' + str(i)
+ else:
+ numeric = str(i)
+ month_choice.append((numeric, datetime(2009, i, 1).strftime('%B')))
+MONTHS = tuple(month_choice)
+calendar_years = [ ]
+
+# calendar_years.append(('','- Year -'))
+for i in range(datetime.now().year, datetime.now().year + 10):
+ calendar_years.append((i,i))
+YEARS = tuple(calendar_years)
+
+class CardForm(forms.ModelForm):
+ CARD_TYPES = (('Visa', 'Visa'),
+ ('Amex', 'Amex'),
+ ('Discover', 'Discover'),
+ ('Mastercard', 'Mastercard'),)
+
+ class Meta:
+ model = Card
+ exclude = ('data','num', 'user')
+
+ cardholder_name = forms.CharField(max_length=100)
+ card_number = forms.CharField(max_length=20)
+ card_type = forms.ChoiceField(choices=CARD_TYPES)
+ card_expire_month = forms.ChoiceField(choices=MONTHS)
+ card_expire_year = forms.ChoiceField(choices=YEARS)
View
@@ -0,0 +1,14 @@
+from django.db import models
+from django.contrib.auth.models import User
+
+class Card(models.Model):
+ data = models.CharField(max_length=500)
+ user = models.ForeignKey(User)
+ num = models.CharField(max_length=4)
+
+ @property
+ def display_number(self):
+ return u'xxxx-xxxx-xxxx-' + unicode(self.num)
+
+ def __unicode__(self):
+ return unicode(self.user.username) + ' - ' + self.display_number
View
@@ -0,0 +1,16 @@
+from ecomstore.settings import CURRENT_PATH
+from keyczar import keyczar
+import os
+
+KEY_PATH = os.path.join(CURRENT_PATH, 'keys')
+
+def encrypt(plaintext):
+ crypter = _get_crypter()
+ return crypter.Encrypt(plaintext)
+
+def decrypt(ciphertext):
+ crypter = _get_crypter()
+ return crypter.Decrypt(ciphertext)
+
+def _get_crypter():
+ return keyczar.Crypter.Read(KEY_PATH)
View
@@ -0,0 +1,9 @@
+from django.test import TestCase, Client
+from ecomstore.billing.passkey import encrypt, decrypt
+
+class EncryptionTestCase(TestCase):
+
+ def test_encrypt_decrypt(self):
+ to_encrypt = 'Some text here'
+ self.failUnlessEqual(to_encrypt, decrypt(encrypt(to_encrypt)))
+ self.failIfEqual(to_encrypt, encrypt(to_encrypt))
View
@@ -0,0 +1,5 @@
+from django.conf.urls.defaults import *
+
+urlpatterns = patterns('ecomstore.billing.views',
+ (r'^add_card/$', 'add_card'),
+)
View
@@ -0,0 +1,32 @@
+from django.shortcuts import render_to_response
+from django.core import serializers
+from django.utils import simplejson
+from django.template import RequestContext
+from django.contrib.auth.decorators import login_required
+from ecomstore.billing.forms import CardForm
+from ecomstore.billing import passkey
+
+@login_required
+def add_card(request):
+ if request.method == 'POST':
+ post_data = request.POST.copy()
+ # convert the POST variables into JSON format
+ post_data.__delitem__('csrfmiddlewaretoken')
+ json_data = simplejson.dumps(post_data)
+ # encrypt the JSON
+ encrypted_json = passkey.encrypt(json_data)
+ # retrieve the encrypted JSON
+ decrypted_json = passkey.decrypt(encrypted_json)
+ # convert the decrypted JSON into a dictionary
+ decrypted_data = simplejson.loads(decrypted_json)
+ # store the newly encrypted data as a Card instance
+ form = CardForm(post_data)
+ card = form.save(commit=False)
+ card.user = request.user
+ card.num = post_data.get('card_number')[-4:]
+ card.data = encrypted_json
+ card.save()
+ else:
+ form = CardForm()
+ return render_to_response("billing/add_card.html", locals(),
+ context_instance=RequestContext(request))
View
No changes.
View
@@ -0,0 +1,10 @@
+from django.core.cache import cache
+from ecomstore.settings import CACHE_TIMEOUT
+
+def cache_update(sender, **kwargs):
+ item = kwargs.get('instance')
+ cache.set(item.cache_key, item, CACHE_TIMEOUT)
+
+def cache_evict(sender, **kwargs):
+ item = kwargs.get('instance')
+ cache.delete(item.cache_key)
View
@@ -0,0 +1,3 @@
+from django.db import models
+
+# Create your models here.
View
@@ -0,0 +1,23 @@
+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+ def test_basic_addition(self):
+ """
+ Tests that 1 + 1 always equals 2.
+ """
+ self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+
View
@@ -0,0 +1 @@
+# Create your views here.
View
@@ -96,3 +96,24 @@ def empty_cart(request):
user_cart = get_cart_items(request)
user_cart.delete()
+
+from django.conf import settings
+from django.db.models import Max
+from ecomstore.settings import SESSION_AGE_DAYS
+from datetime import datetime, timedelta
+
+def remove_old_cart_items():
+ print "Removing old carts"
+ # calculate date of SESSION_AGE_DAYS days ago
+ remove_before = datetime.now() + timedelta(days=-settings.SESSION_AGE_DAYS)
+ cart_ids = [ ]
+ old_items = CartItem.objects.values('cart_id'). \
+ annotate(last_change=Max('date_added')). \
+ filter(last_change__lt=remove_before).order_by()
+ # create a list of cart IDs that havent been modified
+ for item in old_items:
+ cart_ids.append(item['cart_id'])
+ to_remove = CartItem.objects.filter(cart_id__in=cart_ids)
+ # delete those CartItem instances
+ to_remove.delete()
+ print str(len(cart_ids)) + " carts were removed"
No changes.
No changes.
@@ -0,0 +1,9 @@
+from django.core.management.base import NoArgsCommand
+from ecomstore.cart import cart
+
+class Command(NoArgsCommand):
+
+ help = "Delete shopping cart items more than SESSION_AGE_DAYS days old"
+
+ def handle_noargs(self, **options):
+ cart.remove_old_cart_items()
View
@@ -1,23 +1,71 @@
-"""
-This file demonstrates two different styles of tests (one doctest and one
-unittest). These will both pass when you run "manage.py test".
+from ecomstore.catalog.models import Product
+from ecomstore.cart.models import CartItem
+from ecomstore.cart import cart
+from django.test import TestCase, Client
+from django.core import urlresolvers
+from django.db import IntegrityError
+from django.contrib import csrf
+from django.conf import settings
+import httplib
-Replace these with more appropriate tests for your application.
-"""
+class CartTestCase(TestCase):
+ def setUp(self):
+ self.client = Client()
+ self.product = Product.active.all()[0]
+
+ def test_cart_id(self):
+ home_url = urlresolvers.reverse('catalog_home')
+ self.client.get(home_url)
+ # check that there is a cart_id set in session
+ # after a page with cart box has been requested
+ self.failUnless(self.client.session.get(cart.CART_ID_SESSION_KEY, ''))
+
+ def test_add_product(self):
+ QUANTITY = 2
+ product_url = self.product.get_absolute_url()
+ response = self.client.get(product_url)
+ self.assertEqual(response.status_code, httplib.OK )
+ # store count in cart_count variable
+ cart_item_count = self.get_cart_item_count()
+ # assert that the cart item count is zero
+ self.failUnlessEqual(cart_item_count, 0)
+ # perform the post of adding to the cart
+ cookie = self.client.cookies[settings.SESSION_COOKIE_NAME]
+ csrf_token = csrf.middleware._make_token(cookie.value)
+ postdata = {'product_slug': self.product.slug,
+ 'quantity': QUANTITY,
+ 'csrfmiddlewaretoken': csrf_token }
+ response = self.client.post(product_url, postdata )
+ # assert redirected to cart page - 302 then 200
+ cart_url = urlresolvers.reverse('show_cart')
+ self.assertRedirects(response, cart_url, status_code=httplib.FOUND,
+ target_status_code=httplib.OK)
+ # assert cart item count is incremented by one
+ self.assertEqual(self.get_cart_item_count(), cart_item_count + 1)
+ cart_id = self.get_cart_id()
+ last_item = CartItem.objects.filter(cart_id=cart_id). \
+ latest('date_added')
+ # assert the latest cart item has a quantity of two
+ self.failUnlessEqual(last_item.quantity, QUANTITY)
+ # assert the latest cart item is the correct product
+ self.failUnlessEqual(last_item.product, self.product)
+
+ def get_cart_item_count(self):
+ cart_id = self.get_cart_id()
+ return CartItem.objects.filter(cart_id=cart_id).count()
+
+ def get_cart_id(self):
+ return self.client.session.get(cart.CART_ID_SESSION_KEY)
-from django.test import TestCase
-
-class SimpleTest(TestCase):
- def test_basic_addition(self):
- """
- Tests that 1 + 1 always equals 2.
- """
- self.failUnlessEqual(1 + 1, 2)
-
-__test__ = {"doctest": """
-Another way to test that 1 + 1 is equal to 2.
-
->>> 1 + 1 == 2
-True
-"""}
+ def test_add_to_cart_fails_csrf(self):
+ quantity = 2
+ product_url = self.product.get_absolute_url()
+ response = self.client.get(product_url)
+ self.assertEqual(response.status_code, httplib.OK )
+ # perform the post of adding to the cart
+ postdata = {'product_slug': self.product.slug,
+ 'quantity': quantity }
+ response = self.client.post(product_url, postdata )
+ # assert forbidden error due to missing CSRF input
+ self.assertEqual(response.status_code, httplib.FORBIDDEN )
View
@@ -2,4 +2,4 @@
urlpatterns = patterns('ecomstore.cart.views',
(r'^$', 'show_cart', { 'template_name': 'cart/cart.html' }, 'show_cart'),
-)
+)
View
@@ -21,4 +21,4 @@ def show_cart(request, template_name):
# for Google Checkout button
merchant_id = settings.GOOGLE_CHECKOUT_MERCHANT_ID
return render_to_response(template_name, locals(),
- context_instance=RequestContext(request))
+ context_instance=RequestContext(request))
Oops, something went wrong.

0 comments on commit 0c051f6

Please sign in to comment.