Full Code of mishbahr/django-users2 for AI

master 1ee244dc4ca1 cached
76 files
103.4 KB
27.1k tokens
146 symbols
1 requests
Download .txt
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) <mishbahx@gmail.com>

Contributors
------------

* John Matthew (jfmatth) <john@compunique.com>
* moemen <moemenology@gmail.com>
* Alwerdani <alwerdani@gmail.com>
* Weizhong Tu (twz915) <tuweizhong@163.com>
* Ahmed Maher (mxahmed) <ahmedmaherelmitwally@gmail.com>

================================================
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 <target>' where <target> is one of"
	@echo "  html       to make standalone HTML files"
	@echo "  dirhtml    to make HTML files named index.html in directories"
	@echo "  singlehtml to make a single large HTML file"
	@echo "  pickle     to make pickle files"
	@echo "  json       to make JSON files"
	@echo "  htmlhelp   to make HTML files and a HTML help project"
	@echo "  qthelp     to make HTML files and a qthelp project"
	@echo "  devhelp    to make HTML files and a Devhelp project"
	@echo "  epub       to make an epub"
	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
	@echo "  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
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'django-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 ^<target^>` where ^<target^> is one of
	echo.  html       to make standalone HTML files
	echo.  dirhtml    to make HTML files named index.html in directories
	echo.  singlehtml to make a single large HTML file
	echo.  pickle     to make pickle files
	echo.  json       to make JSON files
	echo.  htmlhelp   to make HTML files and a HTML help project
	echo.  qthelp     to make HTML files and a qthelp project
	echo.  devhelp    to make HTML files and a Devhelp project
	echo.  epub       to make an epub
	echo.  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter
	echo.  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),
            ['<User: user@example.com>', '<User: user1@example.com>'], 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(),
            ['<User: user@example.com>', '<Customer: customer@example.com>'], 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 <a href=\"password/\">this form</a>.'))

    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 %}<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>{% block title %}{{ title|default:"django-users2"}}{% endblock %}</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="description" content="">
	<meta name="author" content="">
</head>
<body>

<div class="header navbar">
	<div class="container">
		<a class="navbar-brand" href="/">Django Users</a>
	</div>
</div>
<div class="container">
	{% if messages %}
		{% for message in messages %}
			<div class="alert {% if message.tags %}alert-{{ message.tags }}"{% endif %}>{{ message }}</div>
		{% endfor %}
	{% endif %}
	{% block content %}
		<p>Use this template get you up and running with django-users2.</p>
	{% endblock content %}
</div>
</body>
</html>


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

{% block content %}
<p>{% trans "Account activation failed" %}</p>
{% endblock %}


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

{% block content %}
<p>{% trans "Your account is now activated." %}</p>
{% 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 %}
<div class="form-wrapper">
	<form method="post" action=".">
		{% if form.errors %}
			{% include "users/partials/errors.html" %}
		{% endif %}
		{% csrf_token %}
		{% for field in form %}
			{% include "users/partials/field.html" %}
		{% endfor %}
		<div class="button-wrapper submit">
			<input type="submit" value="{% trans 'Log in' %}" />
		</div>
		<input type="hidden" name="next" value="{{ next }}" />
		<p><a href="{% url 'users_password_reset' %}">{% trans "Forgot password" %}</a></p>
		<p><a href="{% url 'users_register' %}">{% trans "Register" %}</a></p>
	</form>
</div>
{% endblock %}


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

{% block content %}
<p>{% trans "Logged out" %}</p>
{% endblock %}


================================================
FILE: users/templates/users/partials/errors.html
================================================
{% if form.errors and form.non_field_errors %}
	<div class="form-errors">
		<ul>
			{{ form.non_field_errors|unordered_list }}
		</ul>
	</div>
{% 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 %}
	<div class="field-wrapper {{ field|input_class }} {{ field.css_classes }}{% if field|is_checkbox %} checkbox{% endif %}">
		{% if field.errors %}
			<ul class="errorlist">
				{{ field.errors|unordered_list }}
			</ul>
		{% endif %}
		{% if field|is_checkbox %}
			{{ field }}
		{% endif %}
		<label for="{{ field.id_for_label }}"{% if field.field.required %} class="required"{% endif %}>
			{{ field.label }}{% if field.field.required %}<span class="asterisk">*</span>{% endif %}
		</label>
		{% if not field|is_checkbox %}
			{{ field }}
		{% endif %}
		{% if field.help_text %}
			<div class="help_text">{{ field.help_text|safe }}</div>
		{% endif %}
	</div>
{% endif %}


