Permalink
Browse files

upgrade to django 1.3, add user login

  • Loading branch information...
1 parent 37efbb0 commit eb41c1ef616eec72fa9a9a8960fbf0b532373ad5 @invalid-email-address invalid-email-address committed with Jun 15, 2011
View
132 mainapp/forms.py
@@ -2,20 +2,26 @@
from django.template.loader import render_to_string
from django.core.mail import send_mail
from fixmystreet import settings
-from mainapp.models import Ward, Report, ReportUpdate, ReportCategoryClass,ReportCategory,ReportSubscriber,DictToPoint
-from django.utils.translation import ugettext_lazy
+from django.conf import settings
+from mainapp.models import Ward, Report, ReportUpdate, ReportCategoryClass,ReportCategory,ReportSubscriber,DictToPoint,UserProfile
+from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.geos import fromstr
from django.forms.util import ErrorDict
+from registration.forms import RegistrationForm
+from registration.models import RegistrationProfile
+from django.contrib.auth.models import User
+from django.contrib.auth.forms import AuthenticationForm
+from django.contrib.sites.models import Site
class ContactForm(forms.Form):
name = forms.CharField(max_length=100,
widget=forms.TextInput(attrs={ 'class': 'required' }),
- label=ugettext_lazy('Name'))
+ label=_('Name'))
email = forms.EmailField(widget=forms.TextInput(attrs=dict({ 'class': 'required' },
maxlength=200)),
- label=ugettext_lazy('Email'))
+ label=_('Email'))
body = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'required' }),
- label=ugettext_lazy('Message'))
+ label=_('Message'))
def save(self, fail_silently=False):
message = render_to_string("emails/contact/message.txt", self.cleaned_data )
@@ -32,6 +38,11 @@ class ReportSubscriberForm(forms.ModelForm):
class Meta:
model = ReportSubscriber
fields = ( 'email', )
+
+ def __init__(self,data=None,files=None,initial=None, freeze_email=False):
+ super(ReportSubscriberForm,self).__init__(data,files=files, initial=initial)
+ if freeze_email:
+ self.fields['email'].widget.attrs['readonly'] = 'readonly'
"""
Do some pre-processing to
@@ -60,7 +71,8 @@ def __init__(self, ward=None,required=True, widget=None, label=None,
groups[catclass].append((category.pk, category.name ))
for catclass, values in groups.items():
choices.append((catclass,values))
- super(CategoryChoiceField,self).__init__(choices,required,widget,label,initial,help_text,args,kwargs)
+
+ super(CategoryChoiceField,self).__init__(choices=choices,required=required,widget=widget,label=label,initial=initial,help_text=help_text,*args,**kwargs)
def clean(self, value):
super(CategoryChoiceField,self).clean(value)
@@ -71,11 +83,21 @@ def clean(self, value):
return model
+class EditProfileForm(forms.ModelForm):
+ class Meta:
+ model = UserProfile
+ fields = ( 'phone',)
+
class ReportUpdateForm(forms.ModelForm):
class Meta:
model = ReportUpdate
fields = ( 'desc','author','email','phone')
+ def __init__(self,data=None,files=None,initial=None, freeze_email=False):
+ super(ReportUpdateForm,self).__init__(data,files=files, initial=initial)
+ if freeze_email:
+ self.fields['email'].widget.attrs['readonly'] = 'readonly'
+
class ReportForm(forms.ModelForm):
"""
@@ -151,5 +173,103 @@ def all_errors(self):
errors[key] = value
return( errors )
+
+from social_auth.backends import get_backend
+
+
+class FMSNewRegistrationForm(RegistrationForm):
+
+ username = forms.CharField(widget=forms.widgets.HiddenInput,required=False)
+ phone = forms.CharField(max_length=100,
+ widget=forms.TextInput(attrs={ 'class': 'required' }),
+ label=_('Phone'))
+ first_name = forms.CharField(max_length=100,
+ widget=forms.TextInput(attrs={ 'class': 'required' }),
+ label=_('First Name'))
+ last_name = forms.CharField(max_length=100,
+ widget=forms.TextInput(attrs={ 'class': 'required' }),
+ label=_('Last Name'))
+
+ def __init__(self, *args, **kw):
+ super(FMSNewRegistrationForm, self).__init__(*args, **kw)
+ self.fields.keyOrder = [
+ 'first_name',
+ 'last_name',
+ 'email',
+ 'phone',
+ 'password1',
+ 'password2',
+ 'username' ]
+
+
+ def save(self, profile_callback=None):
+ username = self.cleaned_data.get('username',None)
+
+ if username:
+ # flag that there's an existing user created by
+ # social_auth.
+ new_user = User.objects.get(username=username)
+ else:
+ # otherwise, normal registration.
+ # look for a user with the same email.
+ if User.objects.filter(email=self.cleaned_data.get('email')):
+ new_user = User.objects.get(email=self.cleaned_data.get('email'))
+ else:
+ new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['email'],
+ password=self.cleaned_data['password1'],
+ email=self.cleaned_data['email'],
+ send_email=False )
+ new_user.first_name = self.cleaned_data.get('first_name','')
+ new_user.last_name = self.cleaned_data.get('last_name','')
+ new_user.email = self.cleaned_data.get('email')
+ new_user.set_password(self.cleaned_data.get('password1'))
+ new_user.username = self.cleaned_data.get('email')
+
+ new_user.save()
+
+ user_profile, g_or_c = UserProfile.objects.get_or_create(user=new_user)
+ user_profile.phone = self.cleaned_data.get('phone','')
+ user_profile.save()
+
+ if not new_user.is_active:
+ self.send_email(new_user)
+
+ return( new_user )
+
+ def clean_username(self):
+ return self.cleaned_data['username']
+
+ def clean_email(self):
+ if User.objects.filter(email=self.cleaned_data['email'],is_active=True).count() != 0:
+ raise forms.ValidationError(_(u'That email is already in use.'))
+ return self.cleaned_data['email']
+
+ def send_email(self,new_user):
+ registration_profile = RegistrationProfile.objects.get(user=new_user)
+ current_site = Site.objects.get_current()
+
+ subject = render_to_string('registration/activation_email_subject.txt',
+ { 'site': current_site })
+ # Email subject *must not* contain newlines
+ subject = ''.join(subject.splitlines())
+
+ message = render_to_string('registration/activation_email.txt',
+ { 'activation_key': registration_profile.activation_key,
+ 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
+ 'site': current_site })
+
+ new_user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
+
+
+# just override the AuthenticationForm username so that it's label
+# says 'email'
+
+class FMSAuthenticationForm(AuthenticationForm):
+ """
+ Base class for authenticating users. Extend this to get a form that accepts
+ username/password logins.
+ """
+ username = forms.CharField(label=_("Email"), max_length=30)
+
View
14 mainapp/management/commands/create_cityadmin.py
@@ -1,4 +1,4 @@
-from mainapp.models import UserProfile,City
+from mainapp.models import CityAdmin, City
from optparse import make_option
from django.contrib.auth.models import Group, User
from django.core.management.base import BaseCommand,CommandError
@@ -17,12 +17,6 @@ def handle(self, *args, **options):
if not options.has_key(option.dest):
raise CommandError("%s must be specified" % (option.dest))
city = City.objects.get(name=options['city'])
- user = User.objects.create_user(options['userid'], options['email'], options['password'] )
- user.is_staff = True
- city_admin = Group.objects.get(name='CityAdmins')
- user.groups.add(city_admin)
- user.save()
- profile = UserProfile(user=user)
- profile.save()
- profile.cities.add(city)
- profile.save()
+ user = CityAdmin.objects.create_user(options['userid'], options['email'], city, options['password'] )
+ if not user:
+ print "error creating user"
View
24 mainapp/management/signals/post_syncdb.py
@@ -1,25 +1 @@
-from mainapp.models import Ward,Councillor,EmailRule
-from django.db.models.signals import post_syncdb
-from django.contrib.auth.models import Group, Permission
-from django.contrib.contenttypes.models import ContentType
-cityadmin_permission_names = [ 'Can change ward',
- 'Can add email rule',
- 'Can change email rule',
- 'Can delete email rule',
- 'Can add councillor',
- 'Can change councillor',
- 'Can delete councillor' ]
-
-def add_cityadmin_group_permissions(sender, **kwargs):
- if kwargs['app'].__name__ != 'mainapp.models':
- return
-
- city_admin,created = Group.objects.get_or_create(name='CityAdmins')
- for name in cityadmin_permission_names:
- permission = Permission.objects.get(name=name)
- city_admin.permissions.add(permission)
- city_admin.save()
- print "created %s cityadmin permission group" % kwargs['app'].__name__
-
-post_syncdb.connect(add_cityadmin_group_permissions)
View
80 mainapp/models.py
@@ -18,7 +18,8 @@
from django.utils.encoding import iri_to_uri
from django.contrib.gis.geos import fromstr
from django.http import Http404
-from django.contrib.auth.models import User
+from django.contrib.auth.models import User,Group,Permission
+from registration.models import RegistrationProfile
# from here: http://www.djangosnippets.org/snippets/630/
class CCEmailMessage(EmailMessage):
@@ -450,6 +451,7 @@ def save(self):
m.update(self.email)
m.update(str(time.time()))
self.confirm_token = m.hexdigest()
+ if not self.is_confirmed:
confirm_url = settings.SITE_URL + "/reports/subscribers/confirm/" + self.confirm_token
message = render_to_string("emails/subscribe/message.txt",
{ 'confirm_url': confirm_url, 'subscriber': self })
@@ -702,12 +704,86 @@ class UserProfile(models.Model):
cities = models.ManyToManyField(City, null=True)
+ # fields for 'non-admin' users:
+ phone = models.CharField(max_length=255, verbose_name = ugettext_lazy("Phone"), null=True )
+
+
def __unicode__(self):
return self.user.username
+
+class FMSUserManager(models.Manager):
+ '''
+ FMSUser and FMSUserManager integrate
+ with django-social-auth and django-registration
+ '''
+ def create_user(self, username, email, password=None):
+ user = RegistrationProfile.objects.create_inactive_user(username,password,email,send_email=False)
+
+ if user:
+ UserProfile.objects.get_or_create(user=user)
+ return FMSUser.objects.get(username=user.username)
+ else:
+ return( None )
+
+class FMSUser(User):
+ '''
+ FMSUser and FMSUserManager integrate
+ with django-social-auth and django-registration
+ '''
+ class Meta:
+ proxy = True
+
+ objects = FMSUserManager()
-class DictToPoint():
+
+class CityAdminManager(models.Manager):
+ PERMISSION_NAMES = [ 'Can change ward',
+ 'Can add email rule',
+ 'Can change email rule',
+ 'Can delete email rule',
+ 'Can add councillor',
+ 'Can change councillor',
+ 'Can delete councillor' ]
+
+ GROUP_NAME = 'CityAdmins'
+ def get_group(self):
+ if Group.objects.filter(name=self.GROUP_NAME).exists():
+ return Group.objects.get(name=self.GROUP_NAME)
+ else:
+ group = Group.objects.create(name=self.GROUP_NAME)
+ for name in self.PERMISSION_NAMES:
+ permission = Permission.objects.get(name=name)
+ group.permissions.add(permission)
+ group.save()
+ return group
+
+
+ def create_user(self, username, email, city, password=None):
+ group = self.get_group()
+ user = User.objects.create_user(username, email, password )
+ user.is_staff = True
+ user.groups.add(group)
+ user.save()
+ profile = UserProfile(user=user)
+ profile.save()
+ profile.cities.add(city)
+ profile.save()
+ return user
+
+class CityAdmin(User):
+ '''
+ An admin user who can edit ward data for a city.
+ '''
+ class Meta:
+ proxy = True
+
+ objects = CityAdminManager()
+
+
+class DictToPoint():
+ ''' Helper class '''
def __init__(self, dict, exceptclass = Http404 ):
if exceptclass and not dict.has_key('lat') or not dict.has_key('lon'):
raise exceptclass
View
2 mainapp/tests/__init__.py
@@ -1,3 +1,5 @@
from emailrules import *
from stats import *
+from account import *
from base_cases import *
+
View
15 mainapp/tests/base_cases.py
@@ -6,6 +6,7 @@
import settings
import re
+
CREATE_PARAMS = { 'title': 'A report from our API',
'lat': '45.4043333270000034',
'lon': '-75.6870889663999975',
@@ -163,6 +164,17 @@ def test(self):
self.assertEquals(len(mail.outbox), 1)
self.assertEquals(mail.outbox[0].to, [settings.ADMIN_EMAIL])
+ def _get_error_response(self,query):
+ " check we always end up on the home page "
+ response = self.c.get(self._url(query), follow=True)
+ self.assertEquals( response.status_code, 200 )
+ self.assertEquals( response.template[0].name, 'home.html')
+ return response
+
+ def _url(self,query_str):
+ return( self.base_url + "?q=" + query_str )
+
+
class ChangeCategorySet(BaseCase):
@@ -178,4 +190,5 @@ def test(self):
city.save()
response = self.c.get('/reports/new?&lat=45.4169416715279&lon=-75.70075750350952')
- self.assertContains(response,category_title)
+ self.assertContains(response,category_title)
+
View
22 mainapp/views/reports/main.py
@@ -15,18 +15,29 @@ def new( request ):
pnt = d2p.pnt()
if request.method == "POST":
+ #an UpdateForm is bundled inside ReportForm
report_form = ReportForm( request.POST, request.FILES )
# this checks update is_valid too
if report_form.is_valid():
# this saves the update as part of the report.
- report = report_form.save()
+ report = report_form.save(request.user.is_authenticated())
if report:
return( HttpResponseRedirect( report.get_absolute_url() ))
else:
report_form = ReportForm(initial={ 'lat': request.GET['lat'],
'lon': request.GET['lon'],
'address': request.GET.get('address',None) } )
+ initial={ 'lat': request.GET['lat'],
+ 'lon': request.GET['lon'] }
+
+ if request.user.is_authenticated():
+ initial[ 'author' ] = request.user.first_name + " " + request.user.last_name
+ initial[ 'phone' ] = request.user.get_profile().phone
+ initial[ 'email' ] = request.user.email
+
+ report_form = ReportForm( initial=initial, freeze_email=request.user.is_authenticated() )
+
return render_to_response("reports/new.html",
{ "google": FixMyStreetMap(pnt, True),
'GOOGLE_KEY': settings.GMAP_KEY,
@@ -39,12 +50,19 @@ def new( request ):
def show( request, report_id ):
report = get_object_or_404(Report, id=report_id)
subscribers = report.reportsubscriber_set.count() + 1
+ initial = {}
+
+ if request.user.is_authenticated():
+ initial[ 'author' ] = request.user.first_name + " " + request.user.last_name
+ initial[ 'phone' ] = request.user.get_profile().phone
+ initial[ 'email' ] = request.user.email
+
return render_to_response("reports/show.html",
{ "report": report,
"subscribers": subscribers,
"ward":report.ward,
"updates": ReportUpdate.objects.filter(report=report, is_confirmed=True).order_by("created_at")[1:],
- "update_form": ReportUpdateForm(),
+ "update_form": ReportUpdateForm(initial=initial,freeze_email=request.user.is_authenticated()),
"google": FixMyStreetMap((report.point)) },
context_instance=RequestContext(request))
View
8 mainapp/views/reports/subscribers.py
@@ -13,14 +13,18 @@ def new( request, report_id ):
form = ReportSubscriberForm( request.POST )
if form.is_valid():
subscriber = form.save( commit = False )
- subscriber.report = report;
+ subscriber.report = report
+ subscriber.is_confirmed = request.user.is_authenticated()
if report.is_subscribed(subscriber.email):
error_msg = _("You are already subscribed to this report.")
else:
subscriber.save()
return( HttpResponseRedirect( '/reports/subscribers/create/' ) )
else:
- form = ReportSubscriberForm()
+ initial = {}
+ if request.user.is_authenticated():
+ initial['email'] = request.user.email
+ form = ReportSubscriberForm(initial=initial,freeze_email=request.user.is_authenticated())
return render_to_response("reports/subscribers/new.html",
{ "subscriber_form": form,
View
8 mainapp/views/reports/updates.py
@@ -12,9 +12,13 @@ def new( request, report_id ):
update = update_form.save(commit=False)
update.is_fixed = request.POST.has_key('is_fixed')
update.report=report
+ update.is_confirmed = request.user.is_authenticated()
update.save()
- # redirect after a POST
- return( HttpResponseRedirect( '/reports/updates/create/' ) )
+ # redirect after a POST
+ if request.user.is_authenticated():
+ return( HttpResponseRedirect( report.get_absolute_url() ) )
+ else:
+ return( HttpResponseRedirect( '/reports/updates/create/' ) )
else:
update_form = ReportUpdateForm()
View
81 media/css/layout-8.css
@@ -147,12 +147,28 @@ text-align:left;
#language {
padding-top: 1em;
padding-right: 1em;
- width: 100%;
+ width: 35%;
height: 40px;
text-align: right;
float: right
}
+#account-signin {
+ padding-top: 1.5em;
+ float: left;
+ width: 60%;
+ font-size: 80%;
+}
+
+#account-signin ul {
+ float: right;
+}
+
+#account-signin ul li {
+ float: left;
+ margin-left: 10px;
+ list-style-type: none;
+}
#content {
text-align: left;
@@ -192,7 +208,7 @@ table.form td select {
}
-table.form input[type='text'],table.form textarea {
+table.form input[type='text'],table.form textarea,table.form input[type='password'] {
width: 100%;
border:0 none;
color:#222222;
@@ -393,6 +409,56 @@ padding-right: 5px;
list-style-type: disc;
}
+div.provider-list ul {
+list-style-type:none;
+}
+.social-logo-show {
+display:block;
+background:transparent url(/media/images/social/all_social.png) no-repeat scroll 0 0;
+height:24px;
+width:72px;
+}
+div#register {
+ width: 100%;
+}
+
+#account-form {
+ width: 50%;
+ float:left;
+ text-align: left;
+ border-right:1px solid #E0E0E0;
+ margin-bottom: 1.2em;
+
+}
+
+#account-form h3 {
+font-size:2em;
+margin-bottom:20px;
+}
+
+#register label {
+ width: 150px;
+}
+
+div#social-list
+{
+ width: 30%;
+ float: left;
+ text-align: left;
+ padding:1em 0 20px 20px;
+
+}
+
+#social-list p {
+ font-size:1.16667em;
+ letter-spacing:-0.025em;
+ margin-bottom:18px;
+}
+
+#social-list li {
+margin-bottom:10px;
+}
+
blockquote {
margin-left: 3em !important;
padding-left: 1em !important;
@@ -471,6 +537,15 @@ input.big_button:hover {background: url("/media/images/search-hover.png") no-rep
#contact_us_form p { margin-bottom: .5em; }
#posters { text-align: center; }
#posters p {width: 450px; margin: 20px auto;}
-
+.myreports { width:100%; }
+.myreports td { padding: 2px; }
+.myreports td.section {color:#FFFFFF;
+font-size:80%;
+font-weight:bold;
+margin-top:5px;
+padding-left:5px;
+}
.left {float:left;}
.right {float:right;}
+
+
View
52 settings.py
@@ -3,7 +3,6 @@
import logging
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
-TEST_RUNNER='django.contrib.gis.tests.run_tests'
POSTGIS_TEMPLATE = 'template_postgis'
logging.basicConfig(
@@ -50,22 +49,25 @@
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
- 'django.template.loaders.filesystem.load_template_source',
- 'django.template.loaders.app_directories.load_template_source',
+ 'django.template.loaders.filesystem.Loader',
+ 'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.load_template_source',
)
# include request object in template to determine active page
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
- 'django.core.context_processors.auth',
+ 'django.contrib.auth.context_processors.auth',
+ 'django.core.context_processors.csrf',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
+ 'django.middleware.csrf.CsrfViewMiddleware',
+# 'django.middleware.csrf.CsrfResponseMiddleware',
'mainapp.middleware.subdomains.SubdomainMiddleware',
'mainapp.middleware.SSLMiddleware.SSLRedirect',
)
@@ -93,24 +95,48 @@
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.gis',
+ 'registration',
'contrib.google_analytics',
'contrib.transmeta',
+ 'social_auth',
'mainapp',
)
AUTH_PROFILE_MODULE = 'mainapp.UserProfile'
+AUTHENTICATION_BACKENDS = (
+ 'social_auth.backends.twitter.TwitterBackend',
+ 'social_auth.backends.facebook.FacebookBackend',
+ 'social_auth.backends.google.GoogleOAuthBackend',
+ 'social_auth.backends.google.GoogleOAuth2Backend',
+ 'social_auth.backends.google.GoogleBackend',
+ 'social_auth.backends.yahoo.YahooBackend',
+ 'social_auth.backends.OpenIDBackend',
+ 'django.contrib.auth.backends.ModelBackend',
+ 'mainapp.tests.testsocial_auth.dummy_socialauth.DummyBackend',
+)
+
+SOCIAL_AUTH_USER_MODEL = 'mainapp.FMSUser'
+SOCIAL_AUTH_ASSOCIATE_BY_MAIL = True
+ACCOUNT_ACTIVATION_DAYS = 14
+SOCIAL_AUTH_EXTRA_DATA = False
+SOCIAL_AUTH_COMPLETE_URL_NAME = 'socialauth_complete'
+LOGIN_ERROR_URL = '/accounts/login/error/'
+SOCIAL_AUTH_ERROR_KEY = 'socialauth_error'
+LOGIN_REDIRECT_URL = '/accounts/home/'
#################################################################################
# These variables Should be defined in the local settings file
#################################################################################
#
-#DATABASE_ENGINE = # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
-#DATABASE_NAME = # Or path to database file if using sqlite3.
-#DATABASE_USER = # Not used with sqlite3.
-#DATABASE_PASSWORD = # Not used with sqlite3.
-#DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
-#DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
+#DATABASES = {
+# 'default': {
+# 'ENGINE': 'django.contrib.gis.db.backends.postgis',
+# 'NAME': '',
+# 'USER': '',
+# 'PASSWORD': ''
+# }
+#}
#
#EMAIL_USE_TLS =
#EMAIL_HOST =
@@ -147,3 +173,9 @@
if DEBUG and globals().has_key('TESTVIEW'):
INSTALLED_APPS += ('django_testview',)
+
+
+if DEBUG:
+ SOCIAL_AUTH_IMPORT_BACKENDS = (
+ 'mainapp.tests.testsocial_auth',
+ )
View
4 templates/_search.js
@@ -35,14 +35,15 @@ function html_for_multiple_matches(array)
function html_for_no_results()
{
var html = "<div id='error-msg'>";
- html += '<p>{% trans "Sorry, we couldn\'t find the address you entered. Please try again with another intersection, address or postal code, or add the name of the city to the end of the search."%}</p>';
+ html += "<p>{% trans "Sorry, we couldn\'t find the address you entered. Please try again with another intersection, address or postal code, or add the name of the city to the end of the search."%}</p>";
html += '</div>'
jQuery("#search-error").html(html).fadeIn(1000);
}
function handle_google_geocode_response(geodata)
{
+
if ((geodata.Status.code == 200) && (geodata.Placemark.length > 0 ))
{
if ( geodata.Placemark.length > 1)
@@ -73,7 +74,6 @@ function do_search()
jQuery(document).ready(function($)
{
-
$("#search_box").keyup(function(event){
if(event.keyCode == 13){
$("#search_button").click();
View
2 templates/account/edit.html
@@ -9,7 +9,7 @@
{% block content %}
<div id='profile-form'>
<h3>{% trans "Editing Profile For" %} {{user.first_name}} {{user.last_name}}</h3>
- <form action="/accounts/edit/" method="POST">
+ <form action="/accounts/edit/" method="POST">{% csrf_token %}
<table class='form'>
{{form.as_table}}
<tr>
View
2 templates/admin/login.html
@@ -14,7 +14,7 @@
<p class="errornote">{{ error_message }}</p>
{% endif %}
<div id="content-main">
-<form action="{{ app_path }}" method="post" id="login-form">
+<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}
<div class="form-row">
<label for="id_username">{% trans 'Username:' %}</label> <input type="text" name="username" id="id_username" />
</div>
View
14 templates/base.html
@@ -38,8 +38,20 @@
<a href='/'><img src="/media/images/fms-canada-logo.gif"></a>
</div>
<div id="header_right">
+ <div id='account-signin'>
+ <ul>
+ {% if user.is_authenticated %}
+ <li><a href='{% url account_home %}'>My Account</a></li>
+ <li><a href='{% url auth_logout %}'>Sign Out</a></li>
+ {% else %}
+ <li><a href='{% url auth_login %}'>Sign In</a></li>
+ <li><a href='{% url registration_register %}'>Create Account</a></li>
+ {% endif %}
+ </ul>
+
+ </div>
<div id="language">
- <form action="/i18n/setlang/" method="post">
+ <form action="/i18n/setlang/" method="post">{% csrf_token %}
<select name="language">
{% for lang in LANGUAGES %}
<option value="{{ lang.0 }}">{{ lang.1 }}</option>
View
2 templates/contact/new.html
@@ -16,7 +16,7 @@
</p>
<p>We'd love to get your feedback on this site:</p>
{% endblocktrans %}
-<form action="/contact" method="POST">
+<form action="/contact" method="POST">{% csrf_token %}
<table class='form'>
{{contact_form}}
<tr>
View
2 templates/registration/login.html
@@ -4,7 +4,7 @@
{% block content %}
<div id='account-form'>
<h3>{% trans "Login" %}</h3>
- <form action="/accounts/login/" method="POST">
+ <form action="/accounts/login/" method="POST">{% csrf_token %}
<table class='form'>
{{form.as_table}}
<tr>
View
2 templates/registration/registration_form.html
@@ -22,7 +22,7 @@
</div>
{% endif %}
<h3>{% trans "Join FixMyStreet.ca!" %}</h3>
-<form action="{% url registration_register %}" method="POST">
+<form action="{% url registration_register %}" method="POST">{% csrf_token %}
<table class='form'>
{{form.as_table}}
<tr>
View
2 templates/reports/flags/new.html
@@ -7,7 +7,7 @@
<h3>{{report.title}}</h3>
<p>{{report.first_update.desc}}</p>
</blockquote>
-<form action="/reports/{{report.id}}/flags/" method="POST">
+<form action="/reports/{{report.id}}/flags/" method="POST">{% csrf_token %}
<input type="submit" value="{% trans "Flag this Report" %}">
</form>
View
2 templates/reports/new.html
@@ -58,7 +58,7 @@
<div id="leftcol">
<h3>{% trans "Submitting a report" %}</h3>
- <form enctype="multipart/form-data" method="post" action="/reports/" id='report_form'>
+ <form enctype="multipart/form-data" method="post" action="/reports/" id='report_form'> {% csrf_token %}
<table class='form'>
{{ report_form.as_table }}
<tr>
View
2 templates/reports/show.html
@@ -97,7 +97,7 @@
<div id="update-title"><h3>{% trans "Provide an update" %} </h3></div>
</div>
<p>{% trans "Please note that updates are not sent to city officials." %}</p>
- <form action="/reports/{{report.id}}/updates/" method="post">
+ <form action="/reports/{{report.id}}/updates/" method="post">{% csrf_token %}
<table class="form">
{{update_form.as_table}}
<tr><td></td><td><input type="checkbox" id="is_fixed" name="is_fixed" value="1">{% trans "This problem has been fixed." %}</td></tr>
View
2 templates/reports/subscribers/new.html
@@ -7,7 +7,7 @@
<h2>{% trans "Subscribe to Updates to Report" %}: {{report.title}}</h2>
<p>{% trans "Enter your email address to subscribe to updates for this report:" %}</p>
-<form action="/reports/{{report.id}}/subscribers/" method="POST">
+<form action="/reports/{{report.id}}/subscribers/" method="POST">{% csrf_token %}
{{subscriber_form.as_table}}
<input type="submit" value="{% trans "Subscribe" %}">
</form>
View
46 urls.py
@@ -4,32 +4,38 @@
from django.contrib import admin
from mainapp.feeds import LatestReports, LatestReportsByCity, LatestReportsByWard, LatestUpdatesByReport
from mainapp.models import City
+from social_auth.views import auth as social_auth
+from social_auth.views import disconnect as social_disconnect
+from registration.views import register
+from mainapp.forms import FMSNewRegistrationForm,FMSAuthenticationForm
+from mainapp.views.account import SUPPORTED_SOCIAL_PROVIDERS
+from django.contrib.auth import views as auth_views
+
import mainapp.views.cities as cities
+
feeds = {
'reports': LatestReports,
'wards': LatestReportsByWard,
'cities': LatestReportsByCity,
'report_updates': LatestUpdatesByReport,
}
-if settings.DEBUG:
- SSL_ON = False
-else:
- SSL_ON = True
+SSL_ON = not settings.DEBUG
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/password_reset/$', 'django.contrib.auth.views.password_reset',{'SSL':SSL_ON}),
(r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done'),
(r'^reset/(?P<uidb36>[-\w]+)/(?P<token>[-\w]+)/$', 'django.contrib.auth.views.password_reset_confirm'),
(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete'),
- (r'^admin/(.*)', admin.site.root,{'SSL':SSL_ON}),
+ (r'^admin/', admin.site.urls,{'SSL':SSL_ON}),
(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
(r'^i18n/', include('django.conf.urls.i18n')),
-)
-
+ url(r'^login/(?P<backend>[^/]+)/$', social_auth, name='begin'),
+ url(r'^disconnect/(?P<backend>[^/]+)/$', social_disconnect, name='socialdisconnect'),
+)
urlpatterns += patterns('mainapp.views.main',
(r'^$', 'home', {}, 'home_url_name'),
@@ -49,8 +55,7 @@
urlpatterns += patterns('mainapp.views.wards',
(r'^wards/(\d+)', 'show'),
- (r'^cities/(\d+)/wards/(\d+)', 'show_by_number'),
-
+ (r'^cities/(\d+)/wards/(\d+)', 'show_by_number'),
)
urlpatterns += patterns('',
@@ -91,7 +96,28 @@
(r'^ajax/categories/(\d+)', 'category_desc'),
)
-if settings.DEBUG and 'TESTVIEW' in settings.get_all_members():
+
+urlpatterns += patterns('',
+ url('^accounts/register/$', register, {'form_class': FMSNewRegistrationForm,
+ 'extra_context':
+ { 'providers': SUPPORTED_SOCIAL_PROVIDERS } },name='registration_register'),
+ url('^accounts/login/$', auth_views.login, {'template_name':'registration/login.html',
+ 'authentication_form':FMSAuthenticationForm,
+ 'extra_context':
+ { 'providers': SUPPORTED_SOCIAL_PROVIDERS }}, name='auth_login'),
+ url(r'^accounts/logout/$', auth_views.logout,
+ {'next_page': '/'}, name='auth_logout' ),
+ (r'^accounts/', include('registration.urls'))
+)
+
+urlpatterns += patterns('mainapp.views.account',
+ url(r'^accounts/home/', 'home',name='account_home'),
+ url(r'^accounts/edit/', 'edit',name='account_edit'),
+ (r'^accounts/login/error/$', 'error'),
+ url(r'^accounts/complete/(?P<backend>[^/]+)/$', 'socialauth_complete', name='socialauth_complete'),
+)
+
+if settings.DEBUG and 'TESTVIEW' in settings.__members__:
urlpatterns += patterns ('',
(r'^testview',include('django_testview.urls')))

0 comments on commit eb41c1e

Please sign in to comment.