Sergey Maranchuk avatar Sergey Maranchuk committed f308986

added activation_required decorator, removed NinjaPaginator depension, fix form if UNIQUE_USERNAME=True, added uses.html template

Comments (0)

Files changed (9)

-.*\.pyc
+syntax: glob
+*.pyc
 django_openauth.egg-info
+*.kpf

openauth/admin.py

 from django.contrib import admin
-from openauth.models import Profile
+from openauth.models import Profile, Confirmation
 
 
 class ProfileAdmin(admin.ModelAdmin):
     pass
+
+class ConfirmationAdmin(admin.ModelAdmin):
+    pass
+
 admin.site.register(Profile, ProfileAdmin)
+admin.site.register(Confirmation, ConfirmationAdmin)
 

openauth/forms.py

     password = PasswordField(label=_('Password'))
     password_dup = PasswordField(label=_('Password (confirmation)'))
 
-    
+
     def clean_email(self):
         if get_object_or_None(User, email=self.cleaned_data['email'].lower()):
             raise forms.ValidationError(_(u'This email already registered'))
         return self.cleaned_data['email']
 
-    
+
+    def clean_username(self):
+        if openauth.settings.UNIQUE_USERNAME:
+            if get_object_or_None(User, username=self.cleaned_data['username']):
+                raise forms.ValidationError(_(u'This username already registered'))
+        return self.cleaned_data['username']
+
+
     def clean(self):
         pwd1 = self.cleaned_data.get('password')
         pwd2 = self.cleaned_data.get('password_dup')

openauth/models.py

                                     })
         return openauth.settings.GRAVATAR_URL
 
-    
+
     def __unicode__(self):
         return self.user.username
 

openauth/templates/openauth/registration.html

 {% extends 'base.html' %}
 {% block content %}
 <form action='.' method='post'>
-{{ form.as_table }}
+    <table>
+        {{ form.as_table }}
+    </table>
 <input type='submit' value='submit' />
 </form>
 {% endblock %}

openauth/templates/openauth/users.html

+{% extends 'base.html' %}
+{% block content %}
+{% for user in users %}
+    {{ user }} <br/>
+{% endfor %}
+{% endblock %}
     url(r'^reset_password/$', views.reset_password, name='openauth-reset-password'),
     url(r'^change_password/$', views.change_password, name='openauth-change-password'),
     url(r'^confirm/$', views.confirm, name='openauth-confirm'),
-    url(r'^user/(\d+)/$', views.show_user, name='show-user'),
+    url(r'^user/(\d+)/$', views.show_user, name='openauth-show-user'),
+    url(r'^users/$', views.users, name='openauth-show-users'),
     #url(r'^edit/(\d+)/$', views.edit_user, name='edit-user'),
     #url(r'^email_changed/$', views.email_changed, name='auth_email_changed'),
 )

openauth/utils.py

+from functools import wraps
+
+from django.shortcuts import redirect
+from django.utils.translation import ugettext as _
+from django.conf import settings
+
+import openauth
+
 def unicode_urlencode(params):
     """A unicode aware version of urllib.urlencode"""
     from urllib import urlencode
 
 def generate_hash(string=None):
     import time
-    try:                                                           
-        from hashlib import md5                                    
-    except ImportError:                                            
-        import md5                                                 
+    try:
+        from hashlib import md5
+    except ImportError:
+        import md5
         md5 = md5.new
 
     if not string:
-        string = str(time.time())
+        print dir(settings)
+        string = str(time.time()) + settings.SECRET_KEY
     hash = md5(string).hexdigest()
     return hash
 
 
 
 def parse_template(template_path, **kwargs):
-    """                                     
-    Load and render template.               
+    """
+    Load and render template.
 
     First line of template should contain the subject of email.
-    Return tuple with subject and content.                     
-    """                                                        
+    Return tuple with subject and content.
+    """
     import re
 
     from django.template.loader import get_template
     from django.template import Context
 
     template = get_template(template_path)
-    context = Context(kwargs)             
+    context = Context(kwargs)
     data = template.render(context).strip()
     subject, content = re.split(r'\r?\n', data, 1)