================================================
FILE: users/templates/users/partials/honeypot.html
================================================
{% load form_tags %}

<div class="field-wrapper {{ field|input_class }} {{ field.css_classes }}{% if field|is_checkbox %} checkbox{% endif %}" style="border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;">
	{% if field.errors %}
		<ul class="errorlist">
			{{ field.errors|unordered_list }}
		</ul>
	{% endif %}
	{% if field|is_checkbox %}
		{{ field }}
	{% endif %}
	<label for="{{ field.id_for_label }}">
		{{ field.label }}
	</label>
	{% if not field|is_checkbox %}
		{{ field }}
	{% endif %}
	{% if field.help_text %}
		<div class="help_text">{{ field.help_text|safe }}</div>
	{% endif %}
</div>


================================================
FILE: users/templates/users/password_change_done.html
================================================
{% extends "base.html" %}
{% load i18n %}

{% block content %}
<p>{% trans "Password changed" %}</p>
{% endblock %}


================================================
FILE: users/templates/users/password_change_form.html
================================================
{% extends "base.html" %}
{% load i18n %}

{% block content %}
<div class="form-wrapper">
	<form method="post" action=".">
		{% if form.errors %}
			{% include "users/partials/errors.html" %}
		{% endif %}
		{% csrf_token %}
		{% for field in form %}
			{% include "users/partials/field.html" %}
		{% endfor %}
		<div class="button-wrapper submit">
			<input type="submit" value="{% trans 'Change Password' %}" />
		</div>
	</form>
</div>
{% endblock %}


================================================
FILE: users/templates/users/password_reset_complete.html
================================================
{% extends "base.html" %}
{% load i18n %}

{% block content %}
<p>{% trans "Password reset successfully" %}</p>
<p><a href="{% url 'users_login' %}">{% trans "Log in" %}</a></p>
{% endblock %}


================================================
FILE: users/templates/users/password_reset_confirm.html
================================================
{% extends "base.html" %}
{% load i18n %}

{% block content %}
{% if validlink %}
	<div class="form-wrapper">
		<form method="post" action=".">
			{% if form.errors %}
				{% include "users/partials/errors.html" %}
			{% endif %}
			{% csrf_token %}
			{% for field in form %}
				{% include "users/partials/field.html" %}
			{% endfor %}
			<div class="button-wrapper submit">
				<input type="submit" value="{% trans 'Submit' %}" />
			</div>
		</form>
	</div>
{% else %}
	<p>{% trans "Password reset failed" %}</p>
{% endif %}
{% endblock %}


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

{% block content %}
<p>{% trans "Email with password reset instructions has been sent." %}</p>
{% endblock %}


================================================
FILE: users/templates/users/password_reset_email.html
================================================
{% load i18n %}
{% blocktrans %}Reset password at {{ site_name }}{% endblocktrans %}:
{% block reset_link %}
<a rel="noreferrer" href="{{ protocol }}://{{ domain }}{% url 'users_password_reset_confirm' uid token %}">
  {{ protocol }}://{{ domain }}{% url 'users_password_reset_confirm' uid token %}
</a>
{% endblock %}


================================================
FILE: users/templates/users/password_reset_form.html
================================================
{% extends "base.html" %}
{% load i18n %}

{% block content %}
<div class="form-wrapper">
	<form method="post" action=".">
		{% if form.errors %}
			{% include "users/partials/errors.html" %}
		{% endif %}
		{% csrf_token %}
		{% for field in form %}
			{% include "users/partials/field.html" %}
		{% endfor %}
		<div class="button-wrapper submit">
			<input type="submit" value="{% trans 'Submit' %}" />
		</div>
	</form>
</div>
{% 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 %}
<h1>{% trans "Sign Up Closed" %}</h1>
<p>{% trans "We are sorry, but the sign up is currently closed." %}</p>
{% endblock %}


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

{% block content %}
<p>{% trans "You are now registered. Activation email sent." %}</p>
{% endblock %}

================================================
FILE: users/templates/users/registration_form.html
================================================
{% extends "base.html" %}
{% load i18n %}

