From 23a1ee1b37d5fa2714d9050ce8d3ff13093bc53b Mon Sep 17 00:00:00 2001 From: jpic Date: Mon, 26 Nov 2012 12:34:27 +0100 Subject: [PATCH] Documentation, RTFD GOGOGO --- .gitignore | 1 + README.rst | 12 - docs/Makefile | 154 ++++++++++++ docs/make.bat | 190 ++++++++++++++ docs/requirements.txt | 1 + docs/source/conf.py | 252 +++++++++++++++++++ docs/source/debug.rst | 18 ++ docs/source/decorator.rst | 14 ++ docs/source/index.rst | 31 +++ docs/source/logging.rst | 21 ++ docs/source/middleware.rst | 11 + docs/source/registry.rst | 23 ++ docs/source/shortcuts.rst | 5 + docs/source/testing.rst | 7 + docs/source/tutorial.rst | 209 +++++++++++++++ rules_light/class_decorator.py | 21 ++ rules_light/middleware.py | 13 + rules_light/registry.py | 31 ++- rules_light/tests/__init__.py | 1 + rules_light/tests/class_decorator.py | 35 +-- rules_light/tests/class_decorator_classes.py | 31 +++ rules_light/tests/views.py | 39 +++ rules_light/views.py | 16 ++ test_project/auth_rules.py | 4 + test_project/test_project/rules_logging.py | 37 +++ test_project/test_project/settings.py | 35 +-- test_project/test_project/urls.py | 5 +- 27 files changed, 1139 insertions(+), 78 deletions(-) create mode 100644 docs/Makefile create mode 100644 docs/make.bat create mode 100644 docs/requirements.txt create mode 100644 docs/source/conf.py create mode 100644 docs/source/debug.rst create mode 100644 docs/source/decorator.rst create mode 100644 docs/source/index.rst create mode 100644 docs/source/logging.rst create mode 100644 docs/source/middleware.rst create mode 100644 docs/source/registry.rst create mode 100644 docs/source/shortcuts.rst create mode 100644 docs/source/testing.rst create mode 100644 docs/source/tutorial.rst create mode 100644 rules_light/tests/class_decorator_classes.py create mode 100644 rules_light/tests/views.py create mode 100644 test_project/auth_rules.py create mode 100644 test_project/test_project/rules_logging.py diff --git a/.gitignore b/.gitignore index 6e11ccd..53debf6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *pyc *swp +docs/build diff --git a/README.rst b/README.rst index 156e966..3ee505c 100644 --- a/README.rst +++ b/README.rst @@ -7,18 +7,6 @@ models. One of the goal is to enable developpers of external apps to make rules, depend on it, while allowing a project to override rules. -The design is simple: - -- A global rule registry which is a dict with a couple af methods to proxy the - rules: ``run()`` executes a rule and ``require()`` which does the same but - raises ``Denied`` if ``run()`` returns ``False``. As a dict, it makes it easy - to override, cook or monkey patch if you really need it, -- A view class decorator to take shortcuts, -- A ``process_exception`` middleware that can serve for starters or as an - example, -- Two things make it easy to work with: a view that allows to browse the - registry and several logging levels. - That's all folks ! What's the catch ? diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..2c109ed --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,154 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + set DJANGO_SETTINGS_MODULE="test_project.test_project.settings" + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-rules-light.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-rules-light.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/django-rules-light" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-rules-light" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..156f4cc --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,190 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source +set I18NSPHINXOPTS=%SPHINXOPTS% source +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-rules-light.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-rules-light.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +:end diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..d3e4ba5 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1 @@ +django diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000..b0fbbc9 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,252 @@ +# -*- coding: utf-8 -*- +# +# django-rules-light documentation build configuration file, created by +# sphinx-quickstart on Mon Nov 26 00:08:46 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os, os.path + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('../../')) +sys.path.insert(0, os.path.abspath('../../../../lib/python2.7/site-packages/')) +from django.conf import settings +settings.configure() + +autoclass_content = "both" + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'django-rules-light' +copyright = u'2012, James Pic' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.0.1' +# The full version, including alpha/beta/rc tags. +release = '0.0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'django-rules-lightdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'django-rules-light.tex', u'django-rules-light Documentation', + u'James Pic', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'django-rules-light', u'django-rules-light Documentation', + [u'James Pic'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'django-rules-light', u'django-rules-light Documentation', + u'James Pic', 'django-rules-light', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'http://docs.python.org/': None} diff --git a/docs/source/debug.rst b/docs/source/debug.rst new file mode 100644 index 0000000..e8cd12f --- /dev/null +++ b/docs/source/debug.rst @@ -0,0 +1,18 @@ +Debugging +========= + +Two tools are provided to debug issues with your registry: + +- the logger logs everything, +- the url provides a live rule registry browser. + +As usual, resort to ``ipdb``, for example in +``rules_light.RuleRegistry.run()`` place:: + + import ipdb; ipdb.set_trace() + +The registry browser +-------------------- + +.. automodule:: rules_light.views + :members: diff --git a/docs/source/decorator.rst b/docs/source/decorator.rst new file mode 100644 index 0000000..db68a3a --- /dev/null +++ b/docs/source/decorator.rst @@ -0,0 +1,14 @@ +Class decorator +=============== + +API +--- + +.. automodule:: rules_light.class_decorator + :members: + +Examples +-------- + +.. literalinclude:: ../../rules_light/tests/class_decorator_classes.py + :language: python diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 0000000..32dd496 --- /dev/null +++ b/docs/source/index.rst @@ -0,0 +1,31 @@ +.. django-rules-light documentation master file, created by + sphinx-quickstart on Mon Nov 26 00:08:46 2012. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to django-rules-light's documentation! +============================================== + +.. include:: ../../README.rst + +Contents: + +.. toctree:: + :maxdepth: 2 + + tutorial + registry + decorator + middleware + shortcuts + logging + debug + testing + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/docs/source/logging.rst b/docs/source/logging.rst new file mode 100644 index 0000000..65d8bdb --- /dev/null +++ b/docs/source/logging.rst @@ -0,0 +1,21 @@ +Logging +======= + +Everything is logged in the ``rules_light`` logger: + +- rule registered is logged with ``DEBUG`` level, +- rule ``run()`` is logged with ``INFO`` level, +- ``require()`` failure is logged with ``WARN`` level. + +Install +------- + +Example ``settings.LOGGING`` that will display all logged events in the +console, as well as denials in malicious.log. + +See http://docs.djangoproject.com/en/dev/topics/logging for +more details on how to customize your logging configuration. + + +.. literalinclude:: ../../test_project/test_project/rules_logging.py + :language: python diff --git a/docs/source/middleware.rst b/docs/source/middleware.rst new file mode 100644 index 0000000..1ff88f8 --- /dev/null +++ b/docs/source/middleware.rst @@ -0,0 +1,11 @@ +Middleware +========== + +.. automodule:: rules_light.middleware + :members: + +Template +-------- + +.. literalinclude:: ../../rules_light/templates/rules_light/exception.html + :language: django diff --git a/docs/source/registry.rst b/docs/source/registry.rst new file mode 100644 index 0000000..574c4c9 --- /dev/null +++ b/docs/source/registry.rst @@ -0,0 +1,23 @@ +Rule registry +============= + +API +--- + +.. automodule:: rules_light.registry + :members: + +Examples +-------- + +.. literalinclude:: ../../test_project/auth_rules.py + :language: python + +Even django-rules-light's view uses a permission, it is registered in +``rules_light/rules_light_registry.py`` and thus is picked up by +``rules_light.autodiscover()``: + +.. literalinclude:: ../../rules_light/rules_light_registry.py + :language: python + +Of course, you could use any callable instead of the lambda function. diff --git a/docs/source/shortcuts.rst b/docs/source/shortcuts.rst new file mode 100644 index 0000000..e281f0f --- /dev/null +++ b/docs/source/shortcuts.rst @@ -0,0 +1,5 @@ +Shortcuts +========= + +.. automodule:: rules_light.shortcuts + :members: diff --git a/docs/source/testing.rst b/docs/source/testing.rst new file mode 100644 index 0000000..0e0188b --- /dev/null +++ b/docs/source/testing.rst @@ -0,0 +1,7 @@ +Security testing +================ + +It is important to test your security. Here is an example: + +.. literalinclude:: ../../rules_light/tests/views.py + :language: python diff --git a/docs/source/tutorial.rst b/docs/source/tutorial.rst new file mode 100644 index 0000000..6fb9676 --- /dev/null +++ b/docs/source/tutorial.rst @@ -0,0 +1,209 @@ +Tutorial +======== + +Install +------- + +Either install the last release:: + + pip install django-rules-light + +Either install a development version:: + + pip install -e git+https://github.com/jpic/django-rules-light.git#egg=django-rules-light + +That should be enough to work with the registry. + +Middleware +---------- + +To enable the middleware that processes ``rules_light.Denied`` +exception, add to ``setings.MIDDLEWARE_CLASSES``:: + + MIDDLEWARE_CLASSES = ( + # ... + 'rules_light.middleware.Middleware', + ) + +See :doc:`docs on middleware` for more details. + +Autodiscovery +------------- + +To enable autodiscovery of rules in the various apps installed +in your project, add to ``urls.py`` (as early as possible):: + + import rules_light + rules_light.autodiscover() + +See :doc:`docs on registry` for more details. + +Loging +------ + +To enable logging, add a ``rules_light`` logger for example:: + + LOGGING = { + # ... + 'handlers': { + # ... + 'console':{ + 'level':'DEBUG', + 'class':'logging.StreamHandler', + }, + }, + 'loggers': { + 'rules_light': { + 'handlers': ['console'], + 'propagate': True, + 'level': 'DEBUG', + } + } + } + +See :doc:`docs on logging` for more details on logging. + +View +---- + +For templates and static files to be auto discovered by Django, +add to ``settings.INSTALLED_APPS``:: + + INSTALLED_APPS = ( + 'rules_light', + # .... + ) + +Then the view should be usable, install it as such:: + + url(r'^rules/$', RegistryView.as_view(), name='rules_light_registry'), + +Or just:: + + url(r'^rules/', include('rules_light.urls')), + +See :doc:`docs on debugging` for more details on debugging rules. + +Create rules +------------ + +Create a file that will be picked up by +``rules_light.autodiscover()`` like +``your_app/rules_light_registry.py``. + +It can look like this:: + + import rules_light + + # Allow all users to see your_model + rules_light.registry.setdefault('your_app.your_model.read', True) + + def is_admin(user, rulename, *args): + return user.is_staff + + # Allow admins to create and edit models + rules_light.registry.setdefault('your_app.your_model.create', is_admin) + rules_light.registry.setdefault('your_app.your_model.update', is_admin) + rules_light.registry.setdefault('your_app.your_model.delete', is_admin) + +See :doc:`docs on registry` for more details. + +Using rules +----------- + +The rule registry is in charge of using rules, using the ``run()`` method. It +should return True or False. + +Run +``` + +For example with this:: + + def some_condition(user, rulename, *args, **kwargs): + # ... + + rules_light.registry['your_app.your_model.create'] = some_condition + +Doing:: + + rules_light.run(request.user, 'your_app.your_model.create') + +Will call:: + + some_condition(request.user, 'your_app.your_model.create') + +Kwargs are forwarded, for example:: + + rules_light.run(request.user, 'your_app.your_model.create', + with_widget=request.GET['widget']) + +Will call:: + + some_condition(request.user, 'your_app.your_model.create', + with_widget=request.GET['widget']) + +See :doc:`docs on registry` for more details. + +Require +``````` + +The ``require()`` method is useful too, it does the same as ``run()`` except +that it will raise ``rules_light.Denied``. This will block the request process +and will be catched by the middleware if installed. + +See :doc:`docs on registry` for more details. + +Decorator +````````` + +You can decorate a class based view as such:: + + @rules_light.class_decorator + class SomeCreateView(views.CreateView): + model=SomeModel + +This will automatically require ``'some_app.some_model.create'``. + +See :doc:`docs on decorator` for more usages of the decorator. + +Override rules +-------------- + +If your project wants to change the behaviour of ``your_app`` to allows users +to create models and edit the models they have created, you could add after +``rules_light.autodiscover()``:: + + def my_model_or_staff(user, rulename, obj): + return user.is_staff or user == obj.author + + rules_light.registry['your_app.your_model.create'] = True + rules_light.registry['your_app.your_model.update'] = my_model_or_staff + rules_light.registry['your_app.your_model.delete'] = my_model_or_staff + +As you can see, a project can **completely** change the security logic of an +app, which should enpower creative django developers hehe ... + +See :doc:`docs on registry` for more details. + +Take a shortcut +--------------- + +django-rules-light comes with a predefined ``is_staff`` rule which you could +use in ``your_app/rules_light_registry.py``:: + + import rules_light + + # Allow all users to see your_model + rules_light.registry.setdefault('your_app.your_model.read', True) + + # Allow admins to create and edit models + rules_light.registry.setdefault('your_app.your_model.create', rules_light.is_staff) + rules_light.registry.setdefault('your_app.your_model.update', rules_light.is_staff) + rules_light.registry.setdefault('your_app.your_model.delete', rules_light.is_staff) + +See :doc:`docs on shortcuts`. + +Test security +------------- + +See :doc:`security testing docs`. diff --git a/rules_light/class_decorator.py b/rules_light/class_decorator.py index 6154c4c..d087083 100644 --- a/rules_light/class_decorator.py +++ b/rules_light/class_decorator.py @@ -1,3 +1,7 @@ +""" + +""" + from django.views import generic from exceptions import RulesLightException @@ -29,6 +33,23 @@ def new_get_object(self): class class_decorator(object): + """ + Can be used to secure class based views. + + If the view has ``model=YourModel``, it will support: + + - ``CreateView``, it will decorate ``get_form()``, to run + ``rules_light.require('yourapp.yourmodel.create')``, + - ``UpdateView``, it will decorate ``get_object()``, to run + ``rules_light.require('yourapp.yourmodel.update', obj)``, + - ``DeleteView``, it will decorate ``get_object()``, to run + ``rules_light.require('yourapp.yourmodel.delete', obj)``, + - ``DetailView``, it will decorate ``get_object()``, to run + ``rules_light.require('yourapp.yourmodel.read', obj)``, + - others views, if the rule name is specified in the decorator for example + ``@class_decorator('some_rule')``, then it will decorate ``dispatch()``, + - Else it raises an exception. + """ rule = None def __new__(self, *args): diff --git a/rules_light/middleware.py b/rules_light/middleware.py index 84c0731..39a9d8d 100644 --- a/rules_light/middleware.py +++ b/rules_light/middleware.py @@ -1,3 +1,8 @@ +""" +The role of the middleware is to present a user friendly error page when a rule +denied process of the request by raising ``Denied``. +""" + from django import template from django import http from django.conf import settings @@ -6,7 +11,15 @@ class Middleware(object): + """ + Install this middleware by adding `rules_light.middleware.Middleware`` to + ``settings.MIDDLEWARE_CLASSES``. + """ def process_exception(self, request, exception): + """ + Render ``rules_light/exception.html`` when a ``Denied`` exception was + raised. + """ if not isinstance(exception, RulesLightException): return diff --git a/rules_light/registry.py b/rules_light/registry.py index 42af3d5..7e6c4c1 100644 --- a/rules_light/registry.py +++ b/rules_light/registry.py @@ -2,24 +2,43 @@ The rule registry is in charge of keeping and executing security rules. It is the core of this app, everything else is optionnal. + +This module provides a variable, ``registry``, which is just a module-level, +default RuleRegistry instance. + +A rule can be a callback or a variable that will be evaluated as bool. """ import logging from exceptions import Denied, DoesNotExist -__all__ = ('RuleRegistry', 'registry', 'require', 'run') +__all__ = ('RuleRegistry', 'registry', 'require', 'run', 'autodiscover') class RuleRegistry(dict): + """ + Dict subclass to manage rules. + + logger + The standard logging logger instance to use. + """ def __init__(self): self.logger = logging.getLogger('rules_light') def __setitem__(self, key, value): + """ + Adds a debug-level log on registration. + """ super(RuleRegistry, self).__setitem__(key, value) self.logger.debug(u'[rules_light] "%s" registered with: %s' % ( key, value)) def run(self, user, name, *args, **kwargs): + """ + Run a rule, return True if whatever it returns evaluates to True. + + Also logs calls with the info-level. + """ if name not in self: raise DoesNotExist(name) @@ -39,6 +58,11 @@ def run(self, user, name, *args, **kwargs): return False def require(self, user, name, *args, **kwargs): + """ + Run a rule, raise ``rules_light.Denied`` if returned False. + + Log denials with warn-level. + """ result = self.run(user, name, *args, **kwargs) if not result: @@ -47,6 +71,7 @@ def require(self, user, name, *args, **kwargs): raise Denied(text) def as_text(self, user, name, *args, **kwargs): + """ Format a rule to be human readable for logging """ if name not in self: raise DoesNotExist(name) @@ -71,10 +96,12 @@ def as_text(self, user, name, *args, **kwargs): def run(user, name, *args, **kwargs): + """ Proxy ``rules_light.registry.run()``. """ return registry.run(user, name, *args, **kwargs) def require(user, name, *args, **kwargs): + """ Proxy ``rules_light.registry.require()``. """ registry.require(user, name, *args, **kwargs) @@ -109,7 +136,7 @@ def autodiscover(): """ Check all apps in INSTALLED_APPS for stuff related to rules_light. - For each app, autodiscover imports app.rules_light_registry if + For each app, autodiscover imports ``app.rules_light_registry`` if available, resulting in execution of ``rules_light.registry[...] = ...`` statements in that module, filling registry. diff --git a/rules_light/tests/__init__.py b/rules_light/tests/__init__.py index 642ad51..45daafd 100644 --- a/rules_light/tests/__init__.py +++ b/rules_light/tests/__init__.py @@ -1,3 +1,4 @@ from registry import RegistryTestCase from class_decorator import DecoratorTestCase from autodiscover import AutodiscoverTestCase +from views import ViewsTestCase diff --git a/rules_light/tests/class_decorator.py b/rules_light/tests/class_decorator.py index 1418747..a19fb7a 100644 --- a/rules_light/tests/class_decorator.py +++ b/rules_light/tests/class_decorator.py @@ -7,30 +7,7 @@ import rules_light from ..views import RegistryView - -@rules_light.class_decorator -class CreateView(generic.CreateView): - model = User - - -@rules_light.class_decorator -class UpdateView(generic.UpdateView): - model = User - - -@rules_light.class_decorator -class DetailView(generic.DetailView): - model = User - - -@rules_light.class_decorator -class DeleteView(generic.DeleteView): - model = User - - -@rules_light.class_decorator('funny') -class FunnyUpdateView(generic.UpdateView): - model = User +from class_decorator_classes import * class DecoratorTestCase(unittest.TestCase): @@ -97,13 +74,17 @@ def test_funny_view_decorator(self): view(self.request, pk=1) def test_dispatch_decorator(self): - rules_light.registry['rules_light.rule.read'] = False - view = RegistryView.as_view() + rules_light.registry['foo'] = False + + @rules_light.class_decorator('foo') + class MyView(generic.View): + pass + view = MyView.as_view() with self.assertRaises(rules_light.Denied) as cm: view(self.request) - rules_light.registry['rules_light.rule.read'] = True + rules_light.registry['foo'] = True # it should not raise an exception view(self.request) diff --git a/rules_light/tests/class_decorator_classes.py b/rules_light/tests/class_decorator_classes.py new file mode 100644 index 0000000..fa86cd0 --- /dev/null +++ b/rules_light/tests/class_decorator_classes.py @@ -0,0 +1,31 @@ +from django.views import generic +from django.contrib.auth.models import User + +import rules_light + +@rules_light.class_decorator +class CreateView(generic.CreateView): + model = User + + +@rules_light.class_decorator +class UpdateView(generic.UpdateView): + model = User + + +@rules_light.class_decorator +class DetailView(generic.DetailView): + model = User + + +@rules_light.class_decorator +class DeleteView(generic.DeleteView): + model = User + + +@rules_light.class_decorator('funny') +class FunnyUpdateView(generic.UpdateView): + model = User + + + diff --git a/rules_light/tests/views.py b/rules_light/tests/views.py new file mode 100644 index 0000000..e225c6c --- /dev/null +++ b/rules_light/tests/views.py @@ -0,0 +1,39 @@ +import unittest + +from django.test.client import RequestFactory +from django.contrib.auth.models import User, AnonymousUser + +import rules_light +from ..views import RegistryView + + +class ViewsTestCase(unittest.TestCase): + def setUp(self): + """ + Note that URL doesn't matter here because the tests excute the views + directly. + """ + User.objects.all().delete() + + self.anonymous_request = RequestFactory().get('/') + self.anonymous_request.user = AnonymousUser() + + self.user_request = RequestFactory().get('/') + self.user_request.user, c = User.objects.get_or_create( + username='foo', is_staff=False) + + self.admin_request = RequestFactory().get('/') + self.admin_request.user, c = User.objects.get_or_create( + username='bar', is_staff=True) + + def test_registry_view(self): + view = RegistryView.as_view() + + with self.assertRaises(rules_light.Denied) as cm: + view(self.anonymous_request) + + with self.assertRaises(rules_light.Denied) as cm: + view(self.user_request) + + # it should not raise an exception + view(self.admin_request) diff --git a/rules_light/views.py b/rules_light/views.py index e85d337..c162a9d 100644 --- a/rules_light/views.py +++ b/rules_light/views.py @@ -5,7 +5,23 @@ @rules_light.class_decorator('rules_light.rule.read') class RegistryView(generic.TemplateView): + """ + Expose the rule registry for debug purposes. + + Install it as such:: + + url(r'^rules/$', RegistryView.as_view(), name='rules_light_registry'), + + Or just:: + + url(r'^rules/', include('rules_light.urls')), + + Note: view requires ``'rules_light.rule.read'`` which is enabled for admins + by default. + """ + template_name = 'rules_light/registry.html' def get_context_data(self): + """ Add the registry to the context. """ return {'registry': rules_light.registry} diff --git a/test_project/auth_rules.py b/test_project/auth_rules.py new file mode 100644 index 0000000..6437dbb --- /dev/null +++ b/test_project/auth_rules.py @@ -0,0 +1,4 @@ +import rules_light + +rules_light.registry['auth.user.read'] = True +rules_light.registry['auth.user.update'] = lambda user, *args: user.is_staff diff --git a/test_project/test_project/rules_logging.py b/test_project/test_project/rules_logging.py new file mode 100644 index 0000000..4f60629 --- /dev/null +++ b/test_project/test_project/rules_logging.py @@ -0,0 +1,37 @@ +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'filters': { + 'require_debug_false': { + '()': 'django.utils.log.RequireDebugFalse' + } + }, + 'handlers': { + 'mail_admins': { + 'level': 'ERROR', + 'filters': ['require_debug_false'], + 'class': 'django.utils.log.AdminEmailHandler' + }, + 'console':{ + 'level':'DEBUG', + 'class':'logging.StreamHandler', + }, + 'malicious':{ + 'level': 'WARN', + 'class': 'logging.FileHandler', + 'filename': 'malicious.log', + }, + }, + 'loggers': { + 'django.request': { + 'handlers': ['mail_admins'], + 'level': 'ERROR', + 'propagate': True, + }, + 'rules_light': { + 'handlers':['console', 'malicious'], + 'propagate': True, + 'level':'DEBUG', + }, + } +} diff --git a/test_project/test_project/settings.py b/test_project/test_project/settings.py index 2477f4a..aad5397 100644 --- a/test_project/test_project/settings.py +++ b/test_project/test_project/settings.py @@ -141,37 +141,4 @@ # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. -# See http://docs.djangoproject.com/en/dev/topics/logging for -# more details on how to customize your logging configuration. -LOGGING = { - 'version': 1, - 'disable_existing_loggers': False, - 'filters': { - 'require_debug_false': { - '()': 'django.utils.log.RequireDebugFalse' - } - }, - 'handlers': { - 'mail_admins': { - 'level': 'ERROR', - 'filters': ['require_debug_false'], - 'class': 'django.utils.log.AdminEmailHandler' - }, - 'console':{ - 'level':'DEBUG', - 'class':'logging.StreamHandler', - }, - }, - 'loggers': { - 'django.request': { - 'handlers': ['mail_admins'], - 'level': 'ERROR', - 'propagate': True, - }, - 'rules_light': { - 'handlers':['console'], - 'propagate': True, - 'level':'DEBUG', - }, - } -} +from rules_logging import LOGGING diff --git a/test_project/test_project/urls.py b/test_project/test_project/urls.py index 78b14b5..d157716 100644 --- a/test_project/test_project/urls.py +++ b/test_project/test_project/urls.py @@ -5,10 +5,9 @@ import rules_light # not need in this particular project ... oh well it'll serve as example rules_light.autodiscover() +# import our project specific rules +import auth_rules -# because we define project-specific rules here for the sake of the example -rules_light.registry['auth.user.read'] = True -rules_light.registry['auth.user.update'] = lambda user, *args: user.is_staff from django.contrib import admin