Commits

Andrii Kostenko committed dfa30e3

Separated tests and documentation (documentation examples is not a valid tests now)

  • Participants
  • Parent commits d850538

Comments (0)

Files changed (4)

File doc/Makefile

+# 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) .
+# the i18n builder cannot share the environment and doctrees with the others
+I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.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 <target>' where <target> 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:
+	$(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-oauth-plus.qhcp"
+	@echo "To view the help file:"
+	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-oauth-plus.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-oauth-plus"
+	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-oauth-plus"
+	@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."
+# -*- coding: utf-8 -*-
+#
+# django-oauth-plus documentation build configuration file, created by
+# sphinx-quickstart on Fri Apr 20 13:56:03 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
+
+# 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('.'))
+
+# -- 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.coverage', '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-oauth-plus'
+copyright = u'2012, David Larlet'
+
+# 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 = '2.0'
+# The full version, including alpha/beta/rc tags.
+release = '2.0'
+
+# 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 = ['_build']
+
+# 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
+# "<project> v<release> 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 <link> 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-oauth-plusdoc'
+
+
+# -- 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-oauth-plus.tex', u'django-oauth-plus Documentation',
+   u'David Larlet', '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-oauth-plus', u'django-oauth-plus Documentation',
+     [u'David Larlet'], 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-oauth-plus', u'django-oauth-plus Documentation',
+   u'David Larlet', 'django-oauth-plus', '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'

File doc/index.rst

+=====================
+Django OAuth provider
+=====================
+
+The `OAuth protocol`_ enables websites or applications (Consumers) to access 
+Protected Resources from a web service (Service Provider) via an API, without 
+requiring Users to disclose their Service Provider credentials to the 
+Consumers. More generally, OAuth creates a freely-implementable and generic 
+methodology for API authentication.
+
+.. _`OAuth protocol`: http://oauth.net/core/1.0a
+
+
+Authenticating with OAuth
+=========================
+
+OAuth authentication is the process in which Users grant access to their 
+Protected Resources without sharing their credentials with the Consumer. 
+OAuth uses Tokens generated by the Service Provider instead of the User's 
+credentials in Protected Resources requests. The process uses two Token types:
+
+    * **Request Token:**
+      Used by the Consumer to ask the User to authorize access to the 
+      Protected Resources. The User-authorized Request Token is exchanged for 
+      an Access Token, MUST only be used once, and MUST NOT be used for any 
+      other purpose. It is RECOMMENDED that Request Tokens have a limited 
+      lifetime.
+    * **Access Token:**
+      Used by the Consumer to access the Protected Resources on behalf of the 
+      User. Access Tokens MAY limit access to certain Protected Resources, and 
+      MAY have a limited lifetime. Service Providers SHOULD allow Users to 
+      revoke Access Tokens. Only the Access Token SHALL be used to access the 
+      Protect Resources.
+
+OAuth Authentication is done in three steps:
+
+    * The Consumer obtains an unauthorized Request Token.
+    * The User authorizes the Request Token.
+    * The Consumer exchanges the Request Token for an Access Token.
+
+See the `OAuth Authentication Flow`_ if you need visual details.
+
+.. _`OAuth Authentication Flow`: http://oauth.net/core/diagram.png
+
+
+Django installation
+===================
+
+First, install dependencies through pip::
+
+    pip install -r requirements.txt
+
+You need to specify the OAuth provider application in your settings and to 
+sync your database thanks to the ``syncdb`` command. Then add it to your 
+URLs::
+
+    # urls.py
+    urlpatterns = patterns('',
+        url(r'^oauth/', include('oauth_provider.urls'))
+    )
+
+.. note::
+    The ``oauth`` prefix is not required, you can specify whatever you want.
+
+As a provider, you probably need to customize the view you display to the user
+in order to allow access. The ``OAUTH_AUTHORIZE_VIEW`` setting allow you to
+specify this view, for instance::
+
+    # settings.py
+    OAUTH_AUTHORIZE_VIEW = 'myapp.views.oauth_authorize'
+
+.. note::
+    See example below with a custom callback view (optional), which depends on
+    ``OAUTH_CALLBACK_VIEW`` setting.
+
+.. note::
+    This implementation set an ``oauth`` flag in session which certify that 
+    the validation had been done by the current user. Otherwise, the external 
+    service can directly POST the validation argument and validate the token 
+    without any action from the user if he is already logged in. Do not delete
+    it in your own view.
+
+There is another setting dedicated to OAuth ``OAUTH_REALM_KEY_NAME``, which
+allows you to specify a realm which will be used in headers::
+
+    # settings.py
+    OAUTH_REALM_KEY_NAME = 'http://photos.example.net'
+    
+    # response
+    WWW-Authenticate: OAuth realm="http://photos.example.net/"
+
+With this setup, your OAuth URLs will be:
+
+    * Request Token URL: /oauth/request_token/
+    * User Authorization URL: /oauth/authorize/, using HTTP GET.
+    * Access Token URL: /oauth/access_token/
+
+That is the only thing you need to document for external developers.
+
+.. note::
+    You can customize the length of your key/secret attributes with 
+    constants ``KEY_SIZE``, ``SECRET_SIZE`` and ``CONSUMER_KEY_SIZE`` defined 
+    in consts.py. Default is set to 16 characters for ``KEY_SIZE`` and 
+    ``SECRET_SIZE`` and 256 characters for ``CONSUMER_KEY_SIZE``.
+
+The ``OAUTH_BLACKLISTED_HOSTNAMES`` setting allows you to restrict callback
+URL hostnames, it must be a list of blacklisted ones. For example::
+
+    OAUTH_BLACKLISTED_HOSTNAMES = ['localhost', '127.0.0.1']
+
+Default is an empty list.
+
+The ``OAUTH_SIGNATURE_METHODS`` setting allows you to restrict signatures'
+methods you'd like to use. For example if you don't want plaintext signature::
+
+    OAUTH_SIGNATURE_METHODS = ['hmac-sha1',]
+
+Default is ``['plaintext', 'hmac-sha1']``.
+
+A complete example is available in ``oauth_examples/provider/`` folder, you
+can run tests from this example with this command::
+
+    $ python manage.py test oauth_provider
+    ...
+    Ran 1 test in 0.264s
+    
+    OK
+    ...
+
+
+Protocol Example 1.0a
+=====================
+
+.. warning::
+    THIS IS THE RECOMMENDED WAY TO USE THIS APPLICATION.
+
+This example is exactly the same as 1.0 except it uses newly introduced
+arguments to be 1.0a compatible and fix the security issue.
+
+An account for Jane is necessary::
+
+    >>> from django.contrib.auth.models import User
+    >>> jane = User.objects.create_user('jane', 'jane@example.com', 'toto')
+
+
+Documentation and Registration
+------------------------------
+
+The Service Provider documentation explains how to register for a Consumer Key 
+and Consumer Secret, and declares the following URLs:
+
+    * Request Token URL:
+      http://photos.example.net/request_token, using HTTP POST
+    * User Authorization URL:
+      http://photos.example.net/authorize, using HTTP GET
+    * Access Token URL:
+      http://photos.example.net/access_token, using HTTP POST
+    * Photo (Protected Resource) URL:
+      http://photos.example.net/photo with required parameter file and 
+      optional parameter size
+
+The Service Provider declares support for the HMAC-SHA1 signature method for 
+all requests, and PLAINTEXT only for secure (HTTPS) requests.
+
+The Consumer printer.example.com already established a Consumer Key and 
+Consumer Secret with photos.example.net and advertizes its printing services 
+for photos stored on photos.example.net. The Consumer registration is:
+
+    * Consumer Key: dpf43f3p2l4k3l03
+    * Consumer Secret: kd94hf93k423kf44
+
+We need to create the Protected Resource and the Consumer first::
+
+    >>> from oauth_provider.models import Resource, Consumer
+    >>> resource = Resource(name='photos', url='/oauth/photo/')
+    >>> resource.save()
+    >>> CONSUMER_KEY = 'dpf43f3p2l4k3l03'
+    >>> CONSUMER_SECRET = 'kd94hf93k423kf44'
+    >>> consumer = Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET, 
+    ...                     name='printer.example.com', user=jane)
+    >>> consumer.save()
+
+
+Obtaining a Request Token
+-------------------------
+
+After Jane informs printer.example.com that she would like to print her 
+vacation photo stored at photos.example.net, the printer website tries to 
+access the photo and receives HTTP 401 Unauthorized indicating it is private. 
+The Service Provider includes the following header with the response::
+
+    >>> from django.test.client import Client
+    >>> c = Client()
+    >>> response = c.get("/oauth/request_token/")
+    >>> response.status_code
+    401
+    >>> # depends on REALM_KEY_NAME Django setting
+    >>> response._headers['www-authenticate']
+    ('WWW-Authenticate', 'OAuth realm=""')
+    >>> response.content
+    'Invalid request parameters.'
+
+The Consumer sends the following HTTP POST request to the Service Provider::
+
+    >>> import time
+    >>> parameters = {
+    ...     'oauth_consumer_key': CONSUMER_KEY,
+    ...     'oauth_signature_method': 'PLAINTEXT',
+    ...     'oauth_signature': '%s&' % CONSUMER_SECRET,
+    ...     'oauth_timestamp': str(int(time.time())),
+    ...     'oauth_nonce': 'requestnonce',
+    ...     'oauth_version': '1.0',
+    ...     'oauth_callback': 'http://printer.example.com/request_token_ready',
+    ...     'scope': 'photos', # custom argument to specify Protected Resource
+    ... }
+    >>> response = c.get("/oauth/request_token/", parameters)
+
+The Service Provider checks the signature and replies with an unauthorized 
+Request Token in the body of the HTTP response::
+
+    >>> response.status_code
+    200
+    >>> response.content
+    'oauth_token_secret=...&oauth_token=...&oauth_callback_confirmed=true'
+    >>> from oauth_provider.models import Token
+    >>> token = list(Token.objects.all())[-1]
+    >>> token.key in response.content, token.secret in response.content
+    (True, True)
+    >>> token.callback, token.callback_confirmed
+    (u'http://printer.example.com/request_token_ready', True)
+
+If you try to access a resource with a wrong scope, it will return an error::
+
+    >>> parameters['scope'] = 'videos'
+    >>> parameters['oauth_nonce'] = 'requestnoncevideos'
+    >>> response = c.get("/oauth/request_token/", parameters)
+    >>> response.status_code
+    401
+    >>> response.content
+    'Resource videos does not exist.'
+    >>> parameters['scope'] = 'photos' # restore
+
+If you try to put a wrong callback, it will return an error::
+
+    >>> parameters['oauth_callback'] = 'wrongcallback'
+    >>> parameters['oauth_nonce'] = 'requestnoncewrongcallback'
+    >>> response = c.get("/oauth/request_token/", parameters)
+    >>> response.status_code
+    401
+    >>> response.content
+    'Invalid callback URL.'
+
+If you do not provide any callback (i.e. oob), the Service Provider SHOULD 
+display the value of the verification code::
+
+    >>> parameters['oauth_callback'] = 'oob'
+    >>> parameters['oauth_nonce'] = 'requestnonceoob'
+    >>> response = c.get("/oauth/request_token/", parameters)
+    >>> response.status_code
+    200
+    >>> response.content
+    'oauth_token_secret=...&oauth_token=...&oauth_callback_confirmed=true'
+    >>> oobtoken = list(Token.objects.all())[-1]
+    >>> oobtoken.key in response.content, oobtoken.secret in response.content
+    (True, True)
+    >>> oobtoken.callback, oobtoken.callback_confirmed
+    (None, False)
+
+
+Requesting User Authorization
+-----------------------------
+
+The Consumer redirects Jane's browser to the Service Provider User 
+Authorization URL to obtain Jane's approval for accessing her private photos.
+
+The Service Provider asks Jane to sign-in using her username and password::
+
+    >>> parameters = {
+    ...     'oauth_token': token.key,
+    ... }
+    >>> response = c.get("/oauth/authorize/", parameters)
+    >>> response.status_code
+    302
+    >>> response['Location']
+    'http://.../accounts/login/?next=/oauth/authorize/%3Foauth_token%3D...'
+    >>> token.key in response['Location']
+    True
+
+If successful, asks her if she approves granting printer.example.com access to 
+her private photos. If Jane approves the request, the Service Provider 
+redirects her back to the Consumer's callback URL::
+
+    >>> c.login(username='jane', password='toto')
+    True
+    >>> token.is_approved
+    0
+    >>> response = c.get("/oauth/authorize/", parameters)
+    >>> response.status_code
+    200
+    >>> response.content
+    'Fake authorize view for printer.example.com with params: oauth_token=...'
+    
+    >>> # fake authorization by the user
+    >>> parameters['authorize_access'] = 1
+    >>> response = c.post("/oauth/authorize/", parameters)
+    >>> response.status_code
+    302
+    >>> response['Location']
+    'http://printer.example.com/request_token_ready?oauth_verifier=...&oauth_token=...'
+    >>> token = Token.objects.get(key=token.key)
+    >>> token.key in response['Location']
+    True
+    >>> token.is_approved
+    1
+
+    >>> # without session parameter (previous POST removed it)
+    >>> response = c.post("/oauth/authorize/", parameters)
+    >>> response.status_code
+    401
+    >>> response.content
+    'Action not allowed.'
+    
+    >>> # fake access not granted by the user (set session parameter again)
+    >>> response = c.get("/oauth/authorize/", parameters)
+    >>> parameters['authorize_access'] = 0
+    >>> response = c.post("/oauth/authorize/", parameters)
+    >>> response.status_code
+    302
+    >>> response['Location']
+    'http://printer.example.com/request_token_ready?oauth_verifier=...&error=Access+not+granted+by+user.'
+    >>> c.logout()
+
+With OAuth 1.0a, the callback argument can be set to "oob" (out-of-band), 
+you can specify your own default callback view with the
+``OAUTH_CALLBACK_VIEW`` setting::
+
+    >>> from oauth_provider.consts import OUT_OF_BAND
+    >>> token.callback = OUT_OF_BAND
+    >>> token.save()
+    >>> parameters = {
+    ...     'oauth_token': token.key,
+    ... }
+    >>> c.login(username='jane', password='toto')
+    True
+    >>> response = c.get("/oauth/authorize/", parameters)
+    >>> parameters['authorize_access'] = 0
+    >>> response = c.post("/oauth/authorize/", parameters)
+    >>> response.status_code
+    200
+    >>> response.content
+    'Fake callback view.'
+    >>> c.logout()
+
+
+Obtaining an Access Token
+-------------------------
+
+Now that the Consumer knows Jane approved the Request Token, it asks the 
+Service Provider to exchange it for an Access Token::
+
+    >>> c = Client()
+    >>> parameters = {
+    ...     'oauth_consumer_key': CONSUMER_KEY,
+    ...     'oauth_token': token.key,
+    ...     'oauth_signature_method': 'PLAINTEXT',
+    ...     'oauth_signature': '%s&%s' % (CONSUMER_SECRET, token.secret),
+    ...     'oauth_timestamp': str(int(time.time())),
+    ...     'oauth_nonce': 'accessnonce',
+    ...     'oauth_version': '1.0',
+    ...     'oauth_verifier': token.verifier,
+    ...     'scope': 'photos',
+    ... }
+    >>> response = c.get("/oauth/access_token/", parameters)
+
+.. note::
+    You can use HTTP Authorization header, if you provide both, header will be
+    checked before parameters. It depends on your needs.
+
+The Service Provider checks the signature and replies with an Access Token in 
+the body of the HTTP response::
+
+    >>> response.status_code
+    200
+    >>> response.content
+    'oauth_token_secret=...&oauth_token=...'
+    >>> access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1]
+    >>> access_token.key in response.content
+    True
+    >>> access_token.secret in response.content
+    True
+    >>> access_token.user.username
+    u'jane'
+
+The Consumer will not be able to request another Access Token with the same
+parameters because the Request Token has been deleted once Access Token is
+created::
+
+    >>> response = c.get("/oauth/access_token/", parameters)
+    >>> response.status_code
+    400
+    >>> response.content
+    'Invalid request token.'
+
+The Consumer will not be able to request another Access Token with a missing
+or invalid verifier::
+
+    >>> new_request_token = Token.objects.create_token(
+    ...     token_type=Token.REQUEST,
+    ...     timestamp=str(int(time.time())),
+    ...     consumer=Consumer.objects.get(key=CONSUMER_KEY),
+    ...     user=jane,
+    ...     resource=Resource.objects.get(name='photos'))
+    >>> new_request_token.is_approved = True
+    >>> new_request_token.save()
+    >>> parameters['oauth_token'] = new_request_token.key
+    >>> parameters['oauth_signature'] = '%s&%s' % (CONSUMER_SECRET, new_request_token.secret)
+    >>> parameters['oauth_verifier'] = 'invalidverifier'
+    >>> response = c.get("/oauth/access_token/", parameters)
+    >>> response.status_code
+    400
+    >>> response.content
+    'Invalid OAuth verifier.'
+    >>> parameters['oauth_verifier'] = new_request_token.verifier # restore
+
+The Consumer will not be able to request an Access Token if the token is not
+approved::
+
+    >>> new_request_token.is_approved = False
+    >>> new_request_token.save()
+    >>> parameters['oauth_nonce'] = 'anotheraccessnonce'
+    >>> response = c.get("/oauth/access_token/", parameters)
+    >>> response.status_code
+    400
+    >>> response.content
+    'Request Token not approved by the user.'
+
+
+Accessing Protected Resources
+-----------------------------
+
+The Consumer is now ready to request the private photo. Since the photo URL is 
+not secure (HTTP), it must use HMAC-SHA1.
+
+Generating Signature Base String
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+To generate the signature, it first needs to generate the Signature Base 
+String. The request contains the following parameters (oauth_signature 
+excluded) which are ordered and concatenated into a normalized string::
+
+    >>> parameters = {
+    ...     'oauth_consumer_key': CONSUMER_KEY,
+    ...     'oauth_token': access_token.key,
+    ...     'oauth_signature_method': 'HMAC-SHA1',
+    ...     'oauth_timestamp': str(int(time.time())),
+    ...     'oauth_nonce': 'accessresourcenonce',
+    ...     'oauth_version': '1.0',
+    ... }
+
+
+Calculating Signature Value
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+HMAC-SHA1 produces the following digest value as a base64-encoded string 
+(using the Signature Base String as text and kd94hf93k423kf44&pfkkdhi9sl3r4s00 
+as key)::
+
+    >>> import oauth2 as oauth
+    >>> oauth_request = oauth.Request.from_token_and_callback(access_token,
+    ...     http_url='http://testserver/oauth/photo/', parameters=parameters)
+    >>> signature_method = oauth.SignatureMethod_HMAC_SHA1()
+    >>> signature = signature_method.sign(oauth_request, consumer, access_token)
+
+
+Requesting Protected Resource
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+All together, the Consumer request for the photo is::
+
+    >>> parameters['oauth_signature'] = signature
+    >>> response = c.get("/oauth/photo/", parameters)
+    >>> response.status_code
+    200
+    >>> response.content
+    'Protected Resource access!'
+
+Otherwise, an explicit error will be raised::
+
+    >>> parameters['oauth_signature'] = 'wrongsignature'
+    >>> parameters['oauth_nonce'] = 'anotheraccessresourcenonce'
+    >>> response = c.get("/oauth/photo/", parameters)
+    >>> response.status_code
+    401
+    >>> response.content
+    'Invalid signature. Expected signature base string: GET&http%3A%2F%2F...%2Foauth%2Fphoto%2F&oauth_...'
+
+    >>> response = c.get("/oauth/photo/")
+    >>> response.status_code
+    401
+    >>> response.content
+    'Invalid request parameters.'
+
+
+Revoking Access
+---------------
+
+If Jane deletes the Access Token of printer.example.com, the Consumer will not 
+be able to access the Protected Resource anymore::
+
+    >>> access_token.delete()
+    >>> # Note that an "Invalid signature" error will be raised here if the
+    >>> # token is not revoked by Jane because we reuse a previously used one.
+    >>> parameters['oauth_signature'] = signature
+    >>> parameters['oauth_nonce'] = 'yetanotheraccessresourcenonce'
+    >>> response = c.get("/oauth/photo/", parameters)
+    >>> response.status_code
+    401
+    >>> response.content
+    'Invalid access token: ...'
+
+

