Repository: mishbahr/django-users2 Branch: master Commit: 1ee244dc4ca1 Files: 76 Total size: 103.4 KB Directory structure: gitextract_jj2ggm8b/ ├── .coveragerc ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs/ │ ├── Makefile │ ├── authors.rst │ ├── conf.py │ ├── contributing.rst │ ├── history.rst │ ├── index.rst │ ├── installation.rst │ ├── make.bat │ ├── readme.rst │ └── usage.rst ├── example/ │ ├── __init__.py │ ├── migrations/ │ │ ├── 0001_initial.py │ │ └── __init__.py │ └── models.py ├── requirements-test.txt ├── requirements.txt ├── runtests.py ├── setup.cfg ├── setup.py ├── tests/ │ ├── __init__.py │ ├── test_admin.py │ ├── test_fields.py │ ├── test_forms.py │ ├── test_managers.py │ ├── test_models.py │ ├── test_utils.py │ └── test_views.py ├── tox.ini └── users/ ├── __init__.py ├── admin.py ├── compat.py ├── conf.py ├── fields.py ├── forms.py ├── managers.py ├── migrations/ │ ├── 0001_initial.py │ ├── 0002_alter_user_last_login_null.py │ └── __init__.py ├── models.py ├── signals.py ├── templates/ │ ├── base.html │ └── users/ │ ├── activate.html │ ├── activation_complete.html │ ├── activation_email.html │ ├── activation_email_subject.html │ ├── login.html │ ├── logout.html │ ├── partials/ │ │ ├── errors.html │ │ ├── field.html │ │ └── honeypot.html │ ├── password_change_done.html │ ├── password_change_form.html │ ├── password_reset_complete.html │ ├── password_reset_confirm.html │ ├── password_reset_done.html │ ├── password_reset_email.html │ ├── password_reset_form.html │ ├── password_reset_subject.html │ ├── registration_closed.html │ ├── registration_complete.html │ └── registration_form.html ├── templatetags/ │ ├── __init__.py │ └── form_tags.py ├── urls.py ├── utils.py └── views.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .coveragerc ================================================ [run] omit = */migrations/* */compat.py */__init__.py */test_* [report] exclude_lines = def __repr__ def __str__ def parse_args pragma: no cover raise NotImplementedError if __name__ == .__main__.: ================================================ FILE: .gitignore ================================================ *.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Complexity output/*.html output/*/index.html # Sphinx docs/_build #pycharm .idea/ #coverage htmlcov ================================================ FILE: .travis.yml ================================================ # Config file for automatic testing at travis-ci.org language: python python: - "3.5" - "3.4" - "2.7" env: - DJANGO="Django==1.11.2" # command to install dependencies, e.g. pip install -r requirements.txt install: - pip install $DJANGO - pip install -r requirements-test.txt # command to run tests using coverage, e.g. python setup.py test script: coverage run --source users runtests.py # report coverage to coveralls.io after_success: coveralls ================================================ FILE: AUTHORS.rst ================================================ ======= Credits ======= Development Lead ---------------- * Mishbah Razzaque (mishbahr) Contributors ------------ * John Matthew (jfmatth) * moemen * Alwerdani * Weizhong Tu (twz915) * Ahmed Maher (mxahmed) ================================================ FILE: CONTRIBUTING.rst ================================================ ============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/mishbahr/django-users2/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "feature" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ django-users2 could always use more documentation, whether as part of the official django-users2 docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/mishbahr/django-users2/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `django-users2` for local development. 1. Fork the `django-users2` repo on GitHub. 2. Clone your fork locally:: $ git clone git@github.com:your_name_here/django-users2.git 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: $ mkvirtualenv django-users2 $ cd django-users2/ $ python setup.py develop 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 users tests $ python setup.py test $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 7. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check https://travis-ci.org/mishbahr/django-users2/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ python -m unittest tests.test_users ================================================ FILE: HISTORY.rst ================================================ .. :changelog: History ------- 0.1.0 (2014-09-25) ++++++++++++++++++ * First release on PyPI. ================================================ FILE: LICENSE ================================================ Copyright (c) 2014, Mishbah Razzaque All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of django-users2 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: MANIFEST.in ================================================ include AUTHORS.rst include CONTRIBUTING.rst include HISTORY.rst include LICENSE include README.rst recursive-include users *.html *.png *.gif *js *.css *jpg *jpeg *svg *py ================================================ FILE: Makefile ================================================ .PHONY: clean-pyc clean-build docs help: @echo "clean-build - remove build artifacts" @echo "clean-pyc - remove Python file artifacts" @echo "lint - check style with flake8" @echo "test - run tests quickly with the default Python" @echo "testall - run tests on every Python version with tox" @echo "coverage - check code coverage quickly with the default Python" @echo "docs - generate Sphinx HTML documentation, including API docs" @echo "release - package and upload a release" @echo "sdist - package" clean: clean-build clean-pyc clean-build: rm -fr build/ rm -fr dist/ rm -fr *.egg-info clean-pyc: find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + lint: flake8 django-users2 tests test: python runtests.py test test-all: tox coverage: coverage run --source django-users2 setup.py test coverage report -m coverage html open htmlcov/index.html docs: rm -f docs/django-users2.rst rm -f docs/modules.rst sphinx-apidoc -o docs/ django-users2 $(MAKE) -C docs clean $(MAKE) -C docs html open docs/_build/html/index.html release: clean python setup.py sdist upload python setup.py bdist_wheel upload sdist: clean python setup.py sdist ls -l dist ================================================ FILE: README.rst ================================================ ============================= django-users2 ============================= .. image:: http://img.shields.io/travis/mishbahr/django-users2.svg?style=flat-square :target: https://travis-ci.org/mishbahr/django-users2/ .. image:: http://img.shields.io/pypi/v/django-users2.svg?style=flat-square :target: https://pypi.python.org/pypi/django-users2/ :alt: Latest Version .. image:: http://img.shields.io/pypi/dm/django-users2.svg?style=flat-square :target: https://pypi.python.org/pypi/django-users2/ :alt: Downloads .. image:: http://img.shields.io/pypi/l/django-users2.svg?style=flat-square :target: https://pypi.python.org/pypi/django-users2/ :alt: License .. image:: http://img.shields.io/coveralls/mishbahr/django-users2.svg?style=flat-square :target: https://coveralls.io/r/mishbahr/django-users2?branch=master Custom user model for django >=1.5 with support for multiple user types and lots of other awesome utils (mostly borrowed from other projects). If you are using django < 1.11, please install v0.2.1 or earlier (`pip install django-users2<=0.2.1`). Features -------- * email as username for authentication (barebone extendable user models) * support for multiple user types (using the awesome django-model-utils) * automatically creates superuser after syncdb/migrations (really handy during the initial development phases) * built in emails/passwords validators (with lots of customisable options) * prepackaged with all the templates, including additional templates required by views in ``django.contrib.auth`` (for a painless signup process) Documentation ------------- The full documentation is at https://django-users2.readthedocs.org. Quickstart ---------- 1. Install `django-users2`:: pip install django-users2 2. Add `django-users2` to `INSTALLED_APPS`:: INSTALLED_APPS = ( ... 'django.contrib.auth', 'django.contrib.sites', 'users', ... ) 3. Set your `AUTH_USER_MODEL` setting to use ``users.User``:: AUTH_USER_MODEL = 'users.User' 4. Once you’ve done this, run the ``migrate`` command to install the model used by this package:: python manage.py migrate 5. Add the `django-users2` URLs to your project’s URLconf as follows:: urlpatterns = patterns('', ... url(r'^accounts/', include('users.urls')), ... ) which sets up URL patterns for the views in django-users2 as well as several useful views in django.contrib.auth (e.g. login, logout, password change/reset) Configuration ----------------------- Set ``USERS_VERIFY_EMAIL = True`` to enable email verification for registered users. When a new ``User`` object is created, with its ``is_active`` field set to ``False``, an activation key is generated, and an email is sent to the user containing a link to click to activate the account:: USERS_VERIFY_EMAIL = False Upon clicking the activation link, the new account is made active (i.e. ``is_active`` field is set to ``True``); after this, the user can log in. Optionally, you can automatically login the user after successful activation:: USERS_AUTO_LOGIN_ON_ACTIVATION = True This is the number of days the users will have, to activate their accounts after registering:: USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS = 3 Automatically create django ``superuser`` after ``syncdb``, by default this option is enabled when ``settings.DEBUG = True``. You can customise the email/password by overriding ``USERS_SUPERUSER_EMAIL`` and ``USERS_SUPERUSER_PASSWORD`` settings (highly recommended):: USERS_CREATE_SUPERUSER = settings.DEBUG USERS_SUPERUSER_EMAIL = 'superuser@djangoproject.com' USERS_SUPERUSER_PASSWORD = 'django' Prevent automated registration by spambots, by enabling a hidden (using css) honeypot field:: USERS_SPAM_PROTECTION = True Prevent user registrations by setting ``USERS_REGISTRATION_OPEN = False``:: USERS_REGISTRATION_OPEN = True Settings for validators, that check the strength of user specified passwords:: # Specifies minimum length for passwords: USERS_PASSWORD_MIN_LENGTH = 5 #Specifies maximum length for passwords: USERS_PASSWORD_MAX_LENGTH = None Optionally, the complexity validator, checks the password strength:: USERS_CHECK_PASSWORD_COMPLEXITY = True Specify number of characters within various sets that a password must contain:: USERS_PASSWORD_POLICY = { 'UPPER': 0, # Uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'LOWER': 0, # Lowercase 'abcdefghijklmnopqrstuvwxyz' 'DIGITS': 0, # Digits '0123456789' 'PUNCTUATION': 0 # Punctuation """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" } Allow/disallow registration using emails addresses from specific domains:: USERS_VALIDATE_EMAIL_DOMAIN = True List of disallowed domains:: USERS_EMAIL_DOMAINS_BLACKLIST = [] For example, ``USERS_EMAIL_DOMAINS_BLACKLIST = ['mailinator.com']`` will block all visitors from using mailinator.com email addresses to register. List of allowed domains:: USERS_EMAIL_DOMAINS_WHITELIST = [] For example, ``USERS_EMAIL_DOMAINS_WHITELIST = ['ljworld.com']`` will only allow user registration with ljworld.com domains. ================================================ FILE: docs/Makefile ================================================ # Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # 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 ' 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 " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @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 " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @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/complexity.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.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/complexity" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" @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." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @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." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." ================================================ FILE: docs/authors.rst ================================================ .. include:: ../AUTHORS.rst ================================================ FILE: docs/conf.py ================================================ # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # 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('.')) cwd = os.getcwd() parent = os.path.dirname(cwd) sys.path.append(parent) import users # -- 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.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-users2' copyright = u'2014, Mishbah Razzaque' # 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 = users.__version__ # The full version, including alpha/beta/rc tags. release = users.__version__ # 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 = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- 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-users2doc' # -- 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-users2.tex', u'django-users2 Documentation', u'Mishbah Razzaque', '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-users2', u'django-users2 Documentation', [u'Mishbah Razzaque'], 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-users2', u'django-users2 Documentation', u'Mishbah Razzaque', 'django-users2', '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' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False ================================================ FILE: docs/contributing.rst ================================================ .. include:: ../CONTRIBUTING.rst ================================================ FILE: docs/history.rst ================================================ .. include:: ../HISTORY.rst ================================================ FILE: docs/index.rst ================================================ .. complexity documentation master file, created by sphinx-quickstart on Tue Jul 9 22:26:36 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to django-users2's documentation! ================================================================= Contents: .. toctree:: :maxdepth: 2 readme installation usage contributing authors history ================================================ FILE: docs/installation.rst ================================================ ============ Installation ============ At the command line:: $ easy_install django-users2 Or, if you have virtualenvwrapper installed:: $ mkvirtualenv django-users2 $ pip install django-users2 ================================================ FILE: docs/make.bat ================================================ @ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . 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. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes 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 ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) 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\complexity.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.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" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF 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 ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end ================================================ FILE: docs/readme.rst ================================================ .. include:: ../README.rst ================================================ FILE: docs/usage.rst ================================================ ======== Usage ======== To use django-users2 in a project:: import django-users2 ================================================ FILE: example/__init__.py ================================================ __author__ = 'mishbah' ================================================ FILE: example/migrations/0001_initial.py ================================================ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('user_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), ('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)), ('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)), ], options={ 'verbose_name': 'Customer', 'verbose_name_plural': 'Customers', }, bases=('users.user',), ), ] ================================================ FILE: example/migrations/__init__.py ================================================ ================================================ FILE: example/models.py ================================================ from django.db import models from django.utils.translation import ugettext_lazy as _ from users.models import User class Customer(User): first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) class Meta: verbose_name = _('Customer') verbose_name_plural = _('Customers') ================================================ FILE: requirements-test.txt ================================================ -r requirements.txt coverage coveralls mock>=1.0.1 nose>=1.3.0 django-nose>=1.2 flake8>=2.1.0 tox>=1.7.0 ================================================ FILE: requirements.txt ================================================ -e . wheel==0.24.0 # Additional requirements go here ================================================ FILE: runtests.py ================================================ import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_users2', } }, ROOT_URLCONF='users.urls', INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.staticfiles', 'django.contrib.messages', 'users', 'example', # used for testing user model subclasses ], MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ), PASSWORD_HASHERS=( 'django.contrib.auth.hashers.SHA1PasswordHasher', ), SITE_ID=1, NOSE_ARGS=['-s'], AUTH_USER_MODEL='users.User', USERS_CREATE_SUPERUSER=False, TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] ) try: import django setup = django.setup except AttributeError: pass else: setup() from django_nose import NoseTestSuiteRunner except ImportError: import traceback traceback.print_exc() raise ImportError('To fix this error, run: pip install -r requirements-test.txt') def run_tests(*test_args): if not test_args: test_args = ['tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:]) ================================================ FILE: setup.cfg ================================================ [wheel] universal = 1 ================================================ FILE: setup.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os import sys import users try: from setuptools import setup except ImportError: from distutils.core import setup version = users.__version__ if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') print("You probably want to also tag the version now:") print(" git tag -a %s -m 'version %s'" % (version, version)) print(" git push --tags") sys.exit() readme = codecs.open('README.rst', 'r', 'utf-8').read() setup( name='django-users2', version=version, description="""Custom user model for django >=1.11 with support for multiple user types""", long_description=readme, author='Mishbah Razzaque', author_email='mishbahx@gmail.com', url='https://github.com/mishbahr/django-users2', packages=[ 'users', ], include_package_data=True, install_requires=[ 'django>=1.11', 'django-model-utils', 'django-appconf', ], license="BSD", zip_safe=False, keywords='django-users2', classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Framework :: Django :: 1.11', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], ) ================================================ FILE: tests/__init__.py ================================================ ================================================ FILE: tests/test_admin.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib.admin.sites import AdminSite from django.contrib.auth import get_user_model from django.contrib.messages.storage.fallback import FallbackStorage from django.core import mail from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from users.admin import UserAdmin class AdminTest(TestCase): user_email = 'user@example.com' user_password = 'pa$sw0Rd' def setUp(self): get_user_model().objects.create_superuser(self.user_email, self.user_password) self.assertTrue(self.client.login( username=self.user_email, password=self.user_password), 'Failed to login user %s' % self.user_email) get_user_model().objects.create_user('user1@example.com', 'pa$sw0Rd1', is_active=False) factory = RequestFactory() self.request = factory.get('/admin') # Hack to test this function as it calls 'messages.add' # See https://code.djangoproject.com/ticket/17971 setattr(self.request, 'session', 'session') messages = FallbackStorage(self.request) setattr(self.request, '_messages', messages) def test_get_queryset(self): user_admin = UserAdmin(get_user_model(), AdminSite()) self.assertQuerysetEqual( user_admin.get_queryset(self.request), ['', ''], ordered=False) @override_settings(USERS_VERIFY_EMAIL=True) def test_send_activation_email(self): user_admin = UserAdmin(get_user_model(), AdminSite()) qs = get_user_model().objects.all() user_admin.send_activation_email(self.request, qs) # we created 1 inactive user, so there should be one email in outbox self.assertEqual(len(mail.outbox), 1) def test_activate_users(self): user_admin = UserAdmin(get_user_model(), AdminSite()) qs = get_user_model().objects.all() user_admin.activate_users(self.request, qs) # both users should be active self.assertEqual(get_user_model().objects.filter(is_active=True).count(), 2) # superuser is automatically activated. so we test the attribute for user1@example.com user = get_user_model().objects.get(email='user1@example.com') self.assertTrue(user.is_active) def tearDown(self): self.client.logout() ================================================ FILE: tests/test_fields.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.test import TestCase from django.test.utils import override_settings from users.fields import (ComplexityValidator, EmailDomainValidator, LengthValidator) class LengthValidatorTest(TestCase): @override_settings(USERS_PASSWORD_MIN_LENGTH=6, USERS_PASSWORD_MAX_LENGTH=20) def setUp(self): self.length_validator = LengthValidator() def test_password_length_validator_min_length(self): value = 'abc' try: self.length_validator(value) except forms.ValidationError: pass else: self.fail('ValidationError not raised when validating \'%s\'' % value) def test_password_length_validator_max_length(self): value = 'qwertyuiopasdfghjklzxcvbnm' try: self.length_validator(value) except forms.ValidationError: pass else: self.fail('ValidationError not raised when validating \'%s\'' % value) class ComplexityValidatorTest(TestCase): password_policy = { 'UPPER': 1, 'LOWER': 1, 'DIGITS': 1, 'PUNCTUATION': 1 } @override_settings(USERS_PASSWORD_POLICY={'UPPER': 1}) def test_complexity_validator_fails_no_uppercase(self): complexity_validator = ComplexityValidator() value = 'password' try: complexity_validator(value) except forms.ValidationError: pass else: self.fail('ValidationError not raised when validating \'%s\'' % value) @override_settings(USERS_PASSWORD_POLICY={'LOWER': 1}) def test_complexity_validator_fails_no_lowercase(self): complexity_validator = ComplexityValidator() value = 'PASSWORD' try: complexity_validator(value) except forms.ValidationError: pass else: self.fail('ValidationError not raised when validating \'%s\'' % value) @override_settings(USERS_PASSWORD_POLICY={'DIGITS': 1}) def test_complexity_validator_fails_no_digit(self): complexity_validator = ComplexityValidator() value = 'password' try: complexity_validator(value) except forms.ValidationError: pass else: self.fail('ValidationError not raised when validating \'%s\'' % value) @override_settings(USERS_PASSWORD_POLICY={'PUNCTUATION': 1}) def test_complexity_validator_fails_no_symbol(self): complexity_validator = ComplexityValidator() value = 'password' try: complexity_validator(value) except forms.ValidationError: pass else: self.fail('ValidationError not raised when validating \'%s\'' % value) @override_settings(USERS_PASSWORD_POLICY=password_policy) def test_complexity_validator_success(self): complexity_validator = ComplexityValidator() value = 'Pas$word1' try: complexity_validator(value) except forms.ValidationError: self.fail('ValidationError raised when validating \'%s\'' % value) class EmailDomainValidatorTest(TestCase): domains_blacklist = ('mailinator.com', ) domains_whitelist = ('djangoproject.com', ) @override_settings(USERS_EMAIL_DOMAINS_WHITELIST=domains_whitelist) def test_email_domain_validator_with_white_list(self): email_domain_validator = EmailDomainValidator() value = 'user@example.com' try: email_domain_validator(value) except forms.ValidationError: pass else: self.fail('ValidationError not raised when validating \'%s\'' % value) @override_settings(USERS_EMAIL_DOMAINS_BLACKLIST=domains_blacklist) def test_email_domain_validator_with_black_list(self): email_domain_validator = EmailDomainValidator() value = 'spammer@mailinator.com' try: email_domain_validator(value) except forms.ValidationError: pass else: self.fail('ValidationError not raised when validating \'%s\'' % value) ================================================ FILE: tests/test_forms.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib.auth import get_user_model from django.test import TestCase from django.utils.encoding import force_text from django.utils.translation import ugettext as _ from users.forms import (RegistrationFormHoneypot, RegistrationFormTermsOfService, UserChangeForm, UserCreationForm) class UserCreationFormTest(TestCase): def test_user_already_exists(self): get_user_model().objects.create_user('testuser@example.com', 'Pa$sw0rd') data = { 'email': 'testuser@example.com', 'password1': 'Pa$sw0rd', 'password2': 'Pa$sw0rd', } form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form['email'].errors, [force_text(form.error_messages['duplicate_email'])]) def test_invalid_email(self): data = { 'email': 'testuser', 'password1': 'Pa$sw0rd', 'password2': 'Pa$sw0rd', } form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertIn(_('Enter a valid email address.'), form['email'].errors) def test_password_verification(self): # The verification password is incorrect. data = { 'email': 'testuser@example.com', 'password1': 'Pa$sw0rd1', 'password2': 'Pa$sw0rd2', } form = UserCreationForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form['password2'].errors, [force_text(form.error_messages['password_mismatch'])]) def test_password_is_not_saved_raw(self): raw_password = 'Pa$sw0rd2' data = { 'email': 'testuser@example.com', 'password1': raw_password, 'password2': raw_password, } form = UserCreationForm(data) user = form.save() self.assertNotEqual(raw_password, user.password) def test_valid_user_are_saved(self): data = { 'email': 'validuser@example.com', 'password1': 'Pa$sw0rd', 'password2': 'Pa$sw0rd', } form = UserCreationForm(data) self.assertTrue(form.is_valid()) user = form.save() self.assertEqual(repr(user), '<%s: validuser@example.com>' % get_user_model().__name__) class UserChangeFormTest(TestCase): def test_username_validity(self): user = get_user_model().objects.create_user('testuser@example.com', 'Pa$sw0rd') data = { 'email': 'invalid-email' } form = UserChangeForm(data, instance=user) self.assertFalse(form.is_valid()) self.assertIn(_('Enter a valid email address.'), form['email'].errors) def test_unsuable_password(self): user = get_user_model().objects.create_user('testuser@example.com', 'Pa$sw0rd') user.set_unusable_password() user.save() form = UserChangeForm(instance=user) self.assertIn(_('No password set.'), form.as_table()) class RegistrationFormTermsOfServiceTest(TestCase): def test_registration_form_with_tos_checkbox_validates(self): data = { 'email': 'testuser@example.com', 'password1': 'Pa$sw0rd', 'password2': 'Pa$sw0rd', 'tos': True } form = RegistrationFormTermsOfService(data=data) self.assertTrue(form.is_valid()) def test_registration_form_with_tos_checkbox_fails(self): data = { 'email': 'testuser@example.com', 'password1': 'Pa$sw0rd', 'password2': 'Pa$sw0rd', } form = RegistrationFormTermsOfService(data=data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['tos'], [u'You must agree to the terms to register']) class RegistrationFormHoneypotTest(TestCase): def test_registration_form_with_honeypot_field(self): data = { 'email': 'testuser@example.com', 'password1': 'Pa$sw0rd', 'password2': 'Pa$sw0rd', } form = RegistrationFormHoneypot(data=data) self.assertTrue(form.is_valid()) def test_registration_form_with_honeypot_field_fails_as_expected(self): data = { 'email': 'testuser@example.com', 'password1': 'Pa$sw0rd', 'password2': 'Pa$sw0rd', 'accept_terms': True } form = RegistrationFormHoneypot(data=data) self.assertFalse(form.is_valid()) ================================================ FILE: tests/test_managers.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib.auth import get_user_model from django.test import TestCase from example.models import Customer class UserManagerTest(TestCase): user_email = 'user@example.com' user_password = 'pa$sw0Rd' def test_create_user(self): user = get_user_model().objects.create_user(self.user_email) self.assertEqual(user.email, self.user_email) self.assertFalse(user.has_usable_password()) self.assertTrue(user.is_active) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) def test_create_superuser(self): user = get_user_model().objects.create_superuser( self.user_email, self.user_password) self.assertEqual(user.email, self.user_email) self.assertTrue(user.check_password, self.user_password) self.assertTrue(user.is_active) self.assertTrue(user.is_staff) self.assertTrue(user.is_superuser) def test_inactive_user_creation(self): # Create deactivated user user = get_user_model().objects.create_user( self.user_email, self.user_password, is_active=False) self.assertFalse(user.is_active) def test_staff_user_creation(self): # Create staff user user = get_user_model().objects.create_user( self.user_email, self.user_password, is_staff=True) self.assertTrue(user.is_staff) def test_empty_username(self): self.assertRaises(ValueError, get_user_model().objects.create_user, email='') def test_automatic_downcasting_of_inherited_user_models(self): get_user_model().objects.create_superuser( self.user_email, self.user_password) Customer.objects.create_user('customer@example.com', 'cu$t0meR') self.assertQuerysetEqual( get_user_model().objects.all(), ['', ''], ordered=False) ================================================ FILE: tests/test_models.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib.auth import get_user_model from django.core import mail from django.test import TestCase class TestUsersModels(TestCase): user_email = 'user@example.com' user_password = 'pa$sw0Rd' def create_user(self): return get_user_model().objects.create_user(self.user_email, self.user_password) def test_user_creation(self): user = self.create_user() self.assertEqual(get_user_model().objects.all().count(), 1) self.assertEqual(user.email, self.user_email) self.assertTrue(user.is_active) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) def test_user_get_full_name(self): user = self.create_user() self.assertEqual(user.get_full_name(), self.user_email) def test_user_get_short_name(self): user = self.create_user() self.assertEqual(user.get_short_name(), self.user_email) def test_email_user(self): # Email definition subject = 'email subject' message = 'email message' from_email = 'from@example.com' user = self.create_user() # Test that no message exists self.assertEqual(len(mail.outbox), 0) # Send test email user.email_user(subject, message, from_email) # Test that one message has been sent self.assertEqual(len(mail.outbox), 1) # Verify that the email is correct self.assertEqual(mail.outbox[0].subject, subject) self.assertEqual(mail.outbox[0].body, message) self.assertEqual(mail.outbox[0].from_email, from_email) self.assertEqual(mail.outbox[0].to, [user.email]) def test_user_activation(self): user = get_user_model().objects.create_user( self.user_email, self.user_password, is_active=False) # check user is not active by default self.assertFalse(user.is_active) # activate user user.activate() self.assertTrue(user.is_active) def test_(self): user = self.create_user() self.assertIsNotNone(user.user_type) ================================================ FILE: tests/test_utils.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import date, timedelta from django.contrib.auth import get_user_model from django.core import mail from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from users.conf import settings from users.utils import (auto_create_superuser, EmailActivationTokenGenerator, send_activation_email) class CreateSuperuserTest(TestCase): user_email = 'user@example.com' user_password = 'pa$sw0Rd' @override_settings(USERS_CREATE_SUPERUSER=True, USERS_SUPERUSER_EMAIL=user_email, USERS_SUPERUSER_PASSWORD=user_password) def test_auto_create_superuser(self): auto_create_superuser(sender=None) user = get_user_model().objects.get(email=self.user_email) self.assertTrue(user.is_active) self.assertTrue(user.is_staff) self.assertTrue(user.is_superuser) class SendActivationEmailTest(TestCase): user_email = 'user@example.com' user_password = 'pa$sw0Rd' @override_settings(USERS_VERIFY_EMAIL=True) def test_send_activation_email(self): factory = RequestFactory() request = factory.get(reverse('users_register')) user = get_user_model().objects.create_user( self.user_email, self.user_password, is_active=False) send_activation_email(user=user, request=request) self.assertEqual(len(mail.outbox), 1) class EmailActivationTokenGeneratorTest(TestCase): user_email = 'user@example.com' user_password = 'pa$sw0Rd' def create_user(self): return get_user_model().objects.create_user(self.user_email, self.user_password) def test_make_token(self): """ Ensure that we can make a token and that it is valid """ user = self.create_user() token_generator = EmailActivationTokenGenerator() token = token_generator.make_token(user) self.assertTrue(token_generator.check_token(user, token)) def test_bad_token(self): """ Ensure bad activation keys are rejected """ user = self.create_user() token_generator = EmailActivationTokenGenerator() bad_activation_keys = ( 'emailactivationtokengenerator', 'emailactivation-tokengenerator', '3rd-bademailactivationkey' ) for key in bad_activation_keys: self.assertFalse(token_generator.check_token(user, key)) def test_timeout(self): """ Ensure we can use the token after n days, but no greater. """ # Uses a mocked version of EmailActivationTokenGenerator # so we can change the value of 'today' class Mocked(EmailActivationTokenGenerator): def __init__(self, today): self._today_val = today def _today(self): return self._today_val user = self.create_user() token_generator = EmailActivationTokenGenerator() token = token_generator.make_token(user) p1 = Mocked(date.today() + timedelta(settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS)) self.assertTrue(p1.check_token(user, token)) p2 = Mocked(date.today() + timedelta(settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS + 1)) self.assertFalse(p2.check_token(user, token)) ================================================ FILE: tests/test_views.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- import re from django.contrib.auth import get_user_model from django.core import mail from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from users.forms import RegistrationForm, RegistrationFormHoneypot class RegisterViewTest(TestCase): user_data = { 'email': 'user@example.com', 'password1': 'pa$sw0Rd', 'password2': 'pa$sw0Rd' } @override_settings(USERS_REGISTRATION_OPEN=True) def test_registration_allowed(self): resp = self.client.get(reverse('users_register')) self.assertEqual(200, resp.status_code) @override_settings(USERS_REGISTRATION_OPEN=False) def test_registration_closed(self): resp = self.client.get(reverse('users_register')) self.assertRedirects(resp, reverse('users_registration_closed')) @override_settings(USERS_SPAM_PROTECTION=False) def test_registration_form(self): resp = self.client.get(reverse('users_register')) self.assertEqual(200, resp.status_code) self.failUnless(isinstance(resp.context['form'], RegistrationForm)) @override_settings(USERS_SPAM_PROTECTION=True) def test_registration_form_with_honeypot(self): resp = self.client.get(reverse('users_register')) self.assertEqual(200, resp.status_code) self.failUnless(isinstance(resp.context['form'], RegistrationFormHoneypot)) def test_registration(self): resp = self.client.post(reverse('users_register'), self.user_data) self.assertRedirects(resp, reverse('users_registration_complete')) def test_registration_created_new_user(self): resp = self.client.post(reverse('users_register'), self.user_data) self.assertEqual(get_user_model().objects.all().count(), 1) @override_settings(LOGIN_REDIRECT_URL=reverse('users_registration_complete')) def test_authenticated_users_are_redirected(self): user = get_user_model().objects.create_user( self.user_data['email'], self.user_data['password1'], is_active=True) login = self.client.login( username=self.user_data['email'], password=self.user_data['password1']) self.assertEqual(login, True) resp = self.client.post(reverse('users_register'), self.user_data) self.assertRedirects(resp, reverse('users_registration_complete')) @override_settings(USERS_VERIFY_EMAIL=True) def test_registered_user_is_not_active(self): resp = self.client.post(reverse('users_register'), self.user_data) new_user = get_user_model().objects.get(email=self.user_data['email']) self.failIf(new_user.is_active) @override_settings(USERS_VERIFY_EMAIL=True) def test_activation_email_was_sent(self): resp = self.client.post(reverse('users_register'), self.user_data) self.assertEqual(len(mail.outbox), 1) class ActivationViewTest(TestCase): user_data = { 'email': 'user@example.com', 'password1': 'pa$sw0Rd', 'password2': 'pa$sw0Rd' } @override_settings(USERS_VERIFY_EMAIL=True) def test_activation_view(self): self.client.post(reverse('users_register'), self.user_data) activation_email = mail.outbox[0] urlmatch = re.search(r'https?://[^/]*(/.*activate/\S*)', activation_email.body) self.assertTrue(urlmatch is not None, 'No URL found in sent email') resp = self.client.get(urlmatch.groups()[0]) self.assertRedirects(resp, reverse('users_activation_complete')) new_user = get_user_model().objects.get(email=self.user_data['email']) self.assertTrue(new_user.is_active) @override_settings(USERS_VERIFY_EMAIL=True) def test_activation_view_fails_as_expected(self): url = reverse('users_activate', kwargs={ 'uidb64': 'MQ', 'token': 'bad-69b5cdcd57c6854d1b04' }) resp = self.client.get(url) self.assertEqual(200, resp.status_code) self.failUnless(resp.context['title'], 'Email confirmation unsuccessful') ================================================ FILE: tox.ini ================================================ [tox] envlist = py26, py27, py33 [testenv] setenv = PYTHONPATH = {toxinidir}:{toxinidir}/users commands = python runtests.py deps = -r{toxinidir}/requirements-test.txt ================================================ FILE: users/__init__.py ================================================ __version__ = '0.2.2' ================================================ FILE: users/admin.py ================================================ from django.contrib import admin, messages from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import ugettext_lazy as _ from .conf import settings from .forms import UserChangeForm, UserCreationForm from .models import User from .utils import send_activation_email try: from django.contrib.admin.utils import model_ngettext except ImportError: # pragma: no cover from django.contrib.admin.util import model_ngettext class UserModelFilter(admin.SimpleListFilter): """ An admin list filter for the UserAdmin which enables filtering by its child models. """ title = _('user type') parameter_name = 'user_type' def lookups(self, request, model_admin): user_types = set([user.user_type for user in model_admin.model.objects.all()]) return [(user_type.id, user_type.name) for user_type in user_types] def queryset(self, request, queryset): try: value = int(self.value()) except TypeError: value = None if value: return queryset.filter(user_type_id__exact=value) else: return queryset class UserAdmin(BaseUserAdmin): fieldsets = ( (None, { 'fields': ('email', 'password') }), (_('Permissions'), { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions') }), (_('Important dates'), { 'fields': ('last_login', 'date_joined') }), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2') }), ) form = UserChangeForm add_form = UserCreationForm list_display = ('email', 'is_active') list_filter = (UserModelFilter, 'is_staff', 'is_superuser', 'is_active',) search_fields = ('email',) ordering = ('email',) actions = ('activate_users', 'send_activation_email', ) readonly_fields = ('last_login', 'date_joined', ) def get_queryset(self, request): # optimize queryset for list display. qs = self.model.base_objects.get_queryset() ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs def activate_users(self, request, queryset): """ Activates the selected users, if they are not already activated. """ n = 0 for user in queryset: if not user.is_active: user.activate() n += 1 self.message_user( request, _('Successfully activated %(count)d %(items)s.') % {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS) activate_users.short_description = _('Activate selected %(verbose_name_plural)s') def send_activation_email(self, request, queryset): """ Send activation emails for the selected users, if they are not already activated. """ n = 0 for user in queryset: if not user.is_active and settings.USERS_VERIFY_EMAIL: send_activation_email(user=user, request=request) n += 1 self.message_user( request, _('Activation emails sent to %(count)d %(items)s.') % {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS) send_activation_email.short_description = \ _('Send activation emails to selected %(verbose_name_plural)s') admin.site.register(User, UserAdmin) ================================================ FILE: users/compat.py ================================================ import base64 from binascii import Error as BinasciiError try: from django.utils.http import urlsafe_base64_encode except ImportError: def urlsafe_base64_encode(s): """ Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b'\n=') try: from django.utils.http import urlsafe_base64_decode except ImportError: def urlsafe_base64_decode(s): """ Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped. """ s = s.encode('utf-8') # base64encode should only return ASCII. try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'=')) except (LookupError, BinasciiError) as e: raise ValueError(e) ================================================ FILE: users/conf.py ================================================ from appconf import AppConf from django.conf import settings class UsersAppConf(AppConf): VERIFY_EMAIL = False CREATE_SUPERUSER = settings.DEBUG SUPERUSER_EMAIL = 'superuser@djangoproject.com' SUPERUSER_PASSWORD = 'django' EMAIL_CONFIRMATION_TIMEOUT_DAYS = 3 SPAM_PROTECTION = True REGISTRATION_OPEN = True AUTO_LOGIN_ON_ACTIVATION = True AUTO_LOGIN_AFTER_REGISTRATION = False PASSWORD_MIN_LENGTH = 5 PASSWORD_MAX_LENGTH = None CHECK_PASSWORD_COMPLEXITY = True PASSWORD_POLICY = { 'UPPER': 0, # Uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'LOWER': 0, # Lowercase 'abcdefghijklmnopqrstuvwxyz' 'DIGITS': 0, # Digits '0123456789' 'PUNCTUATION': 0 # Punctuation """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" } VALIDATE_EMAIL_DOMAIN = True EMAIL_DOMAINS_BLACKLIST = [] EMAIL_DOMAINS_WHITELIST = [] class Meta: prefix = 'users' ================================================ FILE: users/fields.py ================================================ import string from django import forms from django.core.validators import validate_email from django.forms.widgets import CheckboxInput from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _ from .conf import settings class LengthValidator(object): code = 'length' def __init__(self, min_length=None, max_length=None): self.min_length = min_length or settings.USERS_PASSWORD_MIN_LENGTH self.max_length = max_length or settings.USERS_PASSWORD_MAX_LENGTH def __call__(self, value): if self.min_length and len(value) < self.min_length: raise forms.ValidationError( _('Password too short (must be %s characters or more)') % self.min_length, code=self.code) elif self.max_length and len(value) > self.max_length: raise forms.ValidationError( _('Password too long (must be %s characters or less)') % self.max_length, code=self.code) length_validator = LengthValidator() class ComplexityValidator(object): code = 'complexity' message = _('Weak password, %s') def __init__(self): self.password_policy = settings.USERS_PASSWORD_POLICY def __call__(self, value): if not settings.USERS_CHECK_PASSWORD_COMPLEXITY: # pragma: no cover return uppercase, lowercase, digits, non_ascii, punctuation = set(), set(), set(), set(), set() for char in value: if char.isupper(): uppercase.add(char) elif char.islower(): lowercase.add(char) elif char.isdigit(): digits.add(char) elif char in string.punctuation: punctuation.add(char) else: non_ascii.add(char) if len(uppercase) < self.password_policy.get('UPPER', 0): raise forms.ValidationError( self.message % _('must contain %(UPPER)s or ' 'more uppercase characters (A-Z)') % self.password_policy, code=self.code) elif len(lowercase) < self.password_policy.get('LOWER', 0): raise forms.ValidationError( self.message % _('Must contain %(LOWER)s or ' 'more lowercase characters (a-z)') % self.password_policy, code=self.code) elif len(digits) < self.password_policy.get('DIGITS', 0): raise forms.ValidationError( self.message % _('must contain %(DIGITS)s or ' 'more numbers (0-9)') % self.password_policy, code=self.code) elif len(punctuation) < self.password_policy.get('PUNCTUATION', 0): raise forms.ValidationError( self.message % _('must contain %(PUNCTUATION)s or more ' 'symbols') % self.password_policy, code=self.code) complexity_validator = ComplexityValidator() class PasswordField(forms.CharField): widget = forms.PasswordInput() default_validators = [length_validator, complexity_validator, ] class HoneyPotField(forms.BooleanField): widget = CheckboxInput def __init__(self, *args, **kwargs): super(HoneyPotField, self).__init__(*args, **kwargs) self.required = False if not self.label: self.label = _('Are you human? (Sorry, we have to ask!)') if not self.help_text: self.help_text = _('Please don\'t check this box if you are a human.') def validate(self, value): if value: raise forms.ValidationError(_('Doh! You are a robot!')) class EmailDomainValidator(object): message = _('Sorry, %s emails are not allowed. Please use a different email address.') code = 'invalid' def __init__(self, ): self.domain_blacklist = settings.USERS_EMAIL_DOMAINS_BLACKLIST self.domain_whitelist = settings.USERS_EMAIL_DOMAINS_WHITELIST def __call__(self, value): if not settings.USERS_VALIDATE_EMAIL_DOMAIN: # pragma: no cover return if not value or '@' not in value: raise forms.ValidationError(_('Enter a valid email address.'), code=self.code) value = force_text(value) user_part, domain_part = value.rsplit('@', 1) if self.domain_blacklist and domain_part in self.domain_blacklist: raise forms.ValidationError(self.message % domain_part, code=self.code) if self.domain_whitelist and domain_part not in self.domain_whitelist: raise forms.ValidationError(self.message % domain_part, code=self.code) validate_email_domain = EmailDomainValidator() class UsersEmailField(forms.EmailField): default_validators = [validate_email, validate_email_domain] ================================================ FILE: users/forms.py ================================================ from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext_lazy as _ from .conf import settings from .fields import HoneyPotField, PasswordField, UsersEmailField class UserCreationForm(forms.ModelForm): error_messages = { 'duplicate_email': _('A user with that email already exists.'), 'password_mismatch': _('The two password fields didn\'t match.'), } email = UsersEmailField(label=_('Email Address'), max_length=255) password1 = PasswordField(label=_('Password')) password2 = PasswordField( label=_('Password Confirmation'), help_text=_('Enter the same password as above, for verification.')) class Meta: model = get_user_model() fields = ('email',) def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data['email'] try: get_user_model()._default_manager.get(email=email) except get_user_model().DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) user.is_active = not settings.USERS_VERIFY_EMAIL if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField(label=_('Password'), help_text=_( 'Raw passwords are not stored, so there is no way to see ' 'this user\'s password, but you can change the password ' 'using this form.')) class Meta: model = get_user_model() exclude = () def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') def clean_password(self): return self.initial['password'] class RegistrationForm(UserCreationForm): error_css_class = 'error' required_css_class = 'required' class RegistrationFormTermsOfService(RegistrationForm): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ tos = forms.BooleanField( label=_('I have read and agree to the Terms of Service'), widget=forms.CheckboxInput, error_messages={ 'required': _('You must agree to the terms to register') }) class RegistrationFormHoneypot(RegistrationForm): """ Subclass of ``RegistrationForm`` which adds a honeypot field for Spam Prevention """ accept_terms = HoneyPotField() ================================================ FILE: users/managers.py ================================================ from django.contrib.auth.models import BaseUserManager from django.utils import timezone from model_utils.managers import InheritanceQuerySet from .conf import settings class UserManager(BaseUserManager): def get_queryset(self): """ Fixes get_query_set vs get_queryset for Django <1.6 """ try: qs = super(UserManager, self).get_queryset() except AttributeError: # pragma: no cover qs = super(UserManager, self).get_query_set() return qs get_query_set = get_queryset def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): users_auto_activate = not settings.USERS_VERIFY_EMAIL now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) is_active = extra_fields.pop('is_active', users_auto_activate) user = self.model(email=email, is_staff=is_staff, is_active=is_active, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): is_staff = extra_fields.pop('is_staff', False) return self._create_user(email=email, password=password, is_staff=is_staff, is_superuser=False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email=email, password=password, is_staff=True, is_superuser=True, is_active=True, **extra_fields) class UserInheritanceManager(UserManager): def get_queryset(self): return InheritanceQuerySet(self.model).select_subclasses() get_query_set = get_queryset ================================================ FILE: users/migrations/0001_initial.py ================================================ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(default=django.utils.timezone.now, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(unique=True, max_length=255, verbose_name='email address', db_index=True)), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(to='auth.Group', verbose_name='groups', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user')), ('user_permissions', models.ManyToManyField(to='auth.Permission', verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user')), ('user_type', models.ForeignKey(editable=False, on_delete=models.SET_NULL, to='contenttypes.ContentType', null=True)), ], options={ 'abstract': False, 'verbose_name': 'User', 'swappable': 'AUTH_USER_MODEL', 'verbose_name_plural': 'Users', }, bases=(models.Model,), ), ] ================================================ FILE: users/migrations/0002_alter_user_last_login_null.py ================================================ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='user', name='last_login', field=models.DateTimeField(null=True, verbose_name='last login', blank=True), ), ] ================================================ FILE: users/migrations/__init__.py ================================================ ================================================ FILE: users/models.py ================================================ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.contrib.contenttypes.models import ContentType from django.core.mail import send_mail from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .conf import settings from .managers import UserInheritanceManager, UserManager class AbstractUser(AbstractBaseUser, PermissionsMixin): USERS_AUTO_ACTIVATE = not settings.USERS_VERIFY_EMAIL email = models.EmailField( _('email address'), max_length=255, unique=True, db_index=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.')) is_active = models.BooleanField( _('active'), default=USERS_AUTO_ACTIVATE, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) user_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True, editable=False) objects = UserInheritanceManager() base_objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('User') verbose_name_plural = _('Users') abstract = True def get_full_name(self): """ Return the email.""" return self.email def get_short_name(self): """ Return the email.""" return self.email def email_user(self, subject, message, from_email=None): """ Send an email to this User.""" send_mail(subject, message, from_email, [self.email]) def activate(self): self.is_active = True self.save() def save(self, *args, **kwargs): if not self.user_type_id: self.user_type = ContentType.objects.get_for_model(self, for_concrete_model=False) super(AbstractUser, self).save(*args, **kwargs) class User(AbstractUser): """ Concrete class of AbstractUser. Use this if you don't need to extend User. """ class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL' ================================================ FILE: users/signals.py ================================================ from django.dispatch import Signal # A new user has registered. user_registered = Signal(providing_args=['user', 'request']) # A user has activated his or her account. user_activated = Signal(providing_args=['user', 'request']) ================================================ FILE: users/templates/base.html ================================================ {% load i18n staticfiles %} {% block title %}{{ title|default:"django-users2"}}{% endblock %}
{% if messages %} {% for message in messages %}
{{ message }}
{% endfor %} {% endif %} {% block content %}