-    return (subject.strip(), content.strip())     
+    return (subject.strip(), content.strip())
 
 
 def email_template(rcpt, template_path, **kwargs):
     **kwargs may contain variables for template rendering.
     """
     from django.conf import settings
-    from django.core.mail import send_mail 
+    from django.core.mail import send_mail
 
     subject, content = parse_template(template_path, **kwargs)
     count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
                       [rcpt], fail_silently=True)
     return bool(count)
 
+
 def str_to_class(str):
     mod_str, cls_str = str.rsplit('.', 1)
     mod = __import__(mod_str, globals(), locals(), ['foobar'])
     cls = getattr(mod, cls_str)
     return cls
+
+
+def message(request, msg, priority, redirect_name, args=[], kwargs={}):
+    """
+    Shortcut that prepare data for message view.
+    """
+    if openauth.settings.MESSAGE_TYPE == 'flash':
+        request.flash[priority] = msg
+        return redirect(redirect_name, *args, **kwargs)
+    return {'TEMPLATE': 'openauth/message.html', 'message': msg}
+
+
+def activation_required(view_func):
+    """
+    Decorator for views that checks is registration allowed and
+    is user olready authenticated
+    """
+    @wraps(view_func)
+    def wrapper(request, *args, **kwargs):
+        if request.user.is_authenticated():
+            return message(request, _('You have to logout before registration'), 'notice', '/')
+        if not openauth.settings.REGISTRATION_ALLOWED:
+            request.flash['notice'] = _('Sorry. Registration is disabled.')
+            return message(request, _('We are sorry, but registration is disabled. Come back later'), 'notice', '/')
+        return view_func(request, *args, **kwargs)
+    return wrapper

openauth/views.py

 import time
-
 from datetime import datetime, timedelta, date
 
 from django.conf import settings
 from django.core.urlresolvers import reverse
 from django.contrib.auth.decorators import login_required
 from django.contrib import auth 
-from django.shortcuts import get_object_or_404, redirect
+from django.shortcuts import get_object_or_404
 from django.utils.translation import ugettext as _
 from django.http import HttpResponseRedirect
 from django.db.models import Q
 
 from annoying.decorators import ajax_request, render_to
-from ninjapaginator.util import NinjaPaginator
-
-
-import openauth                          
+import openauth
 from openauth.forms import RestorePasswordForm, NewPasswordForm, LoginForm, NewEmailForm, EditUserForm
-from openauth.utils import email_template, build_redirect_url, str_to_class, generate_hash
+from openauth.utils import email_template, build_redirect_url, str_to_class, \
+    generate_hash, activation_required, message
 from openauth.models import Confirmation
 
 
-def message(request, msg, priority, redirect_name, args=[], kwargs={}):
-    """
-    Shortcut that prepare data for message view.
-    """
-    if openauth.settings.MESSAGE_TYPE == 'flash':
-        request.flash[priority] = msg
-        return redirect(redirect_name, *args, **kwargs)
-    return {'TEMPLATE': 'openauth/message.html', 'message': msg}
-
-
 @render_to()
 def confirm(request):
     """
 
 
 @render_to('openauth/registration.html')
+@activation_required
 def registration(request):
     """
     Only anonymous users can view this page
     Registration should be allowed in REGISTRATION_ALLOWED setting
     """
-    if request.user.is_authenticated():
-        return message(request, _('You have to logout before registration'), 'notice', '/')
-
-    if not openauth.settings.REGISTRATION_ALLOWED: 
-        request.flash['notice'] = 'Sorry. Registration is disabled.'
-        return message(request, _('We are sorry, but registration is disabled. Come back later'), 'notice', '/')
 
     if request.POST:
         form = str_to_class(openauth.settings.REGISTRATION_FORM)(request.POST)
     """
     Show user profile 
     """
-    
+
     user = get_object_or_404(User, pk=user_id)
     return {'user': user}
 
- 
 
+@render_to('openauth/users.html')
+def users(request):
+    users = User.objects.filter(is_active=True).all()
+    return {'users': users}
 
-@render_to('account/users.html')
-@NinjaPaginator(style='filmfeed', per_page=16) 
-def users(request):
-    users = User.objects.all()
-    users = order_by(request, users)
-    return {'object_list': users}
-
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.