{% block content %}
<div class="form-wrapper">
	<form method="post" action=".">
		{% if form.errors %}
			{% include "users/partials/errors.html" %}
		{% endif %}
		{% csrf_token %}
		{% for field in form %}
			{% include "users/partials/field.html" %}
		{% endfor %}
		<div class="button-wrapper submit">
			<input type="submit" value="{% trans 'Register' %}" />
		</div>
	</form>
</div>
{% 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<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[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<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[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)
Download .txt
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
Download .txt
SYMBOL INDEX (146 symbols across 22 files)

FILE: example/migrations/0001_initial.py
  class Migration (line 8) | class Migration(migrations.Migration):

FILE: example/models.py
  class Customer (line 7) | class Customer(User):
    class Meta (line 11) | class Meta:

FILE: runtests.py
  function run_tests (line 74) | def run_tests(*test_args):

FILE: tests/test_admin.py
  class AdminTest (line 14) | class AdminTest(TestCase):
    method setUp (line 19) | def setUp(self):
    method test_get_queryset (line 37) | def test_get_queryset(self):
    method test_send_activation_email (line 44) | def test_send_activation_email(self):
    method test_activate_users (line 52) | def test_activate_users(self):
    method tearDown (line 63) | def tearDown(self):

FILE: tests/test_fields.py
  class LengthValidatorTest (line 11) | class LengthValidatorTest(TestCase):
    method setUp (line 14) | def setUp(self):
    method test_password_length_validator_min_length (line 17) | def test_password_length_validator_min_length(self):
    method test_password_length_validator_max_length (line 26) | def test_password_length_validator_max_length(self):
  class ComplexityValidatorTest (line 36) | class ComplexityValidatorTest(TestCase):
    method test_complexity_validator_fails_no_uppercase (line 45) | def test_complexity_validator_fails_no_uppercase(self):
    method test_complexity_validator_fails_no_lowercase (line 56) | def test_complexity_validator_fails_no_lowercase(self):
    method test_complexity_validator_fails_no_digit (line 67) | def test_complexity_validator_fails_no_digit(self):
    method test_complexity_validator_fails_no_symbol (line 78) | def test_complexity_validator_fails_no_symbol(self):
    method test_complexity_validator_success (line 89) | def test_complexity_validator_success(self):
  class EmailDomainValidatorTest (line 98) | class EmailDomainValidatorTest(TestCase):
    method test_email_domain_validator_with_white_list (line 103) | def test_email_domain_validator_with_white_list(self):
    method test_email_domain_validator_with_black_list (line 114) | def test_email_domain_validator_with_black_list(self):

FILE: tests/test_forms.py
  class UserCreationFormTest (line 13) | class UserCreationFormTest(TestCase):
    method test_user_already_exists (line 15) | def test_user_already_exists(self):
    method test_invalid_email (line 28) | def test_invalid_email(self):
    method test_password_verification (line 38) | def test_password_verification(self):
    method test_password_is_not_saved_raw (line 50) | def test_password_is_not_saved_raw(self):
    method test_valid_user_are_saved (line 61) | def test_valid_user_are_saved(self):
  class UserChangeFormTest (line 73) | class UserChangeFormTest(TestCase):
    method test_username_validity (line 75) | def test_username_validity(self):
    method test_unsuable_password (line 84) | def test_unsuable_password(self):
  class RegistrationFormTermsOfServiceTest (line 92) | class RegistrationFormTermsOfServiceTest(TestCase):
    method test_registration_form_with_tos_checkbox_validates (line 94) | def test_registration_form_with_tos_checkbox_validates(self):
    method test_registration_form_with_tos_checkbox_fails (line 104) | def test_registration_form_with_tos_checkbox_fails(self):
  class RegistrationFormHoneypotTest (line 115) | class RegistrationFormHoneypotTest(TestCase):
    method test_registration_form_with_honeypot_field (line 116) | def test_registration_form_with_honeypot_field(self):
    method test_registration_form_with_honeypot_field_fails_as_expected (line 125) | def test_registration_form_with_honeypot_field_fails_as_expected(self):

FILE: tests/test_managers.py
  class UserManagerTest (line 9) | class UserManagerTest(TestCase):
    method test_create_user (line 14) | def test_create_user(self):
    method test_create_superuser (line 22) | def test_create_superuser(self):
    method test_inactive_user_creation (line 32) | def test_inactive_user_creation(self):
    method test_staff_user_creation (line 38) | def test_staff_user_creation(self):
    method test_empty_username (line 44) | def test_empty_username(self):
    method test_automatic_downcasting_of_inherited_user_models (line 47) | def test_automatic_downcasting_of_inherited_user_models(self):

FILE: tests/test_models.py
  class TestUsersModels (line 8) | class TestUsersModels(TestCase):
    method create_user (line 13) | def create_user(self):
    method test_user_creation (line 16) | def test_user_creation(self):
    method test_user_get_full_name (line 26) | def test_user_get_full_name(self):
    method test_user_get_short_name (line 30) | def test_user_get_short_name(self):
    method test_email_user (line 34) | def test_email_user(self):
    method test_user_activation (line 57) | def test_user_activation(self):
    method test_ (line 66) | def test_(self):

FILE: tests/test_utils.py
  class CreateSuperuserTest (line 17) | class CreateSuperuserTest(TestCase):
    method test_auto_create_superuser (line 25) | def test_auto_create_superuser(self):
  class SendActivationEmailTest (line 35) | class SendActivationEmailTest(TestCase):
    method test_send_activation_email (line 41) | def test_send_activation_email(self):
  class EmailActivationTokenGeneratorTest (line 51) | class EmailActivationTokenGeneratorTest(TestCase):
    method create_user (line 55) | def create_user(self):
    method test_make_token (line 58) | def test_make_token(self):
    method test_bad_token (line 68) | def test_bad_token(self):
    method test_timeout (line 83) | def test_timeout(self):

FILE: tests/test_views.py
  class RegisterViewTest (line 14) | class RegisterViewTest(TestCase):
    method test_registration_allowed (line 22) | def test_registration_allowed(self):
    method test_registration_closed (line 27) | def test_registration_closed(self):
    method test_registration_form (line 32) | def test_registration_form(self):
    method test_registration_form_with_honeypot (line 38) | def test_registration_form_with_honeypot(self):
    method test_registration (line 43) | def test_registration(self):
    method test_registration_created_new_user (line 47) | def test_registration_created_new_user(self):
    method test_authenticated_users_are_redirected (line 52) | def test_authenticated_users_are_redirected(self):
    method test_registered_user_is_not_active (line 63) | def test_registered_user_is_not_active(self):
    method test_activation_email_was_sent (line 69) | def test_activation_email_was_sent(self):
  class ActivationViewTest (line 74) | class ActivationViewTest(TestCase):
    method test_activation_view (line 82) | def test_activation_view(self):
    method test_activation_view_fails_as_expected (line 94) | def test_activation_view_fails_as_expected(self):

FILE: users/admin.py
  class UserModelFilter (line 16) | class UserModelFilter(admin.SimpleListFilter):
    method lookups (line 24) | def lookups(self, request, model_admin):
    method queryset (line 28) | def queryset(self, request, queryset):
  class UserAdmin (line 40) | class UserAdmin(BaseUserAdmin):
    method get_queryset (line 71) | def get_queryset(self, request):
    method activate_users (line 79) | def activate_users(self, request, queryset):
    method send_activation_email (line 96) | def send_activation_email(self, request, queryset):

FILE: users/compat.py
  function urlsafe_base64_encode (line 7) | def urlsafe_base64_encode(s):
  function urlsafe_base64_decode (line 17) | def urlsafe_base64_decode(s):

FILE: users/conf.py
  class UsersAppConf (line 5) | class UsersAppConf(AppConf):
    class Meta (line 28) | class Meta:

FILE: users/fields.py
  class LengthValidator (line 12) | class LengthValidator(object):
    method __init__ (line 15) | def __init__(self, min_length=None, max_length=None):
    method __call__ (line 19) | def __call__(self, value):
  class ComplexityValidator (line 32) | class ComplexityValidator(object):
    method __init__ (line 36) | def __init__(self):
    method __call__ (line 39) | def __call__(self, value):
  class PasswordField (line 82) | class PasswordField(forms.CharField):
  class HoneyPotField (line 87) | class HoneyPotField(forms.BooleanField):
    method __init__ (line 90) | def __init__(self, *args, **kwargs):
    method validate (line 98) | def validate(self, value):
  class EmailDomainValidator (line 103) | class EmailDomainValidator(object):
    method __init__ (line 107) | def __init__(self, ):
    method __call__ (line 111) | def __call__(self, value):
  class UsersEmailField (line 131) | class UsersEmailField(forms.EmailField):

FILE: users/forms.py
  class UserCreationForm (line 10) | class UserCreationForm(forms.ModelForm):
    class Meta (line 23) | class Meta:
    method clean_email (line 27) | def clean_email(self):
    method clean_password2 (line 41) | def clean_password2(self):
    method save (line 52) | def save(self, commit=True):
  class UserChangeForm (line 61) | class UserChangeForm(forms.ModelForm):
    class Meta (line 68) | class Meta:
    method __init__ (line 72) | def __init__(self, *args, **kwargs):
    method clean_password (line 78) | def clean_password(self):
  class RegistrationForm (line 82) | class RegistrationForm(UserCreationForm):
  class RegistrationFormTermsOfService (line 87) | class RegistrationFormTermsOfService(RegistrationForm):
  class RegistrationFormHoneypot (line 101) | class RegistrationFormHoneypot(RegistrationForm):

FILE: users/managers.py
  class UserManager (line 9) | class UserManager(BaseUserManager):
    method get_queryset (line 11) | def get_queryset(self):
    method _create_user (line 23) | def _create_user(self, email, password,
    method create_user (line 40) | def create_user(self, email, password=None, **extra_fields):
    method create_superuser (line 47) | def create_superuser(self, email, password, **extra_fields):
  class UserInheritanceManager (line 53) | class UserInheritanceManager(UserManager):
    method get_queryset (line 54) | def get_queryset(self):

FILE: users/migrations/0001_initial.py
  class Migration (line 8) | class Migration(migrations.Migration):

FILE: users/migrations/0002_alter_user_last_login_null.py
  class Migration (line 7) | class Migration(migrations.Migration):

FILE: users/models.py
  class AbstractUser (line 12) | class AbstractUser(AbstractBaseUser, PermissionsMixin):
    class Meta (line 34) | class Meta:
    method get_full_name (line 39) | def get_full_name(self):
    method get_short_name (line 43) | def get_short_name(self):
    method email_user (line 47) | def email_user(self, subject, message, from_email=None):
    method activate (line 51) | def activate(self):
    method save (line 55) | def save(self, *args, **kwargs):
  class User (line 61) | class User(AbstractUser):
    class Meta (line 68) | class Meta(AbstractUser.Meta):

FILE: users/templatetags/form_tags.py
  function is_checkbox (line 9) | def is_checkbox(field):
  function input_class (line 14) | def input_class(field):
  function is_honeypot (line 22) | def is_honeypot(field):

FILE: users/utils.py
  function auto_create_superuser (line 40) | def auto_create_superuser(sender, **kwargs):
  class EmailActivationTokenGenerator (line 57) | class EmailActivationTokenGenerator(object):
    method make_token (line 59) | def make_token(self, user):
    method check_token (line 62) | def check_token(self, user, token):
    method _make_token_with_timestamp (line 87) | def _make_token_with_timestamp(self, user, timestamp):
    method _num_days (line 99) | def _num_days(dt):
    method _today (line 103) | def _today():
  function send_activation_email (line 108) | def send_activation_email(

FILE: users/views.py
  function register (line 29) | def register(request,
  function registration_closed (line 89) | def registration_closed(request,
  function registration_complete (line 101) | def registration_complete(request,
  function activate (line 115) | def activate(request,
  function activation_complete (line 160) | def activation_complete(request,
Condensed preview — 76 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (114K chars).
[
  {
    "path": ".coveragerc",
    "chars": 238,
    "preview": "[run]\nomit =\n    */migrations/*\n    */compat.py\n    */__init__.py\n    */test_*\n\n[report]\nexclude_lines =\n    def __repr_"
  },
  {
    "path": ".gitignore",
    "chars": 409,
    "preview": "*.py[cod]\n\n# C extensions\n*.so\n\n# Packages\n*.egg\n*.egg-info\ndist\nbuild\neggs\nparts\nbin\nvar\nsdist\ndevelop-eggs\n.installed."
  },
  {
    "path": ".travis.yml",
    "chars": 464,
    "preview": "# Config file for automatic testing at travis-ci.org\n\nlanguage: python\n\npython:\n  - \"3.5\"\n  - \"3.4\"\n  - \"2.7\"\nenv:\n    -"
  },
  {
    "path": "AUTHORS.rst",
    "chars": 353,
    "preview": "=======\nCredits\n=======\n\nDevelopment Lead\n----------------\n\n* Mishbah Razzaque (mishbahr) <mishbahx@gmail.com>\n\nContribu"
  },
  {
    "path": "CONTRIBUTING.rst",
    "chars": 3204,
    "preview": "============\nContributing\n============\n\nContributions are welcome, and they are greatly appreciated! Every\nlittle bit he"
  },
  {
    "path": "HISTORY.rst",
    "chars": 97,
    "preview": ".. :changelog:\n\nHistory\n-------\n\n0.1.0 (2014-09-25)\n++++++++++++++++++\n\n* First release on PyPI.\n"
  },
  {
    "path": "LICENSE",
    "chars": 1476,
    "preview": "Copyright (c) 2014, Mishbah Razzaque\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or wi"
  },
  {
    "path": "MANIFEST.in",
    "chars": 172,
    "preview": "include AUTHORS.rst\ninclude CONTRIBUTING.rst\ninclude HISTORY.rst\ninclude LICENSE\ninclude README.rst\nrecursive-include us"
  },
  {
    "path": "Makefile",
    "chars": 1245,
    "preview": ".PHONY: clean-pyc clean-build docs\n\nhelp:\n\t@echo \"clean-build - remove build artifacts\"\n\t@echo \"clean-pyc - remove Pytho"
  },
  {
    "path": "README.rst",
    "chars": 5198,
    "preview": "=============================\ndjango-users2\n=============================\n\n.. image:: http://img.shields.io/travis/mishb"
  },
  {
    "path": "docs/Makefile",
    "chars": 6777,
    "preview": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD "
  },
  {
    "path": "docs/authors.rst",
    "chars": 27,
    "preview": ".. include:: ../AUTHORS.rst"
  },
  {
    "path": "docs/conf.py",
    "chars": 8151,
    "preview": "# -*- coding: utf-8 -*-\n#\n# complexity documentation build configuration file, created by\n# sphinx-quickstart on Tue Jul"
  },
  {
    "path": "docs/contributing.rst",
    "chars": 32,
    "preview": ".. include:: ../CONTRIBUTING.rst"
  },
  {
    "path": "docs/history.rst",
    "chars": 27,
    "preview": ".. include:: ../HISTORY.rst"
  },
  {
    "path": "docs/index.rst",
    "chars": 443,
    "preview": ".. complexity documentation master file, created by\n   sphinx-quickstart on Tue Jul  9 22:26:36 2013.\n   You can adapt t"
  },
  {
    "path": "docs/installation.rst",
    "chars": 208,
    "preview": "============\nInstallation\n============\n\nAt the command line::\n\n    $ easy_install django-users2\n\nOr, if you have virtual"
  },
  {
    "path": "docs/make.bat",
    "chars": 6466,
    "preview": "@ECHO OFF\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-build\n)\nset BUI"
  },
  {
    "path": "docs/readme.rst",
    "chars": 26,
    "preview": ".. include:: ../README.rst"
  },
  {
    "path": "docs/usage.rst",
    "chars": 86,
    "preview": "========\nUsage\n========\n\nTo use django-users2 in a project::\n\n    import django-users2"
  },
  {
    "path": "example/__init__.py",
    "chars": 23,
    "preview": "__author__ = 'mishbah'\n"
  },
  {
    "path": "example/migrations/0001_initial.py",
    "chars": 904,
    "preview": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.co"
  },
  {
    "path": "example/migrations/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "example/models.py",
    "chars": 393,
    "preview": "from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom users.models import User\n\n\ncl"
  },
  {
    "path": "requirements-test.txt",
    "chars": 105,
    "preview": "-r requirements.txt\n\ncoverage\ncoveralls\nmock>=1.0.1\nnose>=1.3.0\ndjango-nose>=1.2\nflake8>=2.1.0\ntox>=1.7.0"
  },
  {
    "path": "requirements.txt",
    "chars": 53,
    "preview": "-e .\nwheel==0.24.0\n\n# Additional requirements go here"
  },
  {
    "path": "runtests.py",
    "chars": 2642,
    "preview": "import sys\n\ntry:\n    from django.conf import settings\n\n    settings.configure(\n        DEBUG=True,\n        USE_TZ=True,\n"
  },
  {
    "path": "setup.cfg",
    "chars": 21,
    "preview": "[wheel]\nuniversal = 1"
  },
  {
    "path": "setup.py",
    "chars": 1544,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport codecs\nimport os\nimport sys\n\nimport users\n\ntry:\n    from setuptool"
  },
  {
    "path": "tests/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "tests/test_admin.py",
    "chars": 2457,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.contrib.admin.sites import AdminSite\nfrom django.contrib.auth "
  },
  {
    "path": "tests/test_fields.py",
    "chars": 4198,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.test import TestCase\nfrom django.test"
  },
  {
    "path": "tests/test_forms.py",
    "chars": 4604,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.contrib.auth import get_user_model\nfrom django.test import Tes"
  },
  {
    "path": "tests/test_managers.py",
    "chars": 1983,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.contrib.auth import get_user_model\nfrom django.test import Tes"
  },
  {
    "path": "tests/test_models.py",
    "chars": 2142,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.contrib.auth import get_user_model\nfrom django.core import mai"
  },
  {
    "path": "tests/test_utils.py",
    "chars": 3483,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom datetime import date, timedelta\n\nfrom django.contrib.auth import get_"
  },
  {
    "path": "tests/test_views.py",
    "chars": 4140,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport re\n\nfrom django.contrib.auth import get_user_model\nfrom django.core"
  },
  {
    "path": "tox.ini",
    "chars": 176,
    "preview": "[tox]\nenvlist = py26, py27, py33\n\n[testenv]\nsetenv =\n    PYTHONPATH = {toxinidir}:{toxinidir}/users\ncommands = python ru"
  },
  {
    "path": "users/__init__.py",
    "chars": 22,
    "preview": "__version__ = '0.2.2'\n"
  },
  {
    "path": "users/admin.py",
    "chars": 3611,
    "preview": "from django.contrib import admin, messages\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django."
  },
  {
    "path": "users/compat.py",
    "chars": 860,
    "preview": "import base64\nfrom binascii import Error as BinasciiError\n\ntry:\n    from django.utils.http import urlsafe_base64_encode\n"
  },
  {
    "path": "users/conf.py",
    "chars": 943,
    "preview": "from appconf import AppConf\nfrom django.conf import settings\n\n\nclass UsersAppConf(AppConf):\n    VERIFY_EMAIL = False\n   "
  },
  {
    "path": "users/fields.py",
    "chars": 4856,
    "preview": "import string\n\nfrom django import forms\nfrom django.core.validators import validate_email\nfrom django.forms.widgets impo"
  },
  {
    "path": "users/forms.py",
    "chars": 3431,
    "preview": "from django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.forms import ReadOnlyPa"
  },
  {
    "path": "users/managers.py",
    "chars": 1994,
    "preview": "from django.contrib.auth.models import BaseUserManager\nfrom django.utils import timezone\n\nfrom model_utils.managers impo"
  },
  {
    "path": "users/migrations/0001_initial.py",
    "chars": 2410,
    "preview": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django."
  },
  {
    "path": "users/migrations/0002_alter_user_last_login_null.py",
    "chars": 430,
    "preview": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migrat"
  },
  {
    "path": "users/migrations/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "users/models.py",
    "chars": 2263,
    "preview": "from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin\nfrom django.contrib.contenttypes.models import"
  },
  {
    "path": "users/signals.py",
    "chars": 230,
    "preview": "from django.dispatch import Signal\n\n# A new user has registered.\nuser_registered = Signal(providing_args=['user', 'reque"
  },
  {
    "path": "users/templates/base.html",
    "chars": 792,
    "preview": "{% load i18n staticfiles %}<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t<meta charset=\"utf-8\">\n\t<title>{% block title %}{{ t"
  },
  {
    "path": "users/templates/users/activate.html",
    "chars": 125,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<p>{% trans \"Account activation failed\" %}</p>\n{% endbloc"
  },
  {
    "path": "users/templates/users/activation_complete.html",
    "chars": 130,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<p>{% trans \"Your account is now activated.\" %}</p>\n{% en"
  },
  {
    "path": "users/templates/users/activation_email.html",
    "chars": 441,
    "preview": "{% load i18n %}\n\n{% trans \"Thank you for registering an account at\" %} {{ site.name }}\n{% trans \"To activate your regist"
  },
  {
    "path": "users/templates/users/activation_email_subject.html",
    "chars": 67,
    "preview": "{% load i18n %}{% trans \"Account activation on\" %} {{ site.name }}\n"
  },
  {
    "path": "users/templates/users/login.html",
    "chars": 661,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<div class=\"form-wrapper\">\n\t<form method=\"post\" action=\"."
  },
  {
    "path": "users/templates/users/logout.html",
    "chars": 110,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<p>{% trans \"Logged out\" %}</p>\n{% endblock %}\n"
  },
  {
    "path": "users/templates/users/partials/errors.html",
    "chars": 155,
    "preview": "{% if form.errors and form.non_field_errors %}\n\t<div class=\"form-errors\">\n\t\t<ul>\n\t\t\t{{ form.non_field_errors|unordered_l"
  },
  {
    "path": "users/templates/users/partials/field.html",
    "chars": 821,
    "preview": "{% load form_tags %}\n\n{% if field.is_hidden %}\n\t{{ field }}\n{% elif field|is_honeypot %}\n\t{% include \"users/partials/hon"
  },
  {
    "path": "users/templates/users/partials/honeypot.html",
    "chars": 667,
    "preview": "{% load form_tags %}\n\n<div class=\"field-wrapper {{ field|input_class }} {{ field.css_classes }}{% if field|is_checkbox %"
  },
  {
    "path": "users/templates/users/password_change_done.html",
    "chars": 116,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<p>{% trans \"Password changed\" %}</p>\n{% endblock %}\n"
  },
  {
    "path": "users/templates/users/password_change_form.html",
    "chars": 454,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<div class=\"form-wrapper\">\n\t<form method=\"post\" action=\"."
  },
  {
    "path": "users/templates/users/password_reset_complete.html",
    "chars": 193,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<p>{% trans \"Password reset successfully\" %}</p>\n<p><a hr"
  },
  {
    "path": "users/templates/users/password_reset_confirm.html",
    "chars": 545,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n{% if validlink %}\n\t<div class=\"form-wrapper\">\n\t\t<form me"
  },
  {
    "path": "users/templates/users/password_reset_done.html",
    "chars": 153,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<p>{% trans \"Email with password reset instructions has b"
  },
  {
    "path": "users/templates/users/password_reset_email.html",
    "chars": 319,
    "preview": "{% load i18n %}\n{% blocktrans %}Reset password at {{ site_name }}{% endblocktrans %}:\n{% block reset_link %}\n<a rel=\"nor"
  },
  {
    "path": "users/templates/users/password_reset_form.html",
    "chars": 445,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<div class=\"form-wrapper\">\n\t<form method=\"post\" action=\"."
  },
  {
    "path": "users/templates/users/password_reset_subject.html",
    "chars": 125,
    "preview": "{% load i18n %}{% autoescape off %}\n{% blocktrans %}Password reset on {{ site_name }}{% endblocktrans %}\n{% endautoescap"
  },
  {
    "path": "users/templates/users/registration_closed.html",
    "chars": 188,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<h1>{% trans \"Sign Up Closed\" %}</h1>\n<p>{% trans \"We are"
  },
  {
    "path": "users/templates/users/registration_complete.html",
    "chars": 145,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<p>{% trans \"You are now registered. Activation email sen"
  },
  {
    "path": "users/templates/users/registration_form.html",
    "chars": 447,
    "preview": "{% extends \"base.html\" %}\n{% load i18n %}\n\n{% block content %}\n<div class=\"form-wrapper\">\n\t<form method=\"post\" action=\"."
  },
  {
    "path": "users/templatetags/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "users/templatetags/form_tags.py",
    "chars": 465,
    "preview": "from django import forms, template\n\nfrom users.fields import HoneyPotField\n\nregister = template.Library()\n\n\n@register.fi"
  },
  {
    "path": "users/urls.py",
    "chars": 2423,
    "preview": "from django.conf.urls import url\nfrom django.contrib.auth import views as auth_views\n\nfrom .views import (activate, acti"
  },
  {
    "path": "users/utils.py",
    "chars": 4763,
    "preview": "from datetime import date\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.mail import EmailMultiAlterna"
  },
  {
    "path": "users/views.py",
    "chars": 6157,
    "preview": "from django.contrib import messages\nfrom django.contrib.auth import get_user_model, login\nfrom django.urls import revers"
  }
]

About this extraction

This page contains the full source code of the mishbahr/django-users2 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 76 files (103.4 KB), approximately 27.1k tokens, and a symbol index with 146 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!