Use this template get you up and running with django-users2.

{% endblock content %}
================================================ FILE: users/templates/users/activate.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}

{% trans "Account activation failed" %}

{% endblock %} ================================================ FILE: users/templates/users/activation_complete.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}

{% trans "Your account is now activated." %}

{% endblock %} ================================================ FILE: users/templates/users/activation_email.html ================================================ {% load i18n %} {% trans "Thank you for registering an account at" %} {{ site.name }} {% trans "To activate your registration, please visit the following page:" %} {{ protocol }}://{{ site.domain }}{% url 'users_activate' uid token %} {% blocktrans %}This link will expire in {{ expiration_days }} days.{% endblocktrans %} {% trans "If you didn't register this account you can simply delete this email and we won't bother you again." %} ================================================ FILE: users/templates/users/activation_email_subject.html ================================================ {% load i18n %}{% trans "Account activation on" %} {{ site.name }} ================================================ FILE: users/templates/users/login.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}
{% if form.errors %} {% include "users/partials/errors.html" %} {% endif %} {% csrf_token %} {% for field in form %} {% include "users/partials/field.html" %} {% endfor %}

{% trans "Forgot password" %}

{% trans "Register" %}

{% endblock %} ================================================ FILE: users/templates/users/logout.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}

{% trans "Logged out" %}

