Repository: appliedsec/djangular Branch: master Commit: 8d6bc26cd70b Files: 45 Total size: 48.1 KB Directory structure: gitextract_gczgbp39/ ├── .coveragerc ├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── README.md ├── djangular/ │ ├── __init__.py │ ├── config/ │ │ └── angularseed_template/ │ │ └── angular/ │ │ ├── app.css │ │ ├── app.js │ │ ├── components/ │ │ │ └── version/ │ │ │ ├── interpolate-filter.js │ │ │ ├── interpolate-filter_test.js │ │ │ ├── version-directive.js │ │ │ ├── version-directive_test.js │ │ │ ├── version.js │ │ │ └── version_test.js │ │ ├── index.html │ │ ├── view1/ │ │ │ ├── view1.html │ │ │ ├── view1.js │ │ │ └── view1_test.js │ │ └── view2/ │ │ ├── view2.html │ │ ├── view2.js │ │ └── view2_test.js │ ├── finders.py │ ├── management/ │ │ ├── __init__.py │ │ └── commands/ │ │ ├── __init__.py │ │ └── startangularapp.py │ ├── middleware.py │ ├── models.py │ ├── static/ │ │ └── js/ │ │ └── resource_patch.js │ ├── storage.py │ ├── templates/ │ │ └── djangular_module.js │ ├── tests/ │ │ ├── __init__.py │ │ ├── test_base.py │ │ ├── test_commands.py │ │ ├── test_finders.py │ │ ├── test_middleware.py │ │ ├── test_storage.py │ │ ├── test_urls.py │ │ ├── test_utils.py │ │ └── unit/ │ │ └── filterSpec.js │ ├── urls.py │ ├── utils.py │ └── views.py ├── runtests.py └── setup.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .coveragerc ================================================ [report] # Regexes for lines to exclude from consideration exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain about missing debug-only code: def __repr__ if self\.debug def __unicode__ def __repr__ if settings.DEBUG raise NotImplementedError from django\. # Don't complain if tests don't hit defensive assertion code: raise AssertionError raise NotImplementedError # Don't complain if non-runnable code isn't run: if 0: if __name__ == .__main__.: [run] omit = *tests* *migrations* *site-packages* *src* *settings* ================================================ FILE: .gitignore ================================================ *.log *.pot *.pyc local_settings.py .DS_Store .idea .hg .hgignore dist djangular.egg-info .coverage ================================================ FILE: .travis.yml ================================================ language: python python: - "2.7" install: - pip install coverage - pip install $DJANGO script: - coverage run runtests.py - coverage report -m env: - DJANGO="Django==1.5.12" - DJANGO="Django==1.6.11" - DJANGO="Django==1.7.11" - DJANGO="Django==1.8.12" - DJANGO="Django==1.9.5" ================================================ FILE: LICENSE ================================================ Copyright 2013 Applied Security Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: MANIFEST.in ================================================ recursive-include djangular * include LICENSE include README.md ================================================ FILE: README.md ================================================ djangular ========= A reusable app that provides better app integration with AngularJS. Djangular allows you to create AngularJS content per app, instead of creating a single massive AngularJS application inside of Django. This allows you to selectively use apps per site, as well as create a consistent structure across all of your Django apps. This is intended to be a Django version of the angular-seed project (https://github.com/angular/angular-seed). The current mindset is to limit the amount of changes introduced by Djangular. Features -------- + Allows namespacing AngularJS content per Django app. This allows the AngularJS apps and modules to be included (or not) based on Django's settings, and enforces a consistent structure to your Django/AngularJS apps. + Includes an AngularJS module that includes a subset of features similar to what Django provides in its templates. + Adds a patch to AngularJS's $resource module, to enable end of URL slashes that Django requires. + Improves security by enabling of CSRF protection and JSON Vulnerability between Django and AngularJS. + ~~Scripts to allow running JS Unit and E2E tests, similar to the Django test command.~~ This was removed for the time being and will be (re-)included in a future release. + Does not dictate how you use AngularJS inside your Django app. Requirements ------------ + Currently requires Python 2.7. + Supports Django >= 1.5, <= 1.9 + Supports AngularJS 1.2+ (including 1.3.x). + ~~Local installs of Node.js and Karma for testing.~~ Installation ------------ + You may install directly from pypi: pip install djangular + Or download the source and install it in a terminal/console: python setup.py install + Or download the source and move the djangular directory inside your django project as an app (this is the least recommended approach). + Djangular needs to be placed as an app inside a Django project and added to the INSTALLED_APPS setting. INSTALLED_APPS = ( ... 'djangular', ... ) + You will need to obtain a version of AngularJS and place it in the `static` folder of one of your Django apps. Djangular no longer includes a version of AngularJS, since it updates too frequently. Including AngularJS content in your Django Apps ----------------------------------------------- The most popular feature of Djangular, this will both include and namespace your AngularJS content inside your Django apps. Each Django app has its own "angular" folder, with a layout matching the angular-seed project. As a result, the URLs for these get grouped into the `STATIC_URL` structure of Django. + The staticfiles contrib library will need to be included in the INSTALLED_APPS setting. INSTALLED_APPS = ( ... 'django.contrib.staticfiles', 'djangular', ... ) + The STATICFILES_FINDERS needs to be updated to include `djangular.finders.NamespacedAngularAppDirectoriesFinder`. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'djangular.finders.NamespacedAngularAppDirectoriesFinder' ) + Because of this new finder, the `findstatic` and `collectstatic` commands will place the angular files in each app in an associated an `/` folder. You will not need to namespace each of your static directories with the name of your Django application (unless you really want to). * Example: If you have a Django app named `foo` and you are using the default `STATIC_URL` in your settings, the main AngularJS module named `foo` would be found at `foo/angular/app.js` on the file system and at `static/foo/app.js` from the browser. * This namespacing is done automatically. This a `foo` app and a `bar` app can both have an `app.js` inside their `angular` directories, and they will not collide. * Note: Because of these URLs, referring to AngularJS content in a separate app should use a `..//` URL. This will help significantly during testing to make sure paths are correct. * Note: It is recommended to namespace the AngularJS code the same name as the Django app. The created JS files do this already. + To create an app that is already setup with the djangular (or angular-seed) structure, run `python manage.py startangularapp ` from the command line. This will create the files and directory structures needed for you to get started. Including some Django template-like features in your AngularJS templates ------------------------------------------------------------------------ One of the challenges in using AngularJS inside of Django is that you may not have access to some needed variables that are always included in Django templates. Djangular includes an AngularJS module to help with that. + To use the AngularJS module that Djangular provides you, you'll need to add the djangular app to your projects URLs. urlpatterns = patterns('', ... url(r'^djangular/', include('djangular.urls')), ... ) + Alternatively, you may specify the DjangularModuleTemplateView specifically, and customize the url. from djangular.views import DjangularModuleTemplateView ... urlpatterns = patterns('', ... url(r'/djangular.js', DjangularModuleTemplateView.as_view()), ... ) This will add a `djangular` AngularJS module to your front end code. This module includes a `DjangoProperties` constant that includes whether the current user is authenticated, the username, groups and roles of the current user and the static and media urls from Django settings. It also includes a `django` filter, which does some basic substitution based on the properties constant. Enforcing the end slashes of your AngularJS Resources ----------------------------------------------------- $resource is a convenient way to create REST-like services in AngularJS. However, there currently [is a bug](https://github.com/angular/angular.js/issues/992) in $resource that will strip the ending slash, which means that $resource is unusable unless `settings.APPEND_SLASHES` is set to `FALSE`. Djangular used to patch this automatically, but it now includes a separate file (`djangular/static/js/resource_patch.js`) to handle this issue. Simply include that javascript file in your page after you have loaded `angular-resource.js` and ending slashes will be preserved in $resource. Enabling CSRF protection in AngularJS Templates ----------------------------------------------- Djangular includes a JSON Vulnerability middleware that AngularJS knows how to process. To include this protection, add `djangular.middleware.AngularJsonVulnerabilityMiddleware` to the `MIDDLEWARE_CLASSES` setting. This only affects JSON requests (based on Content-Type), so this can be located fairly low in the middleware stack. MIDDLEWARE_CLASSES = ( ... 'djangular.middleware.AngularJsonVulnerabilityMiddleware' ) Once you have enabled CSRF protection in Django by adding the middleware `django.middleware.csrf.CsrfViewMiddleware` to the `MIDDLEWARE_CLASSES` setting, you may use the same protection in AngularJS templates in addition to Django template. There are two different ways to enable this protection via djangular: + Make your main app dependent on the `djangular` module and use the included `csrf-token` directive (that wraps the Django `csrf_token` template tag) inside the appropriate `form` tags in your HTML. // Inside your JavaScript angular.module('myApp', ['djangular', ...]); ...
...
+ Make your main app dependent on the `djangular.csrf`, which will add the appropriate CSRF Token Header in all POSTs, PUTs and DELETEs. Note that this way is vulnerable to cross-site scripting if you make a post to a domain outside your control. angular.module('myApp', ['djangular.csrf', ...]); If you allow a user to login (or logout) and don't redirect or reload the page, the tags and cookies provided by both methods above will be stale. The second option (using the `djangular.csrf` module) provides a `UpdateCSRFToken` function that can be invoked with the new CSRF Token value. Using Djangular in your Django Project -------------------------------------- This section describes some best practices in using Djangular. Please note that these are guidelines and recommendations, but not the only way to use this project. #### AngularJS as purely static content #### The first way to use djangular is to have all of your static content live inside an angular app. This is perhaps the "most correct" way from an AngularJS standpoint and perhaps the "least correct" way from a traditional Django perspective. In doing this, you are only (or almost only) serving content from your static domain and your Django development becomes strictly back-end focused for REST and/or service calls. Few to none of your Django views will produce HTML. You can provide a redirect from a Django view to your static pages (if you like), although this can seem strange when your static content is served from a completely different domain. You may need to configure your web servers to allow remote Ajax calls from your static domain. This approach allows you to use AngularJS with any number of back-ends, as (again) your Django app becomes an API for your AngularJS code to call. This approach can be very different from how your application is currently architected. From our experience, if you decide to do this, we would recommend using local, relative URLs to navigate between the apps instead of specifying the full URL. However, there are times when you will need to specify the full URL. There is an AngularJS module called `djangular` that is rendered via the Django templating engine to obtain common template variables like the `STATIC_URL`, `MEDIA_URL`, the User object, etc. This app includes a service called `DjangoProperties`, which will enable you to get access to those variables, and a `django` filter, which follows the standard AngularJS filtering rules. The URL for this JavaScript is `/djangular/app.js` (note that is not static). The following is a sample route config that uses the aforementioned djangular angular app. Because AngularJS has not set up the $filter directive during the route configuration, the DjangoProperties constant is the only way to obtain the STATIC_URL. Using 'sample' as the name of the Django/AngularJS app: ```javascript angular.module('sample', [ 'djangular', 'sample.filters', 'sample.services', 'sample.directives', 'sample.controllers' ]).config([ '$routeProvider','DjangoProperties', function($routeProvider, DjangoProperties) { $routeProvider.when('/view1', { templateUrl: DjangoProperties.STATIC_URL + 'sample/view1/view1.html', controller: 'View1Ctrl'}); $routeProvider.when('/view2', { templateUrl: DjangoProperties.STATIC_URL + 'sample/view2/view2.html', controller: 'View2Ctrl'}); $routeProvider.otherwise({redirectTo: '/view1'}); } ]); ``` #### Django Templates as AngularJS Templates #### Another way to integrate is to use your Django templates as your AngularJS templates. To do this, we highly recommend using Django 1.5 and heavy use of the `{% verbatim %}` tag, since the Django and AngularJS templating syntaxes are identical. The big advantage of this is that it allows you to use all of the existing template tags and ways of thinking that you are accustomed to using. If you are integrating AngularJS into an existing Django project, this will seem the most appealing. The downsides to this method are the following: + The AngularJS developers recommend not doing this, because it is very easy to get confused about which part of the template is being rendered on the server side and which is being rendered on the client side. Almost every developer on our team has tripped on this once or twice. + The vast majority of HTML that your app is producing is the same on every load... and should be static. However, without some cache configuration, the server will have to render the content on every single request, resulting in poorer performance. #### Using Django Templates to render the skeleton of the app #### What our team currently does is use a Django Template to render the skeleton of every page, but the rest of the page (the partials, CSS and JS) are all included in the AngularJS app. This way, none of the CSS/JS dependencies are duplicated in multiple places. When our app renders the content, we pass in two variables to the RequestContext (and thus, to the template). The `app_name`, which is the name of the app, and `app_dependencies`, which is a list of app names whom the AngularJS app is dependent on. We make heavy use of Django Rest Framework (http://django-rest-framework.org/) to produce our views/REST Services and Django Pipeline (https://github.com/cyberdelia/django-pipeline) to do our app packaging and JS/CSS Compression. The template (more or less) looks like the following: ```html {% load compressed %} App Title {% for dependency in app_dependencies %} {% compressed_css dependency %} {% endfor %} {% compressed_css app_name %} {% for dependency in app_dependencies %} {% compressed_js dependency %} {% endfor %} {% compressed_js app_name %}
``` ================================================ FILE: djangular/__init__.py ================================================ ================================================ FILE: djangular/config/angularseed_template/angular/app.css ================================================ /* app css stylesheet */ .menu { list-style: none; border-bottom: 0.1em solid black; margin-bottom: 2em; padding: 0 0 0.5em; } .menu:before { content: "["; } .menu:after { content: "]"; } .menu > li { display: inline; } .menu > li:before { content: "|"; padding-right: 0.3em; } .menu > li:nth-child(1):before { content: ""; padding: 0; } ================================================ FILE: djangular/config/angularseed_template/angular/app.js ================================================ 'use strict'; // Declare app level module which depends on views, and components angular.module('{{ app_name }}', [ 'ngRoute', '{{ app_name }}.view1', '{{ app_name }}.view2', '{{ app_name }}.version' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); }]); ================================================ FILE: djangular/config/angularseed_template/angular/components/version/interpolate-filter.js ================================================ 'use strict'; angular.module('{{ app_name }}.version.interpolate-filter', []) .filter('interpolate', ['version', function(version) { return function(text) { return String(text).replace(/\%VERSION\%/mg, version); }; }]); ================================================ FILE: djangular/config/angularseed_template/angular/components/version/interpolate-filter_test.js ================================================ 'use strict'; describe('{{ app_name }}.version module', function() { beforeEach(module('{{ app_name }}.version')); describe('interpolate filter', function() { beforeEach(module(function($provide) { $provide.value('version', 'TEST_VER'); })); it('should replace VERSION', inject(function(interpolateFilter) { expect(interpolateFilter('before %VERSION% after')).toEqual('before TEST_VER after'); })); }); }); ================================================ FILE: djangular/config/angularseed_template/angular/components/version/version-directive.js ================================================ 'use strict'; angular.module('{{ app_name }}.version.version-directive', []) .directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]); ================================================ FILE: djangular/config/angularseed_template/angular/components/version/version-directive_test.js ================================================ 'use strict'; describe('{{ app_name }}.version module', function() { beforeEach(module('{{ app_name }}.version')); describe('app-version directive', function() { it('should print current version', function() { module(function($provide) { $provide.value('version', 'TEST_VER'); }); inject(function($compile, $rootScope) { var element = $compile('')($rootScope); expect(element.text()).toEqual('TEST_VER'); }); }); }); }); ================================================ FILE: djangular/config/angularseed_template/angular/components/version/version.js ================================================ 'use strict'; angular.module('{{ app_name }}.version', [ '{{ app_name }}.version.interpolate-filter', '{{ app_name }}.version.version-directive' ]) .value('version', '0.1'); ================================================ FILE: djangular/config/angularseed_template/angular/components/version/version_test.js ================================================ 'use strict'; describe('{{ app_name }}.version module', function() { beforeEach(module('{{ app_name }}.version')); describe('version service', function() { it('should return current version', inject(function(version) { expect(version).toEqual('0.1'); })); }); }); ================================================ FILE: djangular/config/angularseed_template/angular/index.html ================================================ My AngularJS App
Angular seed app: v
================================================ FILE: djangular/config/angularseed_template/angular/view1/view1.html ================================================

This is the partial for view 1.

================================================ FILE: djangular/config/angularseed_template/angular/view1/view1.js ================================================ 'use strict'; angular.module('{{ app_name }}.view1', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1', { templateUrl: 'view1/view1.html', controller: 'View1Ctrl' }); }]) .controller('View1Ctrl', [function() { }]); ================================================ FILE: djangular/config/angularseed_template/angular/view1/view1_test.js ================================================ 'use strict'; describe('{{ app_name }}.view1 module', function() { beforeEach(module('{{ app_name }}.view1')); describe('view1 controller', function(){ it('should ....', inject(function($controller) { //spec body var view1Ctrl = $controller('View1Ctrl'); expect(view1Ctrl).toBeDefined(); })); }); }); ================================================ FILE: djangular/config/angularseed_template/angular/view2/view2.html ================================================ {% verbatim %}

This is the partial for view 2.

Showing of 'interpolate' filter: {{ 'Current version is v%VERSION%.' | interpolate }}

{% endverbatim %} ================================================ FILE: djangular/config/angularseed_template/angular/view2/view2.js ================================================ 'use strict'; angular.module('{{ app_name }}.view2', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view2', { templateUrl: 'view2/view2.html', controller: 'View2Ctrl' }); }]) .controller('View2Ctrl', [function() { }]); ================================================ FILE: djangular/config/angularseed_template/angular/view2/view2_test.js ================================================ 'use strict'; describe('{{ app_name }}.view2 module', function() { beforeEach(module('{{ app_name }}.view2')); describe('view2 controller', function(){ it('should ....', inject(function($controller) { //spec body var view2Ctrl = $controller('View2Ctrl'); expect(view2Ctrl).toBeDefined(); })); }); }); ================================================ FILE: djangular/finders.py ================================================ import django from django.contrib.staticfiles import finders as s_finders # Django rewrote the staticfiles storage internals in 1.7, so... if django.get_version() >= '1.7': import os import re class NamespacedAppDirectoriesFinder(s_finders.AppDirectoriesFinder): """ A namedspace static files finder that looks in the angular directory of each app as specified in the source_dir attribute. """ prepend_source_dir = False def __init__(self, app_names=None, *args, **kwargs): super(NamespacedAppDirectoriesFinder, self).__init__( app_names, *args, **kwargs) for app_name, storage in self.storages.items(): storage.prefix = os.path.join(*(app_name.split('.'))) def find_in_app(self, app, path): if self.prepend_source_dir: prefixed_path = os.path.join(self.source_dir, *(app.split('.'))) else: prefixed_path = os.path.join(*(app.split('.'))) app_re = '^{}{}'.format(prefixed_path, os.sep) if re.match(app_re, path): return super(NamespacedAppDirectoriesFinder, self).find_in_app( app, re.sub(app_re, '', path) ) class NamespacedAngularAppDirectoriesFinder(NamespacedAppDirectoriesFinder): """ A static files finder that looks in the angular directory of each app. """ source_dir = 'angular' class NamespacedE2ETestAppDirectoriesFinder(NamespacedAppDirectoriesFinder): """ A static files finder that looks in the tests/e2e directory of each app. """ source_dir = os.path.join('tests', 'e2e') prepend_source_dir = True else: from . import storage class NamespacedAngularAppDirectoriesFinder(s_finders.AppDirectoriesFinder): """ A static files finder that looks in the angular directory of each app. """ storage_class = storage.NamespacedAngularAppStorage class NamespacedE2ETestAppDirectoriesFinder(s_finders.AppDirectoriesFinder): """ A static files finder that looks in the tests/e2e directory of each app. """ storage_class = storage.NamespacedE2ETestAppStorage class NamespacedLibTestAppDirectoriesFinder(s_finders.AppDirectoriesFinder): """ A static files finder that looks in the tests/lib directory of each app. """ storage_class = storage.NamespacedLibTestAppStorage ================================================ FILE: djangular/management/__init__.py ================================================ ================================================ FILE: djangular/management/commands/__init__.py ================================================ ================================================ FILE: djangular/management/commands/startangularapp.py ================================================ import django import os from django.core import management as mgmt from django.core.management.templates import TemplateCommand from djangular import utils class Command(utils.SiteAndPathUtils, TemplateCommand): help = ("Creates a Djangular app directory structure for the given app " "name in the current directory or optionally in the given " "directory.") if django.get_version() >= "1.7": requires_system_checks = False else: requires_model_validation = False def handle(self, name, target=None, **options): mgmt.call_command('startapp', name, target, **options) # Override the options to setup the template command. options.update({ 'template': os.path.join( self.get_djangular_root(), 'config', 'angularseed_template'), 'extensions': ['.html', '.js'], # Parse HTML And JS files 'files': ['app.css'] }) super(Command, self).handle( 'app', name, target or name, **options) ================================================ FILE: djangular/middleware.py ================================================ class AngularJsonVulnerabilityMiddleware(object): """ A middleware that inserts the AngularJS JSON Vulnerability request on JSON responses. """ # The AngularJS JSON Vulnerability content prefix. See http://docs.angularjs.org/api/ng.$http CONTENT_PREFIX = b")]}',\n" # Make this class easy to extend by allowing class level access. VALID_STATUS_CODES = [200, 201, 202] VALID_CONTENT_TYPES = ['application/json'] def process_response(self, request, response): if response.status_code in self.VALID_STATUS_CODES and response['Content-Type'] in self.VALID_CONTENT_TYPES: response.content = self.CONTENT_PREFIX + response.content return response ================================================ FILE: djangular/models.py ================================================ # No models needed. ================================================ FILE: djangular/static/js/resource_patch.js ================================================ try { if (angular.version.full > "1.3") { angular.module('ngResource').config([ '$resourceProvider', function($resourceProvider) { $resourceProvider.defaults.stripTrailingSlashes = false; } ]); } else { angular.module('ngResource').config([ '$provide', '$httpProvider', function($provide, $httpProvider) { $provide.decorator('$resource', function($delegate) { return function() { if (arguments.length > 0) { // URL arguments[0] = arguments[0].replace(/\/$/, '\\/'); } if (arguments.length > 2) { // Actions angular.forEach(arguments[2], function(action) { if (action && action.url) { action.url = action.url.replace(/\/$/, '\\/'); } }); } return $delegate.apply($delegate, arguments); }; }); $provide.factory('djangularEnforceSlashInterceptor', function() { return { request: function(config) { config.url = config.url.replace(/[\/\\]+$/, '/'); return config; } }; }); $httpProvider.interceptors.push('djangularEnforceSlashInterceptor'); } ]); } } catch (err) { console.log('The ngResource module could not be found.'); } ================================================ FILE: djangular/storage.py ================================================ import django if django.get_version() < '1.7': import os from re import sub from django.contrib.staticfiles.storage import AppStaticStorage class NamespacedAngularAppStorage(AppStaticStorage): """ A file system storage backend that takes an app module and works for the ``app`` directory of it. The app module will be included in the url for the content. """ source_dir = 'angular' def __init__(self, app, *args, **kwargs): """ Returns a static file storage if available in the given app. """ # app is the actual app module self.prefix = os.path.join(*(app.split('.'))) super(NamespacedAngularAppStorage, self).__init__(app, *args, **kwargs) def path(self, name): name = sub('^' + self.prefix + os.sep.encode('string-escape'), '', name) return super(NamespacedAngularAppStorage, self).path(name) class NamespacedE2ETestAppStorage(AppStaticStorage): """ A file system storage backend that takes an app module and works for the ``tests/e2e`` directory of it. The app module will be included in the url for the content. NOTE: This should only be used for end-to-end testing. """ source_dir = os.path.join('tests', 'e2e') def __init__(self, app, *args, **kwargs): """ Returns a static file storage if available in the given app. """ # app is the actual app module prefix_args = [self.source_dir] + app.split('.') self.prefix = os.path.join(*prefix_args) super(NamespacedE2ETestAppStorage, self).__init__(app, *args, **kwargs) class NamespacedLibTestAppStorage(AppStaticStorage): """ A file system storage backend that takes an app module and works for the ``tests/lib`` directory of it. The app module will be included in the url for the content. NOTE: This should only be used for end-to-end testing. """ source_dir = os.path.join('tests', 'lib') def __init__(self, app, *args, **kwargs): """ Returns a static file storage if available in the given app. """ # app is the actual app module prefix_args = app.split('.') + ['lib'] self.prefix = os.path.join(*prefix_args) super(NamespacedLibTestAppStorage, self).__init__(app, *args, **kwargs) ================================================ FILE: djangular/templates/djangular_module.js ================================================ // All template syntax is commented so this can be loaded as a normal JS file. // {% load static %} var djangular = angular.module('djangular', []). constant('DjangoProperties', { 'STATIC_URL': '{% get_static_prefix %}', 'MEDIA_URL': '{% get_media_prefix %}', 'USER_NAME': '{{ user.username|escapejs }}', 'GROUP_NAMES': [ // {% for group in user.groups.all %} '{{ group.name|escapejs }}', // {% endfor %} ], 'IS_AUTHENTICATED': 'True' === '{{ user.is_authenticated|escapejs }}', 'IS_STAFF': 'True' === '{{ user.is_staff }}', 'IS_SUPERUSER': 'True' === '{{ user.is_superuser }}' }). filter('django', ['DjangoProperties', function(DjangoProperties) { return function(text) { for (var constant in DjangoProperties) { text = text.replace('%' + constant + '%', DjangoProperties[constant]); text = text.replace(constant, DjangoProperties[constant]); } return text; } }]). directive('djangoHref', ['$filter', function($filter) { return { restrict: 'A', priority: 99, // same as ng-href link: function(scope, elem, attrs) { attrs.$observe('djangoHref', function(value) { if (!value) return; attrs.$set('href', $filter('django')(value)); }); } }; }]). directive('djangoSrc', ['$filter', function($filter) { return { restrict: 'A', priority: 99, // same as ng-src link: function(scope, elem, attrs) { attrs.$observe('djangoSrc', function(value) { if (!value) return; attrs.$set('src', $filter('django')(value)); }); } }; }]). directive('csrfToken', function() { return { restrict: 'E', template: "{% csrf_token %}" || "", replace: true }; }); // {% if not disable_csrf_headers %} // Assign the CSRF Token as needed, until Angular provides a way to do this properly (https://github.com/angular/angular.js/issues/735) var djangularCsrf = angular.module('djangular.csrf', ['ngCookies']). config(['$httpProvider', function($httpProvider) { // cache $httpProvider, as it's only available during config... djangularCsrf.$httpProvider = $httpProvider; }]). factory('UpdateCsrfToken', function() { return function(csrfToken) { djangularCsrf.$httpProvider.defaults.headers.post['X-CSRFToken'] = csrfToken; djangularCsrf.$httpProvider.defaults.headers.put['X-CSRFToken'] = csrfToken; if (!djangularCsrf.$httpProvider.defaults.headers.delete) djangularCsrf.$httpProvider.defaults.headers.delete = {}; djangularCsrf.$httpProvider.defaults.headers.delete['X-CSRFToken'] = csrfToken; }; }). run(['$cookies', 'UpdateCsrfToken', function($cookies, UpdateCsrfToken) { UpdateCsrfToken($cookies['csrftoken']); }]); // {% endif %} ================================================ FILE: djangular/tests/__init__.py ================================================ import django if django.VERSION < (1, 6): from djangular.tests.test_base import * from djangular.tests.test_finders import * from djangular.tests.test_middleware import * from djangular.tests.test_storage import * from djangular.tests.test_utils import * from djangular.tests.test_commands import * from djangular.tests.test_urls import * ================================================ FILE: djangular/tests/test_base.py ================================================ import django import os from django.test import SimpleTestCase BASE_DIR = os.path.abspath(os.path.dirname(__file__)) def _call_test_func(self, test_fn): apps = None need_to_call_unset = False if django.get_version() >= '1.7': from django.apps import apps if not apps.is_installed('djangular.config.angularseed_template'): apps.set_installed_apps(tuple([ 'djangular.config.angularseed_template'])) need_to_call_unset = True try: test_fn(self) finally: if apps and need_to_call_unset: apps.unset_installed_apps() def test_with_angularseed_template_as_django_app(test_fn): def fn(self): extra_init_py_files = [] try: # Temporarily make the template dirs into python modules by adding # the __init__.py files. for directory in [ 'config', os.path.join('config', 'angularseed_template')]: current_file_name = os.path.join( BASE_DIR, '..', directory, '__init__.py') current_file = open(current_file_name, 'w') extra_init_py_files.append(current_file) current_file.close() except Exception as e: self.fail('Could not create files due to {0}'.format(e.message)) else: _call_test_func(self, test_fn) finally: for py_file in extra_init_py_files: if os.path.exists(py_file.name): os.remove(py_file.name) compiled_file_name = '{0}c'.format(py_file.name) if os.path.exists(compiled_file_name): os.remove(compiled_file_name) return fn class TestAngularSeedAsPythonModuleTest(SimpleTestCase): @test_with_angularseed_template_as_django_app def test_init_py_created(self): self.assertTrue(os.path.exists('{0}/../config/__init__.py'.format(BASE_DIR))) ================================================ FILE: djangular/tests/test_commands.py ================================================ import os import shutil from django.test import TestCase from django.utils._os import upath from djangular.management.commands.startangularapp import Command as StartAngularAppCommand class StartAngularAppCommandTests(TestCase): def setUp(self): # Clean up app directory that is created test_dir = os.path.abspath(os.path.dirname(upath(__file__))) demo_app_path = os.path.join(test_dir, '../../demo') self.addCleanup(shutil.rmtree, demo_app_path) def test_runs(self): StartAngularAppCommand().handle('demo', verbosity=1) ================================================ FILE: djangular/tests/test_finders.py ================================================ import django import os from djangular.tests.test_base import test_with_angularseed_template_as_django_app from djangular import finders from django.test import SimpleTestCase APP_BASE_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) class NamespacedAngularAppDirectoriesFinderTest(SimpleTestCase): @test_with_angularseed_template_as_django_app def test_find(self): if django.get_version() >= '1.7': finder = finders.NamespacedAngularAppDirectoriesFinder( app_names=['djangular.config.angularseed_template']) else: finder = finders.NamespacedAngularAppDirectoriesFinder( apps=['djangular.config.angularseed_template']) self.assertEqual( finder.find('djangular/config/angularseed_template/index.html'), '{0}/config/angularseed_template/angular/index.html'.format( APP_BASE_DIR) ) class NamespacedE2ETestAppDirectoriesFinderTest(SimpleTestCase): @test_with_angularseed_template_as_django_app def test_find(self): self.skipTest('E2E Testing is not implemented yet...') if django.get_version() >= '1.7': finder = finders.NamespacedE2ETestAppDirectoriesFinder( app_names=['djangular.config.angularseed_template']) else: finder = finders.NamespacedE2ETestAppDirectoriesFinder( apps=['djangular.config.angularseed_template']) self.assertEqual( finder.find( 'tests/e2e/djangular/config/angularseed_template/runner.html'), '{0}/config/angularseed_template/tests/e2e/runner.html'.format( APP_BASE_DIR) ) ================================================ FILE: djangular/tests/test_middleware.py ================================================ from djangular import middleware from django.test import SimpleTestCase from django.http import HttpRequest, HttpResponse class AngularJsonVulnerabilityMiddlewareTest(SimpleTestCase): def test_that_middleware_does_nothing_to_html_requests(self): resp = HttpResponse(content_type='text/html', content='') mware = middleware.AngularJsonVulnerabilityMiddleware() mware.process_response(HttpRequest(), resp) self.assertEqual(resp.content, '') def test_that_middleware_does_nothing_to_js_requests(self): resp = HttpResponse(content_type='text/javascript', content='var blah = [];') mware = middleware.AngularJsonVulnerabilityMiddleware() mware.process_response(HttpRequest(), resp) self.assertEqual(resp.content, 'var blah = [];') def test_that_middleware_does_nothing_to_invalid_json_requests(self): resp = HttpResponse(content_type='application/json', content='[1, 2, 3]', status=400) mware = middleware.AngularJsonVulnerabilityMiddleware() mware.process_response(HttpRequest(), resp) self.assertEqual(resp.content, '[1, 2, 3]') def test_that_middleware_adds_prefix_to_valid_json_requests(self): resp = HttpResponse(content_type='application/json', content='[1, 2, 3]') mware = middleware.AngularJsonVulnerabilityMiddleware() mware.process_response(HttpRequest(), resp) self.assertEqual(resp.content, mware.CONTENT_PREFIX + '[1, 2, 3]') ================================================ FILE: djangular/tests/test_storage.py ================================================ import django if django.get_version() < '1.7': from djangular import storage from django.test import SimpleTestCase from djangular.tests.test_base import test_with_angularseed_template_as_django_app class NamespacedAppAngularStorageTest(SimpleTestCase): def test_source_dir_is_angular(self): self.assertEqual( storage.NamespacedAngularAppStorage.source_dir, 'angular') def test_prefix_is_given_app_name(self): app_storage = storage.NamespacedAngularAppStorage('djangular') self.assertEqual(app_storage.prefix, 'djangular') @test_with_angularseed_template_as_django_app def test_prefix_is_given_app_name_for_more_complicated_scenario(self): app_storage = storage.NamespacedAngularAppStorage( 'djangular.config.angularseed_template') self.assertEqual(app_storage.prefix, 'djangular/config/angularseed_template') class NamespacedE2ETestAppStorageTest(SimpleTestCase): def test_source_dir_is_tests(self): self.assertEqual( storage.NamespacedE2ETestAppStorage.source_dir, 'tests/e2e') def test_prefix_is_given_app_name(self): app_storage = storage.NamespacedE2ETestAppStorage('djangular') self.assertEqual(app_storage.prefix, 'tests/e2e/djangular') @test_with_angularseed_template_as_django_app def test_prefix_is_given_app_name_for_more_complicated_scenario(self): app_storage = storage.NamespacedE2ETestAppStorage( 'djangular.config.angularseed_template') self.assertEqual(app_storage.prefix, 'tests/e2e/djangular/config/angularseed_template') ================================================ FILE: djangular/tests/test_urls.py ================================================ from django.core.urlresolvers import reverse from django.test import TestCase class UrlsTests(TestCase): def test_urls_import(self): """Smoke test to make sure urls imports are valid.""" self.assertEqual('/app.js', reverse('djangular-module')) ================================================ FILE: djangular/tests/test_utils.py ================================================ import os from djangular import utils from django.test import SimpleTestCase class SiteAndPathUtilsTest(SimpleTestCase): site_utils = utils.SiteAndPathUtils() def test_djangular_root(self): current_dir = os.path.dirname(os.path.abspath(__file__)) djangular_dir = os.path.dirname(current_dir) self.assertEqual(djangular_dir, self.site_utils.get_djangular_root()) ================================================ FILE: djangular/tests/unit/filterSpec.js ================================================ 'use strict'; /* jasmine specs for filters go here */ describe('filter', function() { beforeEach(module('djangular')); describe('django', function() { it('should replace STATIC_URL inside of percent signs', inject(function(djangoFilter) { expect(djangoFilter('before %STATIC_URL% after')). toEqual('before {% get_static_prefix %} after'); })); it('should replace STATIC_URL without percent signs', inject(function(djangoFilter) { expect(djangoFilter('before STATIC_URL after')). toEqual('before {% get_static_prefix %} after'); })); it('should replace MEDIA_URL inside of percent signs', inject(function(djangoFilter) { expect(djangoFilter('before %MEDIA_URL% after')). toEqual('before {% get_media_prefix %} after'); })); it('should replace MEDIA_URL without percent signs', inject(function(djangoFilter) { expect(djangoFilter('before MEDIA_URL after')). toEqual('before {% get_media_prefix %} after'); })); it('should replace USER_NAME inside of percent signs', inject(function(djangoFilter) { expect(djangoFilter('before %USER_NAME% after')). toEqual('before {{ user.username|escapejs }} after'); })); it('should replace USER_NAME without percent signs', inject(function(djangoFilter) { expect(djangoFilter('before USER_NAME after')). toEqual('before {{ user.username|escapejs }} after'); })); it('should replace IS_AUTHENTICATED inside of percent signs', inject(function(djangoFilter) { expect(djangoFilter('before %IS_AUTHENTICATED% after')). toEqual('before false after'); })); it('should replace IS_AUTHENTICATED without percent signs', inject(function(djangoFilter) { expect(djangoFilter('before IS_AUTHENTICATED after')). toEqual('before false after'); })); }); }); ================================================ FILE: djangular/urls.py ================================================ from django.conf.urls import patterns, url from .views import DjangularModuleTemplateView urlpatterns = patterns('', url(r'^app.js$', DjangularModuleTemplateView.as_view(), name='djangular-module') ) ================================================ FILE: djangular/utils.py ================================================ import os CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) class SiteAndPathUtils(object): """ Mixin to get commonly used directories in Djangular Commands """ def get_default_site_app(self): """ Retrieves the name of the django app that contains the site config. """ return os.environ["DJANGO_SETTINGS_MODULE"].replace('.settings', '') def get_default_site_path(self): """ Retrieves the name of the django app that contains the site config. """ settings_module = __import__(self.get_default_site_app()) return settings_module.__path__[0] def get_djangular_root(self): """ Returns the absolute path of the djangular app. """ return CURRENT_DIR def get_project_root(self): """ Retrieves the root of the project directory without having to have a entry in the settings. """ default_site = self.get_default_site_app() path = self.get_default_site_path() # Move up one directory per '.' in site path. Most sites are at the top level, so this is just a precaution. for _ in range(len(default_site.split('.'))): path = os.path.dirname(path) return path ================================================ FILE: djangular/views.py ================================================ from django.views.generic.base import TemplateView class DjangularModuleTemplateView(TemplateView): content_type = 'text/javascript' template_name = 'djangular_module.js' disable_csrf_headers = False def get_context_data(self, **kwargs): context = super(DjangularModuleTemplateView, self).get_context_data(**kwargs) context['disable_csrf_headers'] = self.disable_csrf_headers return context ================================================ FILE: runtests.py ================================================ #!/usr/bin/env python import sys import django from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'djangular', ], MIDDLEWARE_CLASSES=[ 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ], ROOT_URLCONF='djangular.urls' ) import logging logging.basicConfig( level = logging.DEBUG, format = '%(asctime)s %(levelname)s %(message)s', ) logging.disable(logging.CRITICAL) def runtests(): argv = sys.argv[:1] + ['test', 'djangular'] execute_from_command_line(argv) if __name__ == '__main__': runtests() ================================================ FILE: setup.py ================================================ try: from setuptools import setup, find_packages except ImportError: from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='djangular', version='0.3.0b1', description="A reusable app that provides better app integration with AngularJS.", long_description=""" A reusable app that provides better app integration with AngularJS. Djangular allows you to create AngularJS content per app, instead of creating a single massive AngularJS application inside of Django. This allows you to selectively use apps per site, as well as create a consistent structure across all of your Django apps. This is intended to be a Django version of the angular-seed project (https://github.com/angular/angular-seed). The current mindset is to limit the amount of changes introduced by Djangular. """, keywords='djangular django angular angularjs', license='Apache', packages=['djangular'], include_package_data=True, author='Brian Montgomery', author_email='brianm@appliedsec.com', url='http://github.com/appliedsec/djangular', classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2.7", "Operating System :: OS Independent", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Software Development :: Libraries :: Python Modules", ], )