Skip to content
This repository was archived by the owner on Dec 15, 2022. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion calloway/apps/api/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class TagHandler(BaseHandler):

def read(self, request):
if 'referer' in request.GET:
bits = filter(None, request.GET['referer'].replace('/admin/','').split('/'))
bits = [_f for _f in request.GET['referer'].replace('/admin/','').split('/') if _f]
model = get_model(*bits[:2])

if len(bits) == 2:
Expand Down
29 changes: 29 additions & 0 deletions calloway/apps/api/handlers.py.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from piston.handler import BaseHandler
from tagging.models import Tag
from django.db.models import get_model

class TagHandler(BaseHandler):
allowed_methods = ('GET',)
model = Tag

def read(self, request):
if 'referer' in request.GET:
bits = filter(None, request.GET['referer'].replace('/admin/','').split('/'))
model = get_model(*bits[:2])

if len(bits) == 2:
r = []
for x in Tag.objects.cloud_for_model(model):
r.append({'size':x.font_size,'name':x.name})
return r
elif len(bits) == 3:
if bits[2] == 'add':
return []
obj = model.objects.get(pk=bits[2])
tags = Tag.objects.get_for_object(obj)
if 'tags' in request.GET:
obj.tags = request.GET['tags']
else:
return tags


2 changes: 1 addition & 1 deletion calloway/apps/api/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.conf.urls.defaults import *
from piston.resource import Resource
from handlers import TagHandler
from .handlers import TagHandler

tag_handler = Resource(TagHandler)

Expand Down
9 changes: 9 additions & 0 deletions calloway/apps/api/urls.py.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.conf.urls.defaults import *
from piston.resource import Resource
from handlers import TagHandler

tag_handler = Resource(TagHandler)

urlpatterns = patterns('',
url(r'^tags/?$', tag_handler),
)
12 changes: 6 additions & 6 deletions calloway/apps/custom_registration/backends/email/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from registration import signals
from registration.models import RegistrationProfile, SHA1_RE
from registration.backends.default import DefaultBackend
from forms import EmailRegistrationForm
from .forms import EmailRegistrationForm

class EmailOrUserNameAuthenticationBackend(ModelBackend):
"""
Expand Down Expand Up @@ -208,21 +208,21 @@ def handle_expired_accounts():
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)

to_delete = []
print "Processing %s registration profiles..." % str(RegistrationProfile.objects.all().count())
print("Processing %s registration profiles..." % str(RegistrationProfile.objects.all().count()))
for profile in RegistrationProfile.objects.all():
# if registration profile is expired, deactive user.
print "Processing %s" % profile.user
print("Processing %s" % profile.user)
# If profile has been activated already, set it to be removed
# and move on to next registration profile
if profile.activation_key == ACTIVATED:
print "Found Active"
print("Found Active")
to_delete.append(profile.pk)
continue

# If the user has not activated their account and the activation
# days have passed, deactivate the user and send an email to user.
if profile.user.is_active and profile.user.date_joined + expiration_date <= datetime.datetime.now():
print "Found Expired"
print("Found Expired")
user = profile.user
user.is_active = False

Expand All @@ -246,5 +246,5 @@ def handle_expired_accounts():

# Delete the registration profiles that were set to be deleted, aka
# user has already activated their account.
print "Deleting %s registration profiles." % str(len(to_delete))
print("Deleting %s registration profiles." % str(len(to_delete)))
RegistrationProfile.objects.filter(pk__in=to_delete).delete()
250 changes: 250 additions & 0 deletions calloway/apps/custom_registration/backends/email/__init__.py.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
import random, datetime

from django.db import models
from django.conf import settings
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
from django.template.loader import render_to_string
from django.utils.hashcompat import sha_constructor
from django.core.mail import send_mail

from registration import signals
from registration.models import RegistrationProfile, SHA1_RE
from registration.backends.default import DefaultBackend
from forms import EmailRegistrationForm

class EmailOrUserNameAuthenticationBackend(ModelBackend):
"""
Authenticates a user against a username or email address.
"""
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
try:
user = User.objects.get(email__iexact=username)
except User.DoesNotExist:
return None

if user and user.check_password(password):
return user
return None


class EmailBackend(DefaultBackend):
"""
Allow registration with email address. Upon suppling only an email
address, the user will have an active account and be logged in. User
will then have a certain amount of days in which there account will
stay active.

User's session will be set to 0 (browser close) timer, from which then
they will have to view the sent email to retrieve the generated password.

User's account will become inactive after the specified days have passed.
From there they will need to click an activation link, sent initially with
there generated password, in order to keep account active.

A managment command is provided to check if accounts have passed ther
expiration date and will set user as inactive.

[custom_registration.managment.commands.check_expired_accounts.py]

./manage.py check_expired_accounts
"""
def activate(self, request, activation_key):
"""
Override default activation process. This will activate the user
even if its passed its expiration date.
"""
if SHA1_RE.search(activation_key):
try:
profile = RegistrationProfile.objects.get(activation_key=activation_key)
except RegistrationProfile.DoesNotExist:
return False

user = profile.user
user.is_active = True
user.save()
profile.activation_key = RegistrationProfile.ACTIVATED
profile.save()
return user
return False

def register(self, request, **kwargs):
"""
Create and immediately log in a new user.

Only require a email to register, username is generated
automatically and a password is random generated and emailed
to the user.