{% endblock %} ================================================ FILE: users/templates/users/partials/errors.html ================================================ {% if form.errors and form.non_field_errors %}
    {{ form.non_field_errors|unordered_list }}
{% endif %} ================================================ FILE: users/templates/users/partials/field.html ================================================ {% load form_tags %} {% if field.is_hidden %} {{ field }} {% elif field|is_honeypot %} {% include "users/partials/honeypot.html" %} {% else %}
{% if field.errors %}
    {{ field.errors|unordered_list }}
{% endif %} {% if field|is_checkbox %} {{ field }} {% endif %} {% if not field|is_checkbox %} {{ field }} {% endif %} {% if field.help_text %}
{{ field.help_text|safe }}
{% endif %}
{% endif %} ================================================ FILE: users/templates/users/partials/honeypot.html ================================================ {% load form_tags %}
{% if field.errors %}
    {{ field.errors|unordered_list }}
{% endif %} {% if field|is_checkbox %} {{ field }} {% endif %} {% if not field|is_checkbox %} {{ field }} {% endif %} {% if field.help_text %}
{{ field.help_text|safe }}
{% endif %}
================================================ FILE: users/templates/users/password_change_done.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}

{% trans "Password changed" %}

{% endblock %} ================================================ FILE: users/templates/users/password_change_form.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}
{% if form.errors %} {% include "users/partials/errors.html" %} {% endif %} {% csrf_token %} {% for field in form %} {% include "users/partials/field.html" %} {% endfor %}
{% endblock %} ================================================ FILE: users/templates/users/password_reset_complete.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}

