Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

refactoring - tabs to spaces + settings to conf

  • Loading branch information...
commit 9b98cd01cd7e2ad2403e6d4760235b5f0880c0e1 1 parent b3ee05a
@zalun zalun authored
Showing with 427 additions and 581 deletions.
  1. +0 −21 flightdeck/NOTES
  2. +0 −20 flightdeck/amo/__init__.py
  3. +129 −129 flightdeck/amo/authentication.py
  4. 0  flightdeck/amo/{default_settings.py → conf.py}
  5. +0 −3  flightdeck/amo/models.py
  6. +10 −12 flightdeck/amo/tests.py
  7. +0 −1  flightdeck/amo/views.py
  8. +0 −18 flightdeck/api/__init__.py
  9. 0  flightdeck/api/{default_settings.py → conf.py}
  10. +0 −3  flightdeck/api/models.py
  11. +10 −9 flightdeck/api/tests.py
  12. +4 −4 flightdeck/api/urls.py
  13. +74 −80 flightdeck/api/views.py
  14. +1 −1  flightdeck/base/context_processors.py
  15. +0 −3  flightdeck/base/models.py
  16. +14 −14 flightdeck/base/shortcuts.py
  17. +0 −23 flightdeck/base/tests.py
  18. +13 −16 flightdeck/base/views.py
  19. +0 −19 flightdeck/person/__init__.py
  20. +4 −4 flightdeck/person/{default_settings.py → conf.py}
  21. +4 −4 flightdeck/person/context_processors.py
  22. +19 −20 flightdeck/person/forms.py
  23. +25 −25 flightdeck/person/models.py
  24. +17 −17 flightdeck/person/tests.py
  25. +23 −23 flightdeck/person/urls.py
  26. +47 −47 flightdeck/person/views.py
  27. +0 −1  flightdeck/settings_local-default.py
  28. +0 −3  flightdeck/tutorial/models.py
  29. +0 −23 flightdeck/tutorial/tests.py
  30. +21 −26 flightdeck/urls.py
  31. +2 −2 flightdeck/urls_local-default.py
  32. +0 −10 flightdeck/utils.py
  33. +10 −0 flightdeck/utils/__init__.py