Activation is still required for account uses after specified number
of days.
"""
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)

email = kwargs['email']

# Generate random password
password = User.objects.make_random_password()

# Generate username based off of the email supplied
username = sha_constructor(str(email)).hexdigest()[:30]

incr = 0
# Ensure the generated username is in fact unqiue
while User.objects.filter(username=username).count() > 0:
incr += 1
username = sha_constructor(str(email + str(incr))).hexdigest()[:30]
# Create the active user
new_user = User.objects.create_user(username, email, password)
new_user.save()

# Create the registration profile, this is still needed because
# the user still needs to activate there account for further users
# after 3 days
registration_profile = RegistrationProfile.objects.create_profile(
new_user)

# Authenticate and login the new user automatically
auth_user = authenticate(username=username, password=password)
login(request, auth_user)

# Set the expiration to when the users browser closes so user
# is forced to log in upon next visit, this should force the user
# to check there email for there generated password.
request.session.set_expiry(0)

# Create a profile instance for the new user if
# AUTH_PROFILE_MODULE is specified in settings
if hasattr(settings, 'AUTH_PROFILE_MODULE') and getattr(settings, 'AUTH_PROFILE_MODULE'):
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
model = models.get_model(app_label, model_name)
try:
profile = new_user.get_profile()
except model.DoesNotExist:
profile = model(user=new_user)
profile.save()

# Custom send activation email
self.send_activation_email(
new_user, registration_profile, password, site)

# Send user_registered signal
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user

def send_activation_email(self, user, profile, password, site):
"""
Custom send email method to supplied the activation link and
new generated password.
"""
ctx_dict = { 'password': password,
'site': site,
'activation_key': profile.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS}

subject = render_to_string(
'registration/email/emails/password_subject.txt',
ctx_dict)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())

message = render_to_string('registration/email/emails/password.txt',
ctx_dict)

try:
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
except:
pass


def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:

* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.

* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.

"""
return getattr(settings, 'REGISTRATION_OPEN', True)

def get_form_class(self, request):
return EmailRegistrationForm

def post_registration_redirect(self, request, user):
"""
After registration, redirect to the home page or supplied "next"
query string or hidden field value.

"""
next_url = "/registration/register/complete/"
if "next" in request.GET or "next" in request.POST:
next_url = request.GET.get("next", None) or request.POST.get("next", None) or "/"

return (next_url, (), {})


def handle_expired_accounts():
"""
Check of expired accounts.
"""
ACTIVATED = RegistrationProfile.ACTIVATED
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)

to_delete = []
print "Processing %s registration profiles..." % str(RegistrationProfile.objects.all().count())
for profile in RegistrationProfile.objects.all():
# if registration profile is expired, deactive user.
print "Processing %s" % profile.user
# If profile has been activated already, set it to be removed
# and move on to next registration profile
if profile.activation_key == ACTIVATED:
print "Found Active"
to_delete.append(profile.pk)
continue

# If the user has not activated their account and the activation
# days have passed, deactivate the user and send an email to user.
if profile.user.is_active and profile.user.date_joined + expiration_date <= datetime.datetime.now():
print "Found Expired"
user = profile.user
user.is_active = False

# Send an email notifing user of there account becoming inactive.
site = Site.objects.get_current()
ctx_dict = { 'site': site,
'activation_key': profile.activation_key}

subject = render_to_string(
'registration/email/emails/account_expired_subject.txt',
ctx_dict)
subject = ''.join(subject.splitlines())

message = render_to_string(
'registration/email/emails/account_expired.txt',
ctx_dict)
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)

# Only save the user instance after the email is sent.
user.save()

# Delete the registration profiles that were set to be deleted, aka
# user has already activated their account.
print "Deleting %s registration profiles." % str(len(to_delete))
RegistrationProfile.objects.filter(pk__in=to_delete).delete()
4 changes: 2 additions & 2 deletions calloway/apps/django_ext/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
'min_compress_len' in inspect.getargspec(cache._cache.set)[0]:
class CacheClass(cache.__class__):
def add(self, key, value, timeout=None, min_compress_len=150000):
if isinstance(value, unicode):
if isinstance(value, str):
value = value.encode('utf-8')
# Allow infinite timeouts
if timeout is None:
timeout = self.default_timeout
return self._cache.add(smart_str(key), value, timeout, min_compress_len)

def set(self, key, value, timeout=None, min_compress_len=150000):
if isinstance(value, unicode):
if isinstance(value, str):
value = value.encode('utf-8')
if timeout is None:
timeout = self.default_timeout
Expand Down
25 changes: 25 additions & 0 deletions calloway/apps/django_ext/cache.py.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from django.core.cache import cache
from django.utils.encoding import smart_str
import inspect

# Check if the cache backend supports min_compress_len. If so, add it.
if cache._cache:
if 'min_compress_len' in inspect.getargspec(cache._cache.add)[0] and \
'min_compress_len' in inspect.getargspec(cache._cache.set)[0]:
class CacheClass(cache.__class__):
def add(self, key, value, timeout=None, min_compress_len=150000):
if isinstance(value, unicode):
value = value.encode('utf-8')
# Allow infinite timeouts
if timeout is None:
timeout = self.default_timeout
return self._cache.add(smart_str(key), value, timeout, min_compress_len)

def set(self, key, value, timeout=None, min_compress_len=150000):
if isinstance(value, unicode):
value = value.encode('utf-8')
if timeout is None:
timeout = self.default_timeout
self._cache.set(smart_str(key), value, timeout, min_compress_len)

cache.__class__ = CacheClass
Loading