{% trans "Password reset successfully" %}

{% trans "Log in" %}

{% endblock %} ================================================ FILE: users/templates/users/password_reset_confirm.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %} {% if validlink %}
{% if form.errors %} {% include "users/partials/errors.html" %} {% endif %} {% csrf_token %} {% for field in form %} {% include "users/partials/field.html" %} {% endfor %}
{% else %}

{% trans "Password reset failed" %}

{% endif %} {% endblock %} ================================================ FILE: users/templates/users/password_reset_done.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}

{% trans "Email with password reset instructions has been sent." %}

{% endblock %} ================================================ FILE: users/templates/users/password_reset_email.html ================================================ {% load i18n %} {% blocktrans %}Reset password at {{ site_name }}{% endblocktrans %}: {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'users_password_reset_confirm' uid token %} {% endblock %} ================================================ FILE: users/templates/users/password_reset_form.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}
{% if form.errors %} {% include "users/partials/errors.html" %} {% endif %} {% csrf_token %} {% for field in form %} {% include "users/partials/field.html" %} {% endfor %}
{% endblock %} ================================================ FILE: users/templates/users/password_reset_subject.html ================================================ {% load i18n %}{% autoescape off %} {% blocktrans %}Password reset on {{ site_name }}{% endblocktrans %} {% endautoescape %} ================================================ FILE: users/templates/users/registration_closed.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}