File oauth_provider/tests.py

-"""
-=====================
-Django OAuth provider
-=====================
-
-The `OAuth protocol`_ enables websites or applications (Consumers) to access 
-Protected Resources from a web service (Service Provider) via an API, without 
-requiring Users to disclose their Service Provider credentials to the 
-Consumers. More generally, OAuth creates a freely-implementable and generic 
-methodology for API authentication.
-
-.. _`OAuth protocol`: http://oauth.net/core/1.0a
-
-
-Authenticating with OAuth
-=========================
-
-OAuth authentication is the process in which Users grant access to their 
-Protected Resources without sharing their credentials with the Consumer. 
-OAuth uses Tokens generated by the Service Provider instead of the User's 
-credentials in Protected Resources requests. The process uses two Token types:
-
-    * **Request Token:**
-      Used by the Consumer to ask the User to authorize access to the 
-      Protected Resources. The User-authorized Request Token is exchanged for 
-      an Access Token, MUST only be used once, and MUST NOT be used for any 
-      other purpose. It is RECOMMENDED that Request Tokens have a limited 
-      lifetime.
-    * **Access Token:**
-      Used by the Consumer to access the Protected Resources on behalf of the 
-      User. Access Tokens MAY limit access to certain Protected Resources, and 
-      MAY have a limited lifetime. Service Providers SHOULD allow Users to 
-      revoke Access Tokens. Only the Access Token SHALL be used to access the 
-      Protect Resources.
-
-OAuth Authentication is done in three steps:
-
-    * The Consumer obtains an unauthorized Request Token.
-    * The User authorizes the Request Token.
-    * The Consumer exchanges the Request Token for an Access Token.
-
-See the `OAuth Authentication Flow`_ if you need visual details.
-
-.. _`OAuth Authentication Flow`: http://oauth.net/core/diagram.png
-
-
-Django installation
-===================
-
-First, install dependencies through pip::
-
-    pip install -r requirements.txt
-
-You need to specify the OAuth provider application in your settings and to 
-sync your database thanks to the ``syncdb`` command. Then add it to your 
-URLs::
-
-    # urls.py
-    urlpatterns = patterns('',
-        url(r'^oauth/', include('oauth_provider.urls'))
-    )
-
-.. note::
-    The ``oauth`` prefix is not required, you can specify whatever you want.
-
-As a provider, you probably need to customize the view you display to the user
-in order to allow access. The ``OAUTH_AUTHORIZE_VIEW`` setting allow you to
-specify this view, for instance::
-
-    # settings.py
-    OAUTH_AUTHORIZE_VIEW = 'myapp.views.oauth_authorize'
-
-.. note::
-    See example below with a custom callback view (optional), which depends on
-    ``OAUTH_CALLBACK_VIEW`` setting.
-
-.. note::
-    This implementation set an ``oauth`` flag in session which certify that 
-    the validation had been done by the current user. Otherwise, the external 
-    service can directly POST the validation argument and validate the token 
-    without any action from the user if he is already logged in. Do not delete
-    it in your own view.
-
-There is another setting dedicated to OAuth ``OAUTH_REALM_KEY_NAME``, which
-allows you to specify a realm which will be used in headers::
-
-    # settings.py
-    OAUTH_REALM_KEY_NAME = 'http://photos.example.net'
-    
-    # response
-    WWW-Authenticate: OAuth realm="http://photos.example.net/"
-
-With this setup, your OAuth URLs will be:
-
-    * Request Token URL: /oauth/request_token/
-    * User Authorization URL: /oauth/authorize/, using HTTP GET.
-    * Access Token URL: /oauth/access_token/
-
-That is the only thing you need to document for external developers.
-
-.. note::
-    You can customize the length of your key/secret attributes with 
-    constants ``KEY_SIZE``, ``SECRET_SIZE`` and ``CONSUMER_KEY_SIZE`` defined 
-    in consts.py. Default is set to 16 characters for ``KEY_SIZE`` and 
-    ``SECRET_SIZE`` and 256 characters for ``CONSUMER_KEY_SIZE``.
-
-The ``OAUTH_BLACKLISTED_HOSTNAMES`` setting allows you to restrict callback
-URL hostnames, it must be a list of blacklisted ones. For example::
-
-    OAUTH_BLACKLISTED_HOSTNAMES = ['localhost', '127.0.0.1']
-
-Default is an empty list.
-
-The ``OAUTH_SIGNATURE_METHODS`` setting allows you to restrict signatures'
-methods you'd like to use. For example if you don't want plaintext signature::
-
-    OAUTH_SIGNATURE_METHODS = ['hmac-sha1',]
-
-Default is ``['plaintext', 'hmac-sha1']``.
-
-A complete example is available in ``oauth_examples/provider/`` folder, you
-can run tests from this example with this command::
-
-    $ python manage.py test oauth_provider
-    ...
-    Ran 1 test in 0.264s
-    
-    OK
-    ...
-
-
-Protocol Example 1.0a
-=====================
-
-.. warning::
-    THIS IS THE RECOMMENDED WAY TO USE THIS APPLICATION.
-
-This example is exactly the same as 1.0 except it uses newly introduced
-arguments to be 1.0a compatible and fix the security issue.
-
-An account for Jane is necessary::
-
-    >>> from django.contrib.auth.models import User
-    >>> jane = User.objects.create_user('jane', 'jane@example.com', 'toto')
-
-
-Documentation and Registration
-------------------------------
-
-The Service Provider documentation explains how to register for a Consumer Key 
-and Consumer Secret, and declares the following URLs:
-
-    * Request Token URL:
-      http://photos.example.net/request_token, using HTTP POST
-    * User Authorization URL:
-      http://photos.example.net/authorize, using HTTP GET
-    * Access Token URL:
-      http://photos.example.net/access_token, using HTTP POST
-    * Photo (Protected Resource) URL:
-      http://photos.example.net/photo with required parameter file and 
-      optional parameter size
-
-The Service Provider declares support for the HMAC-SHA1 signature method for 
-all requests, and PLAINTEXT only for secure (HTTPS) requests.
-
-The Consumer printer.example.com already established a Consumer Key and 
-Consumer Secret with photos.example.net and advertizes its printing services 
-for photos stored on photos.example.net. The Consumer registration is:
-
-    * Consumer Key: dpf43f3p2l4k3l03
-    * Consumer Secret: kd94hf93k423kf44
-
-We need to create the Protected Resource and the Consumer first::
-
-    >>> from oauth_provider.models import Resource, Consumer
-    >>> resource = Resource(name='photos', url='/oauth/photo/')
-    >>> resource.save()
-    >>> CONSUMER_KEY = 'dpf43f3p2l4k3l03'
-    >>> CONSUMER_SECRET = 'kd94hf93k423kf44'
-    >>> consumer = Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET, 
-    ...                     name='printer.example.com', user=jane)
-    >>> consumer.save()
-
-
-Obtaining a Request Token
--------------------------
-
-After Jane informs printer.example.com that she would like to print her 
-vacation photo stored at photos.example.net, the printer website tries to 
-access the photo and receives HTTP 401 Unauthorized indicating it is private. 
-The Service Provider includes the following header with the response::
-
-    >>> from django.test.client import Client
-    >>> c = Client()
-    >>> response = c.get("/oauth/request_token/")
-    >>> response.status_code
-    401
-    >>> # depends on REALM_KEY_NAME Django setting
-    >>> response._headers['www-authenticate']
-    ('WWW-Authenticate', 'OAuth realm=""')
-    >>> response.content
-    'Invalid request parameters.'
-
-The Consumer sends the following HTTP POST request to the Service Provider::
-
-    >>> import time
-    >>> parameters = {
-    ...     'oauth_consumer_key': CONSUMER_KEY,
-    ...     'oauth_signature_method': 'PLAINTEXT',
-    ...     'oauth_signature': '%s&' % CONSUMER_SECRET,
-    ...     'oauth_timestamp': str(int(time.time())),
-    ...     'oauth_nonce': 'requestnonce',
-    ...     'oauth_version': '1.0',
-    ...     'oauth_callback': 'http://printer.example.com/request_token_ready',
-    ...     'scope': 'photos', # custom argument to specify Protected Resource
-    ... }
-    >>> response = c.get("/oauth/request_token/", parameters)
-
-The Service Provider checks the signature and replies with an unauthorized 
-Request Token in the body of the HTTP response::
-
-    >>> response.status_code
-    200
-    >>> response.content
-    'oauth_token_secret=...&oauth_token=...&oauth_callback_confirmed=true'
-    >>> from oauth_provider.models import Token
-    >>> token = list(Token.objects.all())[-1]
-    >>> token.key in response.content, token.secret in response.content
-    (True, True)
-    >>> token.callback, token.callback_confirmed
-    (u'http://printer.example.com/request_token_ready', True)
-
-If you try to access a resource with a wrong scope, it will return an error::
-
-    >>> parameters['scope'] = 'videos'
-    >>> parameters['oauth_nonce'] = 'requestnoncevideos'
-    >>> response = c.get("/oauth/request_token/", parameters)
-    >>> response.status_code
-    401
-    >>> response.content
-    'Resource videos does not exist.'
-    >>> parameters['scope'] = 'photos' # restore
-
-If you try to put a wrong callback, it will return an error::
-
-    >>> parameters['oauth_callback'] = 'wrongcallback'
-    >>> parameters['oauth_nonce'] = 'requestnoncewrongcallback'
-    >>> response = c.get("/oauth/request_token/", parameters)
-    >>> response.status_code
-    401
-    >>> response.content
-    'Invalid callback URL.'
-
-If you do not provide any callback (i.e. oob), the Service Provider SHOULD 
-display the value of the verification code::
-
-    >>> parameters['oauth_callback'] = 'oob'
-    >>> parameters['oauth_nonce'] = 'requestnonceoob'
-    >>> response = c.get("/oauth/request_token/", parameters)
-    >>> response.status_code
-    200
-    >>> response.content
-    'oauth_token_secret=...&oauth_token=...&oauth_callback_confirmed=true'
-    >>> oobtoken = list(Token.objects.all())[-1]
-    >>> oobtoken.key in response.content, oobtoken.secret in response.content
-    (True, True)
-    >>> oobtoken.callback, oobtoken.callback_confirmed
-    (None, False)
-
-
-Requesting User Authorization
------------------------------
-
-The Consumer redirects Jane's browser to the Service Provider User 
-Authorization URL to obtain Jane's approval for accessing her private photos.
-
-The Service Provider asks Jane to sign-in using her username and password::
-
-    >>> parameters = {
-    ...     'oauth_token': token.key,
-    ... }
-    >>> response = c.get("/oauth/authorize/", parameters)
-    >>> response.status_code
-    302
-    >>> response['Location']
-    'http://.../accounts/login/?next=/oauth/authorize/%3Foauth_token%3D...'
-    >>> token.key in response['Location']
-    True
-
-If successful, asks her if she approves granting printer.example.com access to 
-her private photos. If Jane approves the request, the Service Provider 
-redirects her back to the Consumer's callback URL::
-
-    >>> c.login(username='jane', password='toto')
-    True
-    >>> token.is_approved
-    0
-    >>> response = c.get("/oauth/authorize/", parameters)
-    >>> response.status_code
-    200
-    >>> response.content
-    'Fake authorize view for printer.example.com with params: oauth_token=...'
-    
-    >>> # fake authorization by the user
-    >>> parameters['authorize_access'] = 1
-    >>> response = c.post("/oauth/authorize/", parameters)
-    >>> response.status_code
-    302
-    >>> response['Location']
-    'http://printer.example.com/request_token_ready?oauth_verifier=...&oauth_token=...'
-    >>> token = Token.objects.get(key=token.key)
-    >>> token.key in response['Location']
-    True
-    >>> token.is_approved
-    1
-
-    >>> # without session parameter (previous POST removed it)
-    >>> response = c.post("/oauth/authorize/", parameters)
-    >>> response.status_code
-    401
-    >>> response.content
-    'Action not allowed.'
-    
-    >>> # fake access not granted by the user (set session parameter again)
-    >>> response = c.get("/oauth/authorize/", parameters)
-    >>> parameters['authorize_access'] = 0
-    >>> response = c.post("/oauth/authorize/", parameters)
-    >>> response.status_code
-    302
-    >>> response['Location']
-    'http://printer.example.com/request_token_ready?oauth_verifier=...&error=Access+not+granted+by+user.'
-    >>> c.logout()
-
-With OAuth 1.0a, the callback argument can be set to "oob" (out-of-band), 
-you can specify your own default callback view with the
-``OAUTH_CALLBACK_VIEW`` setting::
-
-    >>> from oauth_provider.consts import OUT_OF_BAND
-    >>> token.callback = OUT_OF_BAND
-    >>> token.save()
-    >>> parameters = {
-    ...     'oauth_token': token.key,
-    ... }
-    >>> c.login(username='jane', password='toto')
-    True
-    >>> response = c.get("/oauth/authorize/", parameters)
-    >>> parameters['authorize_access'] = 0
-    >>> response = c.post("/oauth/authorize/", parameters)
-    >>> response.status_code
-    200
-    >>> response.content
-    'Fake callback view.'
-    >>> c.logout()
-
-
-Obtaining an Access Token
--------------------------
-
-Now that the Consumer knows Jane approved the Request Token, it asks the 
-Service Provider to exchange it for an Access Token::
-
-    >>> c = Client()
-    >>> parameters = {
-    ...     'oauth_consumer_key': CONSUMER_KEY,
-    ...     'oauth_token': token.key,
-    ...     'oauth_signature_method': 'PLAINTEXT',
-    ...     'oauth_signature': '%s&%s' % (CONSUMER_SECRET, token.secret),
-    ...     'oauth_timestamp': str(int(time.time())),
-    ...     'oauth_nonce': 'accessnonce',
-    ...     'oauth_version': '1.0',
-    ...     'oauth_verifier': token.verifier,
-    ...     'scope': 'photos',
-    ... }
-    >>> response = c.get("/oauth/access_token/", parameters)
-
-.. note::
-    You can use HTTP Authorization header, if you provide both, header will be
-    checked before parameters. It depends on your needs.
-
-The Service Provider checks the signature and replies with an Access Token in 
-the body of the HTTP response::
-
-    >>> response.status_code
-    200
-    >>> response.content
-    'oauth_token_secret=...&oauth_token=...'
-    >>> access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1]
-    >>> access_token.key in response.content
-    True
-    >>> access_token.secret in response.content
-    True
-    >>> access_token.user.username
-    u'jane'
-
-The Consumer will not be able to request another Access Token with the same
-parameters because the Request Token has been deleted once Access Token is
-created::
-
-    >>> response = c.get("/oauth/access_token/", parameters)
-    >>> response.status_code
-    400
-    >>> response.content
-    'Invalid request token.'
-
-The Consumer will not be able to request another Access Token with a missing
-or invalid verifier::
-
-    >>> new_request_token = Token.objects.create_token(
-    ...     token_type=Token.REQUEST,
-    ...     timestamp=str(int(time.time())),
-    ...     consumer=Consumer.objects.get(key=CONSUMER_KEY),
-    ...     user=jane,
-    ...     resource=Resource.objects.get(name='photos'))
-    >>> new_request_token.is_approved = True
-    >>> new_request_token.save()
-    >>> parameters['oauth_token'] = new_request_token.key
-    >>> parameters['oauth_signature'] = '%s&%s' % (CONSUMER_SECRET, new_request_token.secret)
-    >>> parameters['oauth_verifier'] = 'invalidverifier'
-    >>> response = c.get("/oauth/access_token/", parameters)
-    >>> response.status_code
-    400
-    >>> response.content
-    'Invalid OAuth verifier.'
-    >>> parameters['oauth_verifier'] = new_request_token.verifier # restore
-
-The Consumer will not be able to request an Access Token if the token is not
-approved::
-
-    >>> new_request_token.is_approved = False
-    >>> new_request_token.save()
-    >>> parameters['oauth_nonce'] = 'anotheraccessnonce'
-    >>> response = c.get("/oauth/access_token/", parameters)
-    >>> response.status_code
-    400
-    >>> response.content
-    'Request Token not approved by the user.'
-
-
-Accessing Protected Resources
------------------------------
-
-The Consumer is now ready to request the private photo. Since the photo URL is 
-not secure (HTTP), it must use HMAC-SHA1.
-
-Generating Signature Base String
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-To generate the signature, it first needs to generate the Signature Base 
-String. The request contains the following parameters (oauth_signature 
-excluded) which are ordered and concatenated into a normalized string::
-
-    >>> parameters = {
-    ...     'oauth_consumer_key': CONSUMER_KEY,
-    ...     'oauth_token': access_token.key,
-    ...     'oauth_signature_method': 'HMAC-SHA1',
-    ...     'oauth_timestamp': str(int(time.time())),
-    ...     'oauth_nonce': 'accessresourcenonce',
-    ...     'oauth_version': '1.0',
-    ... }
-
-
-Calculating Signature Value
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-HMAC-SHA1 produces the following digest value as a base64-encoded string 
-(using the Signature Base String as text and kd94hf93k423kf44&pfkkdhi9sl3r4s00 
-as key)::
-
-    >>> import oauth2 as oauth
-    >>> oauth_request = oauth.Request.from_token_and_callback(access_token,
-    ...     http_url='http://testserver/oauth/photo/', parameters=parameters)
-    >>> signature_method = oauth.SignatureMethod_HMAC_SHA1()
-    >>> signature = signature_method.sign(oauth_request, consumer, access_token)
-
-
-Requesting Protected Resource
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-All together, the Consumer request for the photo is::
-
-    >>> parameters['oauth_signature'] = signature
-    >>> response = c.get("/oauth/photo/", parameters)
-    >>> response.status_code
-    200
-    >>> response.content
-    'Protected Resource access!'
-
-Otherwise, an explicit error will be raised::
-
-    >>> parameters['oauth_signature'] = 'wrongsignature'
-    >>> parameters['oauth_nonce'] = 'anotheraccessresourcenonce'
-    >>> response = c.get("/oauth/photo/", parameters)
-    >>> response.status_code
-    401
-    >>> response.content
-    'Invalid signature. Expected signature base string: GET&http%3A%2F%2F...%2Foauth%2Fphoto%2F&oauth_...'
-
-    >>> response = c.get("/oauth/photo/")
-    >>> response.status_code
-    401
-    >>> response.content
-    'Invalid request parameters.'
-
-
-Revoking Access
----------------
-
-If Jane deletes the Access Token of printer.example.com, the Consumer will not 
-be able to access the Protected Resource anymore::
-
-    >>> access_token.delete()
-    >>> # Note that an "Invalid signature" error will be raised here if the
-    >>> # token is not revoked by Jane because we reuse a previously used one.
-    >>> parameters['oauth_signature'] = signature
-    >>> parameters['oauth_nonce'] = 'yetanotheraccessresourcenonce'
-    >>> response = c.get("/oauth/photo/", parameters)
-    >>> response.status_code
-    401
-    >>> response.content
-    'Invalid access token: ...'
-
-"""
-
 import time
 import re
 
 
         response = self.c.get("/oauth/request_token/", self.request_token_parameters)
 