View
21 flightdeck/NOTES
@@ -1,21 +0,0 @@
-This is a document which will carry notes while coding offline
-This content will be send to goplanapp into discussions.
-Please delete only your staff.
-Start coding on the top.
--------------------------------------------------------------
-
-zalun - 2010-02-17 - Saving dependencies
-----------------------------------------
-There is a problem with editing dependencies and saving them together
-with the main edited file. It just doesn't seem to work well to force
-user to use the same save action for all edited files.
-
-What I suggest is to display a popUp onAnySave if any capability was changed.
-Whithin that popUp there will be a list of changed elements. User will have
-an if item should be saved and in which way (new version/update).
-
-The system is designed to connect saving of the model only if its content
-has been changed - however it will to wait until proper onChange event will
-be written. Currently the system will send the onChange event after onBlur,
-which may bring some problems. I guess using the BespinEmbedded will solve
-this issue.
View
20 flightdeck/amo/__init__.py
@@ -1,20 +0,0 @@
-# Taken from feincms
-# http://github.com/matthiask/feincms/blob/master/feincms/__init__.py
-
-# Do not use Django settings at module level as recommended
-from django.utils.functional import LazyObject
-
-class LazySettings(LazyObject):
- def _setup(self):
- from amo import default_settings
- self._wrapped = Settings(default_settings)
-
-class Settings(object):
- def __init__(self, settings_module):
- for setting in dir(settings_module):
- if setting == setting.upper():
- setattr(self, setting, getattr(settings_module, setting))
-
-settings = LazySettings()
-
-
View
258 flightdeck/amo/authentication.py
@@ -5,140 +5,140 @@
from django.utils.encoding import smart_str
from person.models import Profile, Limit
-from amo import settings
+from amo import conf
DEFAULT_AMO_PASSWORD = 'saved in AMO'
class AMOAuthentication:
- def authenticate(self, username, password):
- """
- Authenticate user by contacting with AMO
- """
-
-
- # TODO: Validate alphanum + .-_@
-
- # check if username exists in database
- try:
- user = User.objects.get(username=username)
- # was user signed up via AMO?
- if user.password != DEFAULT_AMO_PASSWORD:
- # standard authorisation
- if user.check_password(password):
- try:
- profile = user.get_profile()
- except:
- # create empty profile for users stored in FD database
- profile = Profile(user=user)
- profile.save()
- return user
- return None
- except User.DoesNotExist:
- # username does not exist in FD database
- user = None
-
-
- # if access to the FD is limited
- if settings.AMO_LIMITED_ACCESS:
- if username not in [x.email for x in list(Limit.objects.all())]:
- return None
-
- if not settings.AUTH_DATABASE:
- return None
-
- # here contact AMO and receive authentication status
- email = username
- username = self.auth_db_authenticate(username, password)
-
- if not username:
- return None
-
- # check if user was already signed to FD
- try:
- user = User.objects.get(username=username)
- # update user's email if needed
- if user.email != email:
- user.email = email
- user.save()
- except:
- # save user into the database
- user = User(
- username=username,
- email=email,
- password=DEFAULT_AMO_PASSWORD,
- )
- user.save()
-
- # Manage profile
- try:
- profile = user.get_profile()
- except Profile.DoesNotExist:
- profile = Profile(user=user)
-
- # update profile and return User instance
- return update_profile(user, profile, self.user_data)
-
-
- def get_user(self, user_id):
- try:
- return User.objects.get(pk=user_id)
- except:
- return None
-
-
- def auth_db_authenticate(self, username, password):
- " authenticate email/password pair in MAO database "
- columns = ('id', 'email','username','display_name','password','homepage')
-
- auth_conn = MySQLdb.connect(
- host=settings.AUTH_DATABASE['HOST'],
- user=settings.AUTH_DATABASE['USER'],
- passwd=settings.AUTH_DATABASE['PASSWORD'],
- db=settings.AUTH_DATABASE['NAME']
- )
- auth_cursor = auth_conn.cursor()
- SQL = 'SELECT %s FROM %s WHERE email="%s"' % (','.join(columns), settings.AUTH_DATABASE['TABLE'], username)
- auth_cursor.execute(SQL)
- data = auth_cursor.fetchone()
- user_data = {}
- for i in range(len(data)):
- user_data[columns[i]] = data[i]
- if not user_data:
- return None
-
- if '$' not in user_data['password']:
- valid = (get_hexdigest('md5', '', password) == user_data['password'])
- else:
- algo, salt, hsh = user_data['password'].split('$')
- valid = (hsh == get_hexdigest(algo, salt, password))
-
- if not valid:
- return None
-
- username = user_data['id']
- self.user_data = user_data
- return username
-
-
+ def authenticate(self, username, password):
+ """
+ Authenticate user by contacting with AMO
+ """
+
+
+ # TODO: Validate alphanum + .-_@
+
+ # check if username exists in database
+ try:
+ user = User.objects.get(username=username)
+ # was user signed up via AMO?
+ if user.password != DEFAULT_AMO_PASSWORD:
+ # standard authorisation
+ if user.check_password(password):
+ try:
+ profile = user.get_profile()
+ except:
+ # create empty profile for users stored in FD database
+ profile = Profile(user=user)
+ profile.save()
+ return user
+ return None
+ except User.DoesNotExist:
+ # username does not exist in FD database
+ user = None
+
+
+ # if access to the FD is limited
+ if conf.AMO_LIMITED_ACCESS:
+ if username not in [x.email for x in list(Limit.objects.all())]:
+ return None
+
+ if not conf.AUTH_DATABASE:
+ return None
+
+ # here contact AMO and receive authentication status
+ email = username
+ username = self.auth_db_authenticate(username, password)
+
+ if not username:
+ return None
+
+ # check if user was already signed to FD
+ try:
+ user = User.objects.get(username=username)
+ # update user's email if needed
+ if user.email != email:
+ user.email = email
+ user.save()
+ except:
+ # save user into the database
+ user = User(
+ username=username,
+ email=email,
+ password=DEFAULT_AMO_PASSWORD,
+ )
+ user.save()
+
+ # Manage profile
+ try:
+ profile = user.get_profile()
+ except Profile.DoesNotExist:
+ profile = Profile(user=user)
+
+ # update profile and return User instance
+ return update_profile(user, profile, self.user_data)
+
+
+ def get_user(self, user_id):
+ try:
+ return User.objects.get(pk=user_id)
+ except:
+ return None
+
+
+ def auth_db_authenticate(self, username, password):
+ " authenticate email/password pair in MAO database "
+ columns = ('id', 'email','username','display_name','password','homepage')
+
+ auth_conn = MySQLdb.connect(
+ host=conf.AUTH_DATABASE['HOST'],
+ user=conf.AUTH_DATABASE['USER'],
+ passwd=conf.AUTH_DATABASE['PASSWORD'],
+ db=conf.AUTH_DATABASE['NAME']
+ )
+ auth_cursor = auth_conn.cursor()
+ SQL = 'SELECT %s FROM %s WHERE email="%s"' % (','.join(columns), conf.AUTH_DATABASE['TABLE'], username)
+ auth_cursor.execute(SQL)
+ data = auth_cursor.fetchone()
+ user_data = {}
+ for i in range(len(data)):
+ user_data[columns[i]] = data[i]
+ if not user_data:
+ return None
+
+ if '$' not in user_data['password']:
+ valid = (get_hexdigest('md5', '', password) == user_data['password'])
+ else:
+ algo, salt, hsh = user_data['password'].split('$')
+ valid = (hsh == get_hexdigest(algo, salt, password))
+
+ if not valid:
+ return None
+
+ username = user_data['id']
+ self.user_data = user_data
+ return username
+
+
def update_profile(user, profile, data):
- if 'display_name' in data:
- if data['display_name']:
- names = data['display_name'].split(' ')
- user.firstname = names[0]
- if len(names) > 1:
- user.lastname = names[-1]
- user.save()
-
- if 'username' in data:
- profile.nickname = data['username']
- if 'homepage' in data:
- profile.homepage = data['homepage']
-
- profile.save()
-
- return user
-
+ if 'display_name' in data:
+ if data['display_name']:
+ names = data['display_name'].split(' ')
+ user.firstname = names[0]
+ if len(names) > 1:
+ user.lastname = names[-1]
+ user.save()
+
+ if 'username' in data:
+ profile.nickname = data['username']
+ if 'homepage' in data:
+ profile.homepage = data['homepage']
+
+ profile.save()
+
+ return user
+
def get_hexdigest(algorithm, salt, raw_password):
- return hashlib.new(algorithm, smart_str(salt + raw_password)).hexdigest()
+ return hashlib.new(algorithm, smart_str(salt + raw_password)).hexdigest()
View
0  flightdeck/amo/default_settings.py → flightdeck/amo/conf.py
File renamed without changes
View
3  flightdeck/amo/models.py
@@ -1,3 +0,0 @@
-from django.db import models
-
-# Create your models here.
View
22 flightdeck/amo/tests.py
@@ -1,17 +1,15 @@
from django.test import TestCase
-from django.test.client import Client
-from django.contrib.auth.models import User
from django.contrib.auth import authenticate
-from person.models import Profile
class AuthTest(TestCase):
-
- def test_failing_login(self):
- # testing failed authentication on AMO
- self.assertEqual(
- None,
- authenticate(
- username='non existing',
- password='user')
- )
+
+ def test_failing_login(self):
+ # testing failed authentication on AMO
+ # this test assumes FlightDeck has access to AMO database
+ self.assertEqual(
+ None,
+ authenticate(
+ username='non existing',
+ password='user')
+ )
View
1  flightdeck/amo/views.py
@@ -1 +0,0 @@
-# Create your views here.
View
18 flightdeck/api/__init__.py
@@ -1,18 +0,0 @@
-# Taken from feincms
-# http://github.com/matthiask/feincms/blob/master/feincms/__init__.py
-
-# Do not use Django settings at module level as recommended
-from django.utils.functional import LazyObject
-
-class LazySettings(LazyObject):
- def _setup(self):
- from api import default_settings
- self._wrapped = Settings(default_settings)
-
-class Settings(object):
- def __init__(self, settings_module):
- for setting in dir(settings_module):
- if setting == setting.upper():
- setattr(self, setting, getattr(settings_module, setting))
-
-settings = LazySettings()
View
0  flightdeck/api/default_settings.py → flightdeck/api/conf.py
File renamed without changes
View
3  flightdeck/api/models.py
@@ -1,3 +0,0 @@
-from django.db import models
-
-# Create your models here.
View
19 flightdeck/api/tests.py
@@ -1,19 +1,20 @@
"""
-Testing the cuddlefish engine to export API
+Testing the cuddlefish engine to export API
"""
import os
from django.test import TestCase
from cuddlefish import apiparser
-from api import settings
+from api import conf
class CuddleTest(TestCase):
- def test_basic(self):
- """
- exporting hunks
- """
- docs_dir = os.path.join(settings.VIRTUAL_ENV,'src/jetpack-sdk/packages/jetpack-core/docs')
- text = open(os.path.join(docs_dir,'url.md')).read()
- self.failUnless(len(list(apiparser.parse_hunks(text))) > 0)
+ def test_basic(self):
+ """
+ exporting hunks
+ """
+ #XXX: the path is different now
+ docs_dir = os.path.join(conf.FRAMEWORK_PATH,'sdk_versions/jetpack-sdk/packages/jetpack-core/docs')
+ text = open(os.path.join(docs_dir,'url.md')).read()
+ self.failUnless(len(list(apiparser.parse_hunks(text))) > 0)
View
8 flightdeck/api/urls.py
@@ -1,9 +1,9 @@
from django.conf.urls.defaults import *
urlpatterns = patterns('api.views',
- url(r'^(?P<package_name>[-\w]+)/module/(?P<module_name>[-\w]+)/$',
- 'module', name='api_module'),
- url(r'^(?P<package_name>[-\w]+)/$', 'package', name='api_package'),
- url(r'$', 'homepage', name='api_home'),
+ url(r'^(?P<package_name>[-\w]+)/module/(?P<module_name>[-\w]+)/$',
+ 'module', name='api_module'),
+ url(r'^(?P<package_name>[-\w]+)/$', 'package', name='api_package'),
+ url(r'$', 'homepage', name='api_home'),
)
View
154 flightdeck/api/views.py
@@ -1,99 +1,93 @@
import os
-import sys
from cuddlefish import apiparser
-from django.shortcuts import render_to_response, get_object_or_404
-from django.http import Http404, HttpResponseRedirect, HttpResponse, \
- HttpResponseNotAllowed, HttpResponseServerError
-from django.template import RequestContext#,Template
-from django.utils import simplejson
+from django.shortcuts import render_to_response
+from django.template import RequestContext
-from base.shortcuts import get_object_or_create, get_object_with_related_or_404, \
- get_random_string
-from api import settings
+from api import conf
def _get_module_filenames(package_name):
- files = os.listdir(os.path.join(settings.SDKPACKAGESDIR,package_name,'docs'))
- files.sort()
- return files
+ files = os.listdir(os.path.join(conf.SDKPACKAGESDIR,package_name,'docs'))
+ files.sort()
+ return files
def _get_module_names(package_name):
- DOC_FILES = _get_module_filenames(package_name)
- return [{'name': os.path.splitext(d)[0]} for d in DOC_FILES]
- modules.sort()
- return modules
+ DOC_FILES = _get_module_filenames(package_name)
+ return [{'name': os.path.splitext(d)[0]} for d in DOC_FILES]
+ DOC_FILES.sort()
+ return DOC_FILES
def homepage(r, package_name='jetpack-core'):
- page = 'apibrowser'
+ page = 'apibrowser'
- sdk_version = settings.SDKVERSION
- package = {'name': package_name, 'modules': _get_module_names(package_name)}
+ sdk_version = conf.SDKVERSION
+ package = {'name': package_name, 'modules': _get_module_names(package_name)}
- return render_to_response(
- 'api_homepage.html',
- locals(),
- context_instance=RequestContext(r))
+ return render_to_response(
+ 'api_homepage.html',
+ locals(),
+ context_instance=RequestContext(r))
def package(r, package_name='jetpack-core'):
- """
- containing a listing of all modules docs
- """
- page = 'apibrowser'
-
- sdk_version = settings.SDKVERSION
-
- DOC_FILES = _get_module_filenames(package_name)
-
- package = {'name': package_name, 'modules': []}
- for d in DOC_FILES:
- text = open(os.path.join(settings.SDKPACKAGESDIR,package_name,'docs',d)).read()
- (doc_name, extension) = os.path.splitext(d)
- # changing the tuples to dictionaries
- hunks = list(apiparser.parse_hunks(text))
- data = {}
- for h in hunks:
- data[h[0]] = h[1]
- package['modules'].append({
- 'name': doc_name,
- 'info': hunks[0][1],
- 'data': data,
- 'hunks': hunks
- })
-
- return render_to_response(
- 'package_doc.html',
- locals(),
- context_instance=RequestContext(r))
-
+ """
+ containing a listing of all modules docs
+ """
+ page = 'apibrowser'
+
+ sdk_version = conf.SDKVERSION
+
+ DOC_FILES = _get_module_filenames(package_name)
+
+ package = {'name': package_name, 'modules': []}
+ for d in DOC_FILES:
+ text = open(os.path.join(conf.SDKPACKAGESDIR,package_name,'docs',d)).read()
+ (doc_name, extension) = os.path.splitext(d)
+ # changing the tuples to dictionaries
+ hunks = list(apiparser.parse_hunks(text))
+ data = {}
+ for h in hunks:
+ data[h[0]] = h[1]
+ package['modules'].append({
+ 'name': doc_name,
+ 'info': hunks[0][1],
+ 'data': data,
+ 'hunks': hunks
+ })
+
+ return render_to_response(
+ 'package_doc.html',
+ locals(),
+ context_instance=RequestContext(r))
+
def module(r, package_name, module_name):
- page = 'apibrowser'
-
- sdk_version = settings.SDKVERSION
- doc_file = '.'.join((module_name,'md'))
- text = open(os.path.join(settings.SDKPACKAGESDIR,package_name,'docs',doc_file)).read()
- # changing the tuples to dictionaries
- hunks = list(apiparser.parse_hunks(text))
- data = []
- for h in hunks:
- # convert JSON to a nice list
- if h[0] == 'api-json':
- entity = h[1]
- entity['template'] = '_entity_%s.html' % entity['type']
- data.append(entity)
-
- module = {
- 'name': module_name,
- 'info': hunks[0][1],
- 'data': data,
- 'hunks': hunks
- }
- package = {'name': package_name, 'modules': _get_module_names(package_name)}
-
- return render_to_response(
- 'module_doc.html',
- locals(),
- context_instance=RequestContext(r))
+ page = 'apibrowser'
+
+ sdk_version = conf.SDKVERSION
+ doc_file = '.'.join((module_name,'md'))
+ text = open(os.path.join(conf.SDKPACKAGESDIR,package_name,'docs',doc_file)).read()
+ # changing the tuples to dictionaries
+ hunks = list(apiparser.parse_hunks(text))
+ data = []
+ for h in hunks:
+ # convert JSON to a nice list
+ if h[0] == 'api-json':
+ entity = h[1]
+ entity['template'] = '_entity_%s.html' % entity['type']
+ data.append(entity)
+
+ module = {
+ 'name': module_name,
+ 'info': hunks[0][1],
+ 'data': data,
+ 'hunks': hunks
+ }
+ package = {'name': package_name, 'modules': _get_module_names(package_name)}
+
+ return render_to_response(
+ 'module_doc.html',
+ locals(),
+ context_instance=RequestContext(r))
View
2  flightdeck/base/context_processors.py
@@ -1,4 +1,4 @@
from django.conf import settings as _settings
def settings(request):
- return {'settings': _settings}
+ return {'settings': _settings}
View
3  flightdeck/base/models.py
@@ -1,3 +0,0 @@
-from django.db import models
-
-# Create your models here.
View
28 flightdeck/base/shortcuts.py
@@ -5,15 +5,15 @@
from django.http import Http404
def get_object_or_create(klass, *args, **kwargs):
- if isinstance(klass, Manager):
- manager = klass
- klass = manager.model
- else:
- manager = klass._default_manager
- try:
- return manager.get(*args, **kwargs)
- except klass.DoesNotExist:
- return manager.create(*args, **kwargs)
+ if isinstance(klass, Manager):
+ manager = klass
+ klass = manager.model
+ else:
+ manager = klass._default_manager
+ try:
+ return manager.get(*args, **kwargs)
+ except klass.DoesNotExist:
+ return manager.create(*args, **kwargs)
def get_object_with_related_or_404(klass, *args, **kwargs):
@@ -34,8 +34,8 @@ def get_object_with_related_or_404(klass, *args, **kwargs):
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
def get_random_string(number=10, prefix=''):
- allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
- if prefix:
- prefix = '%s-' % prefix
- return '%s%s' % (prefix, ''.join([choice(allowed_chars) for i in range(number)]))
-
+ allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
+ if prefix:
+ prefix = '%s-' % prefix
+ return '%s%s' % (prefix, ''.join([choice(allowed_chars) for i in range(number)]))
+
View
23 flightdeck/base/tests.py
@@ -1,23 +0,0 @@
-"""
-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
29 flightdeck/base/views.py
@@ -1,23 +1,20 @@
-from django.http import Http404, HttpResponseRedirect, HttpResponse
-from django.shortcuts import render_to_response, get_object_or_404
-from django.conf import settings
-from django.template import RequestContext#,Template
-from django.contrib import messages
+from django.template import RequestContext
+from django.shortcuts import render_to_response
from jetpack.models import Package
-from jetpack import settings as jp_settings
+from jetpack import conf
def homepage(r):
- # one more for the main one
- addons_limit = jp_settings.HOMEPAGE_PACKAGES_NUMBER
+ # one more for the main one
+ addons_limit = conf.HOMEPAGE_PACKAGES_NUMBER
- libraries = Package.objects.libraries()[:jp_settings.HOMEPAGE_PACKAGES_NUMBER]
- addons = Package.objects.addons()[:addons_limit]
+ libraries = Package.objects.libraries()[:conf.HOMEPAGE_PACKAGES_NUMBER]
+ addons = Package.objects.addons()[:addons_limit]
- addons = list(addons)
- page = 'homepage'
+ addons = list(addons)
+ page = 'homepage'
- return render_to_response(
- 'homepage.html',
- locals(),
- context_instance=RequestContext(r))
+ return render_to_response(
+ 'homepage.html',
+ locals(),
+ context_instance=RequestContext(r))
View
19 flightdeck/person/__init__.py
@@ -1,19 +0,0 @@
-# Taken from feincms
-# http://github.com/matthiask/feincms/blob/master/feincms/__init__.py
-
-# Do not use Django settings at module level as recommended
-from django.utils.functional import LazyObject
-
-class LazySettings(LazyObject):
- def _setup(self):
- from person import default_settings
- self._wrapped = Settings(default_settings)
-
-class Settings(object):
- def __init__(self, settings_module):
- for setting in dir(settings_module):
- if setting == setting.upper():
- setattr(self, setting, getattr(settings_module, setting))
-
-settings = LazySettings()
-
View
8 flightdeck/person/default_settings.py → flightdeck/person/conf.py
@@ -2,12 +2,12 @@
PACKAGES_PER_PAGE = getattr(settings, 'PACKAGES_PER_PAGE', 10)
PACKAGE_PLURAL_NAMES = {
- 'l': 'libraries',
- 'a': 'addons'
+ 'l': 'libraries',
+ 'a': 'addons'
}
PACKAGE_SINGULAR_NAMES = {
- 'l': 'library',
- 'a': 'addon'
+ 'l': 'library',
+ 'a': 'addon'
}
# ------------------------------------------------------------------------
View
8 flightdeck/person/context_processors.py
@@ -1,6 +1,6 @@
def profile(request):
- try:
- return {'profile': request.user.get_profile()}
- except:
- return {}
+ try:
+ return {'profile': request.user.get_profile()}
+ except:
+ return {}
View
39 flightdeck/person/forms.py
@@ -1,33 +1,32 @@
-from django.conf import settings
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm as ContribAuthenticationForm
from django.utils.translation import ugettext_lazy as _
class AuthenticationForm(ContribAuthenticationForm):
- username = forms.CharField(label=_("Email address"), max_length=255)
-
- def clean(self):
- username = self.cleaned_data.get('username')
- password = self.cleaned_data.get('password')
+ username = forms.CharField(label=_("Email address"), max_length=255)
- if username and password:
- try:
- self.user_cache = authenticate(username=username, password=password)
- except Exception as err:
- raise forms.ValidationError(_("Authentication process is broken please <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=570360\">let us know</a><br>%s" % err.__str__()))
+ def clean(self):
+ username = self.cleaned_data.get('username')
+ password = self.cleaned_data.get('password')
- if self.user_cache is None:
- raise forms.ValidationError(_("""Your email and addons.mozilla.org password didn't match.
+ if username and password:
+ try:
+ self.user_cache = authenticate(username=username, password=password)
+ except Exception as err:
+ raise forms.ValidationError(_("Authentication process is broken please <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=570360\">let us know</a><br>%s" % err.__str__()))
+
+ if self.user_cache is None:
+ raise forms.ValidationError(_("""Your email and addons.mozilla.org password didn't match.
Please try again.
Note that both fields are case-sensitive."""))
- elif not self.user_cache.is_active:
- raise forms.ValidationError(_("This account is inactive."))
+ elif not self.user_cache.is_active:
+ raise forms.ValidationError(_("This account is inactive."))
- # TODO: determine whether this should move to its own method.
- if self.request:
- if not self.request.session.test_cookie_worked():
- raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
+ # TODO: determine whether this should move to its own method.
+ if self.request:
+ if not self.request.session.test_cookie_worked():
+ raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
- return self.cleaned_data
+ return self.cleaned_data
View
50 flightdeck/person/models.py
@@ -3,31 +3,31 @@
class Limit(models.Model):
- email = models.CharField(max_length=255)
+ email = models.CharField(max_length=255)
class Profile(models.Model):
- user = models.ForeignKey(User, unique=True)
- nickname = models.CharField(max_length=255, blank=True, null=True)
- location = models.CharField(max_length=255, blank=True, null=True)
- occupation = models.CharField(max_length=255, blank=True, null=True)
- homepage = models.CharField(max_length=255, blank=True, null=True)
- photo = models.CharField(max_length=255, blank=True, null=True)
-
- def get_name(self):
- if not (self.user.first_name or self.user.last_name or self.nickname):
- return self.user.username
- return self.get_fullname()
-
-
- def get_fullname(self):
- name = self.user.first_name if self.user.first_name else None
- if self.user.last_name:
- name = '%s %s' % (name, self.user.last_name) if name else self.user.last_name
- if not name and self.nickname:
- return self.nickname
- return name
-
-
- def __unicode__(self):
- return self.get_name()
+ user = models.ForeignKey(User, unique=True)
+ nickname = models.CharField(max_length=255, blank=True, null=True)
+ location = models.CharField(max_length=255, blank=True, null=True)
+ occupation = models.CharField(max_length=255, blank=True, null=True)
+ homepage = models.CharField(max_length=255, blank=True, null=True)
+ photo = models.CharField(max_length=255, blank=True, null=True)
+
+ def get_name(self):
+ if not (self.user.first_name or self.user.last_name or self.nickname):
+ return self.user.username
+ return self.get_fullname()
+
+
+ def get_fullname(self):
+ name = self.user.first_name if self.user.first_name else None
+ if self.user.last_name:
+ name = '%s %s' % (name, self.user.last_name) if name else self.user.last_name
+ if not name and self.nickname:
+ return self.nickname
+ return name
+
+
+ def __unicode__(self):
+ return self.get_name()
View
34 flightdeck/person/tests.py
@@ -5,23 +5,23 @@
class ProfileTest(TestCase):
- def setUp(self):
- self.user = User(
- username='jdoe',
- first_name='John',
- last_name='Doe'
- )
- self.user.save()
+ def setUp(self):
+ self.user = User(
+ username='jdoe',
+ first_name='John',
+ last_name='Doe'
+ )
+ self.user.save()
- self.profile = Profile()
- self.profile.user = self.user
- self.profile.nickname = 'doer'
+ self.profile = Profile()
+ self.profile.user = self.user
+ self.profile.nickname = 'doer'
- self.profile.save()
-
- def tearDown(self):
- self.profile.delete()
- self.user.delete()
+ self.profile.save()
- def test_get_fullname(self):
- self.assertEqual(self.user.get_profile().get_fullname(), 'John Doe')
+ def tearDown(self):
+ self.profile.delete()
+ self.user.delete()
+
+ def test_get_fullname(self):
+ self.assertEqual(self.user.get_profile().get_fullname(), 'John Doe')
View
46 flightdeck/person/urls.py
@@ -1,36 +1,36 @@
-from django.conf.urls.defaults import *
+from django.conf.urls.defaults import url, patterns
from django.contrib.auth.views import login, logout
from forms import AuthenticationForm
urlpatterns = patterns('person.views',
- url(r'^signin/$', login, {'authentication_form': AuthenticationForm}, name='login'),
- url(r'^signout/$', logout, {"next_page": "/"}, name='logout'),
+ url(r'^signin/$', login, {'authentication_form': AuthenticationForm}, name='login'),
+ url(r'^signout/$', logout, {"next_page": "/"}, name='logout'),
- # dashboard
+ # dashboard
url(r'dashboard/$','dashboard', name='person_dashboard'),
- # disabled
- url(r'^disabled_addons/$',
- 'dashboard_browser', {'type': 'a', 'disabled': True}, name='person_disabled_addons'),
- url(r'^disabled_libraries/$',
- 'dashboard_browser', {'type': 'l', 'disabled': True}, name='person_disabled_libraries'),
- url(r'^disabled_addons/(?P<page_number>\d+)/$',
- 'dashboard_browser', {'type': 'a', 'disabled': True}, name='person_disabled_addons_page'),
- url(r'^disabled_libraries/(?P<page_number>\d+)/$',
- 'dashboard_browser', {'type': 'l', 'disabled': True}, name='person_disabled_libraries_page'),
+ # disabled
+ url(r'^disabled_addons/$',
+ 'dashboard_browser', {'type': 'a', 'disabled': True}, name='person_disabled_addons'),
+ url(r'^disabled_libraries/$',
+ 'dashboard_browser', {'type': 'l', 'disabled': True}, name='person_disabled_libraries'),
+ url(r'^disabled_addons/(?P<page_number>\d+)/$',
+ 'dashboard_browser', {'type': 'a', 'disabled': True}, name='person_disabled_addons_page'),
+ url(r'^disabled_libraries/(?P<page_number>\d+)/$',
+ 'dashboard_browser', {'type': 'l', 'disabled': True}, name='person_disabled_libraries_page'),
- # packages
- url(r'^addons/$',
- 'dashboard_browser', {'type': 'a'}, name='person_addons'),
- url(r'^libraries/$',
- 'dashboard_browser', {'type': 'l'}, name='person_libraries'),
- url(r'^addons/(?P<page_number>\d+)/$',
- 'dashboard_browser', {'type': 'a'}, name='person_addons_page'),
- url(r'^libraries/(?P<page_number>\d+)/$',
- 'dashboard_browser', {'type': 'l'}, name='person_libraries_page'),
+ # packages
+ url(r'^addons/$',
+ 'dashboard_browser', {'type': 'a'}, name='person_addons'),
+ url(r'^libraries/$',
+ 'dashboard_browser', {'type': 'l'}, name='person_libraries'),
+ url(r'^addons/(?P<page_number>\d+)/$',
+ 'dashboard_browser', {'type': 'a'}, name='person_addons_page'),
+ url(r'^libraries/(?P<page_number>\d+)/$',
+ 'dashboard_browser', {'type': 'l'}, name='person_libraries_page'),
- # public profile
+ # public profile
url(r'^(?P<username>\w+)/$','public_profile', name='person_public_profile'),
)
View
94 flightdeck/person/views.py
@@ -6,68 +6,68 @@
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage, EmptyPage
-from person import settings
+from person import conf
from person.models import Profile
def public_profile(r, username, force=None):
- """
- Public profile
- """
- page = "profile"
- person = get_object_or_404(User, username=username)
- profile = person.get_profile()
- addons = person.packages_originated.addons()
- libraries = person.packages_originated.libraries()
- # if owner of the profile and not specially wanted to see it - redirect to dashboard
- return render_to_response("profile.html", locals(),
- context_instance=RequestContext(r))
+ """
+ Public profile
+ """
+ page = "profile"
+ person = get_object_or_404(User, username=username)
+ profile = person.get_profile()
+ addons = person.packages_originated.addons()
+ libraries = person.packages_originated.libraries()
+ # if owner of the profile and not specially wanted to see it - redirect to dashboard
+ return render_to_response("profile.html", locals(),
+ context_instance=RequestContext(r))
def get_packages(person):
- addons = person.packages_originated.addons()
- libraries = person.packages_originated.libraries()
- disabled_addons = person.packages_originated.disabled().filter(type='a')
- disabled_libraries = person.packages_originated.disabled().filter(type='l')
- return addons, libraries, disabled_addons, disabled_libraries
+ addons = person.packages_originated.addons()
+ libraries = person.packages_originated.libraries()
+ disabled_addons = person.packages_originated.disabled().filter(type='a')
+ disabled_libraries = person.packages_originated.disabled().filter(type='l')
+ return addons, libraries, disabled_addons, disabled_libraries
@login_required
def dashboard(r):
- """
- Dashboard of the user
- """
- page = "dashboard"
- person = r.user
- addons, libraries, disabled_addons, disabled_libraries = get_packages(person)
- return render_to_response("user_dashboard.html", locals(),
- context_instance=RequestContext(r))
+ """
+ Dashboard of the user
+ """
+ page = "dashboard"
+ person = r.user
+ addons, libraries, disabled_addons, disabled_libraries = get_packages(person)
+ return render_to_response("user_dashboard.html", locals(),
+ context_instance=RequestContext(r))
@login_required
def dashboard_browser(r, page_number=1, type=None, disabled=False):
- """
- Display a list of addons or libraries with pages
- Filter based on the request (type, username).
- """
+ """
+ Display a list of addons or libraries with pages
+ Filter based on the request (type, username).
+ """
- author = r.user
- packages = author.packages_originated.disabled() if disabled else author.packages_originated.active()
+ author = r.user
+ packages = author.packages_originated.disabled() if disabled else author.packages_originated.active()
- if type:
- other_type = 'l' if type == 'a' else 'a'
- other_packages_number = len(packages.filter(type=other_type))
- packages = packages.filter(type=type)
- template_suffix = settings.PACKAGE_PLURAL_NAMES[type]
+ if type:
+ other_type = 'l' if type == 'a' else 'a'
+ other_packages_number = len(packages.filter(type=other_type))
+ packages = packages.filter(type=type)
+ template_suffix = conf.PACKAGE_PLURAL_NAMES[type]
- limit = r.GET.get('limit', settings.PACKAGES_PER_PAGE)
+ limit = r.GET.get('limit', conf.PACKAGES_PER_PAGE)
- pager = Paginator(
- packages,
- per_page = limit,
- orphans = 1
- ).page(page_number)
-
- addons, libraries, disabled_addons, disabled_libraries = get_packages(author)
+ pager = Paginator(
+ packages,
+ per_page = limit,
+ orphans = 1
+ ).page(page_number)
- return render_to_response(
- 'user_%s.html' % template_suffix, locals(),
- context_instance=RequestContext(r))
+ addons, libraries, disabled_addons, disabled_libraries = get_packages(author)
+
+ return render_to_response(
+ 'user_%s.html' % template_suffix, locals(),
+ context_instance=RequestContext(r))
View
1  flightdeck/settings_local-default.py
@@ -1,5 +1,4 @@
import os.path
-import re
FRAMEWORK_PATH = os.path.dirname(os.path.dirname(__file__)) +'/'
View
3  flightdeck/tutorial/models.py
@@ -1,3 +0,0 @@
-from django.db import models
-
-# Create your models here.
View
23 flightdeck/tutorial/tests.py
@@ -1,23 +0,0 @@
-"""
-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
47 flightdeck/urls.py
@@ -1,6 +1,6 @@
-from django.conf.urls.defaults import *
+from django.conf.urls.defaults import url, patterns, include
from django.views import static
-from django.conf import settings
+from django.conf import settings
from django.contrib import admin
from flightdeck.base import views as base_views
@@ -9,37 +9,32 @@
urls = [
- # home
- url(r'^$',base_views.homepage, name='home'),
- ]
+ # home
+ url(r'^$',base_views.homepage, name='home'),
+ ]
if settings.DEBUG:
- try:
- import grappelli
- urls.append((r'^grappelli/', include('grappelli.urls')))
- except:
- ""
- # admin
- urls.extend([
- (r'^admin/doc/', include('django.contrib.admindocs.urls')),
- (r'^admin/', include(admin.site.urls))
- ])
+ # admin
+ urls.extend([
+ (r'^admin/doc/', include('django.contrib.admindocs.urls')),
+ (r'^admin/', include(admin.site.urls))
+ ])
urls.extend([
- # static files
- # this should be used only in development server
- # please refer to http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/#serving-media-files
- url(r'^media/(?P<path>.*)$', static.serve, {'document_root': settings.MEDIA_ROOT}, name='media'),
+ # static files
+ # this should be used only in development server
+ # please refer to http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/#serving-media-files
+ url(r'^media/(?P<path>.*)$', static.serve, {'document_root': settings.MEDIA_ROOT}, name='media'),
- # API Browser
- (r'^api/', include('api.urls')),
+ # API Browser
+ (r'^api/', include('api.urls')),
- # Tutorial
- (r'^tutorial/', include('tutorial.urls')),
+ # Tutorial
+ (r'^tutorial/', include('tutorial.urls')),
- # Jetpack
- (r'^user/', include('person.urls')),
- (r'', include('jetpack.urls'))
+ # Jetpack
+ (r'^user/', include('person.urls')),
+ (r'', include('jetpack.urls'))
])
urlpatterns = patterns('', *urls)
View
4 flightdeck/urls_local-default.py
@@ -1,7 +1,7 @@
-from django.conf.urls.defaults import *
+from django.conf.urls.defaults import url, patterns, include
urlpatterns = patterns('flightdeck.base.views',
url(r'^$','placeholder', name='placeholder'),
)
-
+
View
10 flightdeck/utils.py
@@ -1,10 +0,0 @@
-from random import choice
-
-CHARS='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
-
-def random_string(length=10, prefix=''):
- random_length = length - len(prefix)
- if random_length <= 0:
- return prefix
- return (prefix + ''.join([choice(CHARS) for i in range(random_length)]))[0:length]
-
View
10 flightdeck/utils/__init__.py
@@ -0,0 +1,10 @@
+from random import choice
+
+CHARS='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
+
+def random_string(length=10, prefix=''):
+ random_length = length - len(prefix)
+ if random_length <= 0:
+ return prefix
+ return (prefix + ''.join([choice(CHARS) for i in range(random_length)]))[0:length]
+
Please sign in to comment.
Something went wrong with that request. Please try again.