{% trans "Sign Up Closed" %}

{% trans "We are sorry, but the sign up is currently closed." %}

{% endblock %} ================================================ FILE: users/templates/users/registration_complete.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}

{% trans "You are now registered. Activation email sent." %}

{% endblock %} ================================================ FILE: users/templates/users/registration_form.html ================================================ {% extends "base.html" %} {% load i18n %} {% block content %}
{% if form.errors %} {% include "users/partials/errors.html" %} {% endif %} {% csrf_token %} {% for field in form %} {% include "users/partials/field.html" %} {% endfor %}
{% endblock %} ================================================ FILE: users/templatetags/__init__.py ================================================ ================================================ FILE: users/templatetags/form_tags.py ================================================ from django import forms, template from users.fields import HoneyPotField register = template.Library() @register.filter def is_checkbox(field): return isinstance(field.field.widget, forms.CheckboxInput) @register.filter def input_class(field): """ Returns widgets class name in lowercase """ return field.field.widget.__class__.__name__.lower() @register.filter def is_honeypot(field): return isinstance(field.field, HoneyPotField) ================================================ FILE: users/urls.py ================================================ from django.conf.urls import url from django.contrib.auth import views as auth_views from .views import (activate, activation_complete, register, registration_closed, registration_complete) urlpatterns = [ url(r'^register/$', register, name='users_register'), url(r'^register/closed/$', registration_closed, name='users_registration_closed'), url(r'^register/complete/$', registration_complete, name='users_registration_complete'), url(r'^activate/complete/$', activation_complete, name='users_activation_complete'), url(r'^activate/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='users_activate'), url(r'^login/$', auth_views.LoginView.as_view( template_name='users/login.html'), name='users_login'), url(r'^logout/$', auth_views.LogoutView.as_view( template_name='users/logout.html'), name='users_logout'), url(r'^password_change/$', auth_views.PasswordChangeView.as_view( template_name='users/password_change_form.html', success_url='users_password_change_done'), name='users_password_change'), url(r'^password_change/done/$', auth_views.PasswordChangeDoneView.as_view( template_name='users/password_change_done.html'), name='users_password_change_done'), url(r'^password_reset/$', auth_views.PasswordResetView.as_view( template_name='users/password_reset_form.html', email_template_name='users/password_reset_email.html', subject_template_name='users/password_reset_subject.html', success_url='users_password_reset_done'), name='users_password_reset'), url(r'^password_reset/done/$', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html'), name='users_password_reset_done'), url(r'^reset/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html', success_url='users_password_reset_complete'), name='users_password_reset_confirm'), url(r'^reset/done/$', auth_views.PasswordResetCompleteView.as_view( template_name='users/password_reset_complete.html'), name='users_password_reset_complete'), ] ================================================ FILE: users/utils.py ================================================ from datetime import date from django.contrib.auth import get_user_model from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils import six from django.utils.crypto import constant_time_compare, salted_hmac from django.utils.encoding import force_bytes from django.utils.http import base36_to_int, int_to_base36 from .compat import urlsafe_base64_encode from .conf import settings try: from django.contrib.sites.shortcuts import get_current_site except ImportError: # pragma: no cover from django.contrib.sites.models import get_current_site try: from django.db.models.signals import post_migrate except ImportError: # pragma: no cover from django.db.models.signals import post_syncdb as post_migrate if settings.USERS_CREATE_SUPERUSER: try: # create_superuser is removed in django 1.7 from django.contrib.auth.management import create_superuser except ImportError: # pragma: no cover pass else: # Prevent interactive question about wanting a superuser created. from django.contrib.auth import models as auth_app post_migrate.disconnect( create_superuser, sender=auth_app, dispatch_uid='django.contrib.auth.management.create_superuser') def auto_create_superuser(sender, **kwargs): if not settings.USERS_CREATE_SUPERUSER: return email = settings.USERS_SUPERUSER_EMAIL password = settings.USERS_SUPERUSER_PASSWORD User = get_user_model() try: User.base_objects.get(email=email) except User.DoesNotExist: print('Creating superuser ({0}:{1})'.format(email, password)) User.objects.create_superuser(email, password) post_migrate.connect(auto_create_superuser, sender=None) class EmailActivationTokenGenerator(object): def make_token(self, user): return self._make_token_with_timestamp(user, self._num_days(self._today())) def check_token(self, user, token): """ Check that a activation token is correct for a given user. """ # Parse the token try: ts_b36, hash = token.split('-') except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS: return False return True def _make_token_with_timestamp(self, user, timestamp): ts_b36 = int_to_base36(timestamp) key_salt = 'users.utils.EmailActivationTokenGenerator' login_timestamp = '' if user.last_login is None else \ user.last_login.replace(microsecond=0, tzinfo=None) value = (six.text_type(user.pk) + six.text_type(user.email) + six.text_type(login_timestamp) + six.text_type(timestamp)) hash = salted_hmac(key_salt, value).hexdigest()[::2] return '%s-%s' % (ts_b36, hash) @staticmethod def _num_days(dt): return (dt - date(2001, 1, 1)).days @staticmethod def _today(): # Used for mocking in tests return date.today() def send_activation_email( user=None, request=None, from_email=None, subject_template='users/activation_email_subject.html', email_template='users/activation_email.html', html_email_template=None): if not user.is_active and settings.USERS_VERIFY_EMAIL: token_generator = EmailActivationTokenGenerator() current_site = get_current_site(request) context = { 'email': user.email, 'site': current_site, 'expiration_days': settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS, 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': token_generator.make_token(user=user), 'protocol': 'https' if request.is_secure() else 'http', } subject = render_to_string(subject_template, context) # email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = render_to_string(email_template, context) email_message = EmailMultiAlternatives(subject, body, from_email, [user.email]) if html_email_template is not None: html_email = render_to_string(html_email_template, context) email_message.attach_alternative(html_email, 'text/html') email_message.send() ================================================ FILE: users/views.py ================================================ from django.contrib import messages from django.contrib.auth import get_user_model, login from django.urls import reverse from django.shortcuts import redirect, resolve_url from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from .compat import urlsafe_base64_decode from .conf import settings from .signals import user_activated, user_registered from .utils import EmailActivationTokenGenerator, send_activation_email try: from django.contrib.sites.shortcuts import get_current_site except ImportError: # pragma: no cover from django.contrib.sites.models import get_current_site if settings.USERS_SPAM_PROTECTION: # pragma: no cover from .forms import RegistrationFormHoneypot as RegistrationForm else: from .forms import RegistrationForm @csrf_protect @never_cache def register(request, template_name='users/registration_form.html', activation_email_template_name='users/activation_email.html', activation_email_subject_template_name='users/activation_email_subject.html', activation_email_html_template_name=None, registration_form=RegistrationForm, registered_user_redirect_to=None, post_registration_redirect=None, activation_from_email=None, current_app=None, extra_context=None): if registered_user_redirect_to is None: registered_user_redirect_to = getattr(settings, 'LOGIN_REDIRECT_URL') if request.user.is_authenticated: return redirect(registered_user_redirect_to) if not settings.USERS_REGISTRATION_OPEN: return redirect(reverse('users_registration_closed')) if post_registration_redirect is None: post_registration_redirect = reverse('users_registration_complete') if request.method == 'POST': form = registration_form(request.POST) if form.is_valid(): user = form.save() if settings.USERS_AUTO_LOGIN_AFTER_REGISTRATION: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) elif not user.is_active and settings.USERS_VERIFY_EMAIL: opts = { 'user': user, 'request': request, 'from_email': activation_from_email, 'email_template': activation_email_template_name, 'subject_template': activation_email_subject_template_name, 'html_email_template': activation_email_html_template_name, } send_activation_email(**opts) user_registered.send(sender=user.__class__, request=request, user=user) return redirect(post_registration_redirect) else: form = registration_form() current_site = get_current_site(request) context = { 'form': form, 'site': current_site, 'site_name': current_site.name, 'title': _('Register'), } if extra_context is not None: # pragma: no cover context.update(extra_context) return TemplateResponse(request, template_name, context) def registration_closed(request, template_name='users/registration_closed.html', current_app=None, extra_context=None): context = { 'title': _('Registration closed'), } if extra_context is not None: # pragma: no cover context.update(extra_context) return TemplateResponse(request, template_name, context) def registration_complete(request, template_name='users/registration_complete.html', current_app=None, extra_context=None): context = { 'login_url': resolve_url(settings.LOGIN_URL), 'title': _('Registration complete'), } if extra_context is not None: # pragma: no cover context.update(extra_context) return TemplateResponse(request, template_name, context) @never_cache def activate(request, uidb64=None, token=None, template_name='users/activate.html', post_activation_redirect=None, current_app=None, extra_context=None): context = { 'title': _('Account activation '), } if post_activation_redirect is None: post_activation_redirect = reverse('users_activation_complete') UserModel = get_user_model() assert uidb64 is not None and token is not None token_generator = EmailActivationTokenGenerator() try: uid = urlsafe_base64_decode(uidb64) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): user.activate() user_activated.send(sender=user.__class__, request=request, user=user) if settings.USERS_AUTO_LOGIN_ON_ACTIVATION: user.backend = 'django.contrib.auth.backends.ModelBackend' # todo - remove this hack login(request, user) messages.info(request, 'Thanks for registering. You are now logged in.') return redirect(post_activation_redirect) else: title = _('Email confirmation unsuccessful') context = { 'title': title, } if extra_context is not None: # pragma: no cover context.update(extra_context) return TemplateResponse(request, template_name, context) def activation_complete(request, template_name='users/activation_complete.html', current_app=None, extra_context=None): context = { 'title': _('Activation complete'), } if extra_context is not None: # pragma: no cover context.update(extra_context) return TemplateResponse(request, template_name, context)