-        # The Service Provider checks the signature and replies with an unauthorized Request Token in the body of the HTTP response:
-        self.assertEqual(
-            response.status_code,
-            200
-            )
-        self.assert_(
-            re.match(r'oauth_token_secret=[^&]+&oauth_token=[^&]+&oauth_callback_confirmed=true',
-                     response.content
-                     ))
-
-        token = self.request_token = list(Token.objects.all())[-1]
-        self.assert_(token.key in response.content)
-        self.assert_(token.secret in response.content)
-        self.assertEqual(token.callback,
-                         self.callback_token)
-        self.assert_(not self.request_token.is_approved)
-        self.assertEqual(
-            token.callback_confirmed,
-            self.callback_confirmed)
-
-    def test_Requesting_user_authorization_fails_when_user_denies_authorization(self):
-        self.test_Request_token_request_succeeds_with_valid_request_token_parameters()
-        self.c.login(username=self.username, password=self.password)
-        parameters = self.authorization_parameters = {'oauth_token': self.request_token.key}
-        response = self.c.get("/oauth/authorize/", parameters)
-        self.assertEqual(
-            response.status_code,
-            200)
-
-        #self.assertEqual(
-        #    response.content,
-        #    'Fake authorize view for printer.example.com with params: oauth_token=...')
-
-        # fake access not granted by the user (set session parameter again)
-        self.authorization_parameters['authorize_access'] = 0
-        response = self.c.post("/oauth/authorize/", self.authorization_parameters)
-        self.assertEqual(
-            response.status_code,
-            302)
-        self.assertEqual('http://printer.example.com/request_token_ready?error=Access+not+granted+by+user.', response['Location'])
-        self.c.logout()
-