├── .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 /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = 3 | */migrations/* 4 | */compat.py 5 | */__init__.py 6 | */test_* 7 | 8 | [report] 9 | exclude_lines = 10 | def __repr__ 11 | def __str__ 12 | def parse_args 13 | pragma: no cover 14 | raise NotImplementedError 15 | if __name__ == .__main__.: -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | 29 | # Translations 30 | *.mo 31 | 32 | # Mr Developer 33 | .mr.developer.cfg 34 | .project 35 | .pydevproject 36 | 37 | # Complexity 38 | output/*.html 39 | output/*/index.html 40 | 41 | # Sphinx 42 | docs/_build 43 | 44 | #pycharm 45 | .idea/ 46 | 47 | #coverage 48 | htmlcov 49 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "3.5" 7 | - "3.4" 8 | - "2.7" 9 | env: 10 | - DJANGO="Django==1.11.2" 11 | 12 | # command to install dependencies, e.g. pip install -r requirements.txt 13 | install: 14 | - pip install $DJANGO 15 | - pip install -r requirements-test.txt 16 | 17 | # command to run tests using coverage, e.g. python setup.py test 18 | script: coverage run --source users runtests.py 19 | 20 | # report coverage to coveralls.io 21 | after_success: coveralls 22 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Mishbah Razzaque (mishbahr) 9 | 10 | Contributors 11 | ------------ 12 | 13 | * John Matthew (jfmatth) 14 | * moemen 15 | * Alwerdani 16 | * Weizhong Tu (twz915) 17 | * Ahmed Maher (mxahmed) -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/mishbahr/django-users2/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | django-users2 could always use more documentation, whether as part of the 40 | official django-users2 docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/mishbahr/django-users2/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `django-users2` for local development. 59 | 60 | 1. Fork the `django-users2` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-users2.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv django-users2 68 | $ cd django-users2/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the 78 | tests, including testing other Python versions with tox:: 79 | 80 | $ flake8 users tests 81 | $ python setup.py test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check 104 | https://travis-ci.org/mishbahr/django-users2/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ python -m unittest tests.test_users -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.1.0 (2014-09-25) 7 | ++++++++++++++++++ 8 | 9 | * First release on PyPI. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014, Mishbah Razzaque 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * 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. 9 | 10 | * 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. 11 | 12 | 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. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include users *.html *.png *.gif *js *.css *jpg *jpeg *svg *py -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs 2 | 3 | help: 4 | @echo "clean-build - remove build artifacts" 5 | @echo "clean-pyc - remove Python file artifacts" 6 | @echo "lint - check style with flake8" 7 | @echo "test - run tests quickly with the default Python" 8 | @echo "testall - run tests on every Python version with tox" 9 | @echo "coverage - check code coverage quickly with the default Python" 10 | @echo "docs - generate Sphinx HTML documentation, including API docs" 11 | @echo "release - package and upload a release" 12 | @echo "sdist - package" 13 | 14 | clean: clean-build clean-pyc 15 | 16 | clean-build: 17 | rm -fr build/ 18 | rm -fr dist/ 19 | rm -fr *.egg-info 20 | 21 | clean-pyc: 22 | find . -name '*.pyc' -exec rm -f {} + 23 | find . -name '*.pyo' -exec rm -f {} + 24 | find . -name '*~' -exec rm -f {} + 25 | 26 | lint: 27 | flake8 django-users2 tests 28 | 29 | test: 30 | python runtests.py test 31 | 32 | test-all: 33 | tox 34 | 35 | coverage: 36 | coverage run --source django-users2 setup.py test 37 | coverage report -m 38 | coverage html 39 | open htmlcov/index.html 40 | 41 | docs: 42 | rm -f docs/django-users2.rst 43 | rm -f docs/modules.rst 44 | sphinx-apidoc -o docs/ django-users2 45 | $(MAKE) -C docs clean 46 | $(MAKE) -C docs html 47 | open docs/_build/html/index.html 48 | 49 | release: clean 50 | python setup.py sdist upload 51 | python setup.py bdist_wheel upload 52 | 53 | sdist: clean 54 | python setup.py sdist 55 | ls -l dist -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | django-users2 3 | ============================= 4 | 5 | .. image:: http://img.shields.io/travis/mishbahr/django-users2.svg?style=flat-square 6 | :target: https://travis-ci.org/mishbahr/django-users2/ 7 | 8 | .. image:: http://img.shields.io/pypi/v/django-users2.svg?style=flat-square 9 | :target: https://pypi.python.org/pypi/django-users2/ 10 | :alt: Latest Version 11 | 12 | .. image:: http://img.shields.io/pypi/dm/django-users2.svg?style=flat-square 13 | :target: https://pypi.python.org/pypi/django-users2/ 14 | :alt: Downloads 15 | 16 | .. image:: http://img.shields.io/pypi/l/django-users2.svg?style=flat-square 17 | :target: https://pypi.python.org/pypi/django-users2/ 18 | :alt: License 19 | 20 | .. image:: http://img.shields.io/coveralls/mishbahr/django-users2.svg?style=flat-square 21 | :target: https://coveralls.io/r/mishbahr/django-users2?branch=master 22 | 23 | 24 | Custom user model for django >=1.5 with support for multiple user types and 25 | lots of other awesome utils (mostly borrowed from other projects). If you are 26 | using django < 1.11, please install v0.2.1 or earlier (`pip install 27 | django-users2<=0.2.1`). 28 | 29 | Features 30 | -------- 31 | 32 | * email as username for authentication (barebone extendable user models) 33 | * support for multiple user types (using the awesome django-model-utils) 34 | * automatically creates superuser after syncdb/migrations (really handy during the initial development phases) 35 | * built in emails/passwords validators (with lots of customisable options) 36 | * prepackaged with all the templates, including additional templates required by views in ``django.contrib.auth`` (for a painless signup process) 37 | 38 | 39 | Documentation 40 | ------------- 41 | 42 | The full documentation is at https://django-users2.readthedocs.org. 43 | 44 | Quickstart 45 | ---------- 46 | 47 | 1. Install `django-users2`:: 48 | 49 | pip install django-users2 50 | 51 | 2. Add `django-users2` to `INSTALLED_APPS`:: 52 | 53 | INSTALLED_APPS = ( 54 | ... 55 | 'django.contrib.auth', 56 | 'django.contrib.sites', 57 | 'users', 58 | ... 59 | ) 60 | 61 | 3. Set your `AUTH_USER_MODEL` setting to use ``users.User``:: 62 | 63 | AUTH_USER_MODEL = 'users.User' 64 | 65 | 4. Once you’ve done this, run the ``migrate`` command to install the model used by this package:: 66 | 67 | python manage.py migrate 68 | 69 | 5. Add the `django-users2` URLs to your project’s URLconf as follows:: 70 | 71 | urlpatterns = patterns('', 72 | ... 73 | url(r'^accounts/', include('users.urls')), 74 | ... 75 | ) 76 | 77 | 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) 78 | 79 | 80 | Configuration 81 | ----------------------- 82 | Set ``USERS_VERIFY_EMAIL = True`` to enable email verification for registered users. 83 | 84 | 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:: 85 | 86 | USERS_VERIFY_EMAIL = False 87 | 88 | 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:: 89 | 90 | USERS_AUTO_LOGIN_ON_ACTIVATION = True 91 | 92 | This is the number of days the users will have, to activate their accounts after registering:: 93 | 94 | USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS = 3 95 | 96 | Automatically create django ``superuser`` after ``syncdb``, by default this option is enabled when ``settings.DEBUG = True``. 97 | 98 | You can customise the email/password by overriding ``USERS_SUPERUSER_EMAIL`` and ``USERS_SUPERUSER_PASSWORD`` settings (highly recommended):: 99 | 100 | USERS_CREATE_SUPERUSER = settings.DEBUG 101 | USERS_SUPERUSER_EMAIL = 'superuser@djangoproject.com' 102 | USERS_SUPERUSER_PASSWORD = 'django' 103 | 104 | Prevent automated registration by spambots, by enabling a hidden (using css) honeypot field:: 105 | 106 | USERS_SPAM_PROTECTION = True 107 | 108 | Prevent user registrations by setting ``USERS_REGISTRATION_OPEN = False``:: 109 | 110 | USERS_REGISTRATION_OPEN = True 111 | 112 | 113 | Settings for validators, that check the strength of user specified passwords:: 114 | 115 | # Specifies minimum length for passwords: 116 | USERS_PASSWORD_MIN_LENGTH = 5 117 | 118 | #Specifies maximum length for passwords: 119 | USERS_PASSWORD_MAX_LENGTH = None 120 | 121 | Optionally, the complexity validator, checks the password strength:: 122 | 123 | USERS_CHECK_PASSWORD_COMPLEXITY = True 124 | 125 | Specify number of characters within various sets that a password must contain:: 126 | 127 | USERS_PASSWORD_POLICY = { 128 | 'UPPER': 0, # Uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 129 | 'LOWER': 0, # Lowercase 'abcdefghijklmnopqrstuvwxyz' 130 | 'DIGITS': 0, # Digits '0123456789' 131 | 'PUNCTUATION': 0 # Punctuation """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" 132 | } 133 | 134 | Allow/disallow registration using emails addresses from specific domains:: 135 | 136 | USERS_VALIDATE_EMAIL_DOMAIN = True 137 | 138 | List of disallowed domains:: 139 | 140 | USERS_EMAIL_DOMAINS_BLACKLIST = [] 141 | 142 | For example, ``USERS_EMAIL_DOMAINS_BLACKLIST = ['mailinator.com']`` will block all visitors from using mailinator.com email addresses to register. 143 | 144 | List of allowed domains:: 145 | 146 | USERS_EMAIL_DOMAINS_WHITELIST = [] 147 | 148 | For example, ``USERS_EMAIL_DOMAINS_WHITELIST = ['ljworld.com']`` will only allow user registration with ljworld.com domains. 149 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(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/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # complexity documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | import users 26 | 27 | # -- General configuration ----------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be extensions 33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'django-users2' 50 | copyright = u'2014, Mishbah Razzaque' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = users.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = users.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output --------------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'default' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ['_static'] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'django-users2doc' 177 | 178 | 179 | # -- Options for LaTeX output -------------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, author, documentclass [howto/manual]). 194 | latex_documents = [ 195 | ('index', 'django-users2.tex', u'django-users2 Documentation', 196 | u'Mishbah Razzaque', 'manual'), 197 | ] 198 | 199 | # The name of an image file (relative to this directory) to place at the top of 200 | # the title page. 201 | #latex_logo = None 202 | 203 | # For "manual" documents, if this is true, then toplevel headings are parts, 204 | # not chapters. 205 | #latex_use_parts = False 206 | 207 | # If true, show page references after internal links. 208 | #latex_show_pagerefs = False 209 | 210 | # If true, show URL addresses after external links. 211 | #latex_show_urls = False 212 | 213 | # Documents to append as an appendix to all manuals. 214 | #latex_appendices = [] 215 | 216 | # If false, no module index is generated. 217 | #latex_domain_indices = True 218 | 219 | 220 | # -- Options for manual page output -------------------------------------------- 221 | 222 | # One entry per manual page. List of tuples 223 | # (source start file, name, description, authors, manual section). 224 | man_pages = [ 225 | ('index', 'django-users2', u'django-users2 Documentation', 226 | [u'Mishbah Razzaque'], 1) 227 | ] 228 | 229 | # If true, show URL addresses after external links. 230 | #man_show_urls = False 231 | 232 | 233 | # -- Options for Texinfo output ------------------------------------------------ 234 | 235 | # Grouping the document tree into Texinfo files. List of tuples 236 | # (source start file, target name, title, author, 237 | # dir menu entry, description, category) 238 | texinfo_documents = [ 239 | ('index', 'django-users2', u'django-users2 Documentation', 240 | u'Mishbah Razzaque', 'django-users2', 'One line description of project.', 241 | 'Miscellaneous'), 242 | ] 243 | 244 | # Documents to append as an appendix to all manuals. 245 | #texinfo_appendices = [] 246 | 247 | # If false, no module index is generated. 248 | #texinfo_domain_indices = True 249 | 250 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 251 | #texinfo_show_urls = 'footnote' 252 | 253 | # If true, do not generate a @detailmenu in the "Top" node's menu. 254 | #texinfo_no_detailmenu = False -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. complexity documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to django-users2's documentation! 7 | ================================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ easy_install django-users2 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv django-users2 12 | $ pip install django-users2 -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | To use django-users2 in a project:: 6 | 7 | import django-users2 -------------------------------------------------------------------------------- /example/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'mishbah' 2 | -------------------------------------------------------------------------------- /example/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | from django.conf import settings 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('users', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='Customer', 17 | fields=[ 18 | ('user_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), 19 | ('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)), 20 | ('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)), 21 | ], 22 | options={ 23 | 'verbose_name': 'Customer', 24 | 'verbose_name_plural': 'Customers', 25 | }, 26 | bases=('users.user',), 27 | ), 28 | ] 29 | -------------------------------------------------------------------------------- /example/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mishbahr/django-users2/1ee244dc4ca162b2331d2a44d45848fdcb80f329/example/migrations/__init__.py -------------------------------------------------------------------------------- /example/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.utils.translation import ugettext_lazy as _ 3 | 4 | from users.models import User 5 | 6 | 7 | class Customer(User): 8 | first_name = models.CharField(_('first name'), max_length=30, blank=True) 9 | last_name = models.CharField(_('last name'), max_length=30, blank=True) 10 | 11 | class Meta: 12 | verbose_name = _('Customer') 13 | verbose_name_plural = _('Customers') 14 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | 3 | coverage 4 | coveralls 5 | mock>=1.0.1 6 | nose>=1.3.0 7 | django-nose>=1.2 8 | flake8>=2.1.0 9 | tox>=1.7.0 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | wheel==0.24.0 3 | 4 | # Additional requirements go here -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | try: 4 | from django.conf import settings 5 | 6 | settings.configure( 7 | DEBUG=True, 8 | USE_TZ=True, 9 | DATABASES={ 10 | 'default': { 11 | 'ENGINE': 'django.db.backends.sqlite3', 12 | 'NAME': 'django_users2', 13 | } 14 | }, 15 | ROOT_URLCONF='users.urls', 16 | INSTALLED_APPS=[ 17 | 'django.contrib.auth', 18 | 'django.contrib.sessions', 19 | 'django.contrib.contenttypes', 20 | 'django.contrib.sites', 21 | 'django.contrib.staticfiles', 22 | 'django.contrib.messages', 23 | 'users', 24 | 'example', # used for testing user model subclasses 25 | ], 26 | MIDDLEWARE_CLASSES=( 27 | 'django.middleware.common.CommonMiddleware', 28 | 'django.contrib.sessions.middleware.SessionMiddleware', 29 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 30 | 'django.contrib.messages.middleware.MessageMiddleware', 31 | ), 32 | PASSWORD_HASHERS=( 33 | 'django.contrib.auth.hashers.SHA1PasswordHasher', 34 | ), 35 | SITE_ID=1, 36 | NOSE_ARGS=['-s'], 37 | AUTH_USER_MODEL='users.User', 38 | USERS_CREATE_SUPERUSER=False, 39 | TEMPLATES = [ 40 | { 41 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 42 | 'DIRS': [], 43 | 'APP_DIRS': True, 44 | 'OPTIONS': { 45 | 'context_processors': [ 46 | 'django.contrib.auth.context_processors.auth', 47 | 'django.template.context_processors.debug', 48 | 'django.template.context_processors.i18n', 49 | 'django.template.context_processors.media', 50 | 'django.template.context_processors.static', 51 | 'django.template.context_processors.tz', 52 | 'django.contrib.messages.context_processors.messages', 53 | ], 54 | }, 55 | }, 56 | ] 57 | ) 58 | 59 | try: 60 | import django 61 | setup = django.setup 62 | except AttributeError: 63 | pass 64 | else: 65 | setup() 66 | 67 | from django_nose import NoseTestSuiteRunner 68 | except ImportError: 69 | import traceback 70 | traceback.print_exc() 71 | raise ImportError('To fix this error, run: pip install -r requirements-test.txt') 72 | 73 | 74 | def run_tests(*test_args): 75 | if not test_args: 76 | test_args = ['tests'] 77 | 78 | # Run tests 79 | test_runner = NoseTestSuiteRunner(verbosity=1) 80 | 81 | failures = test_runner.run_tests(test_args) 82 | 83 | if failures: 84 | sys.exit(failures) 85 | 86 | 87 | if __name__ == '__main__': 88 | run_tests(*sys.argv[1:]) 89 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import codecs 5 | import os 6 | import sys 7 | 8 | import users 9 | 10 | try: 11 | from setuptools import setup 12 | except ImportError: 13 | from distutils.core import setup 14 | 15 | version = users.__version__ 16 | 17 | if sys.argv[-1] == 'publish': 18 | os.system('python setup.py sdist upload') 19 | print("You probably want to also tag the version now:") 20 | print(" git tag -a %s -m 'version %s'" % (version, version)) 21 | print(" git push --tags") 22 | sys.exit() 23 | 24 | readme = codecs.open('README.rst', 'r', 'utf-8').read() 25 | 26 | setup( 27 | name='django-users2', 28 | version=version, 29 | description="""Custom user model for django >=1.11 with support for multiple user types""", 30 | long_description=readme, 31 | author='Mishbah Razzaque', 32 | author_email='mishbahx@gmail.com', 33 | url='https://github.com/mishbahr/django-users2', 34 | packages=[ 35 | 'users', 36 | ], 37 | include_package_data=True, 38 | install_requires=[ 39 | 'django>=1.11', 40 | 'django-model-utils', 41 | 'django-appconf', 42 | ], 43 | license="BSD", 44 | zip_safe=False, 45 | keywords='django-users2', 46 | classifiers=[ 47 | 'Development Status :: 4 - Beta', 48 | 'Framework :: Django', 49 | 'Framework :: Django :: 1.11', 50 | 'Intended Audience :: Developers', 51 | 'License :: OSI Approved :: BSD License', 52 | 'Natural Language :: English', 53 | 'Programming Language :: Python :: 2.7', 54 | 'Programming Language :: Python :: 3', 55 | 'Programming Language :: Python :: 3.4', 56 | 'Programming Language :: Python :: 3.5', 57 | ], 58 | ) 59 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mishbahr/django-users2/1ee244dc4ca162b2331d2a44d45848fdcb80f329/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_admin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from django.contrib.admin.sites import AdminSite 4 | from django.contrib.auth import get_user_model 5 | from django.contrib.messages.storage.fallback import FallbackStorage 6 | from django.core import mail 7 | from django.test import TestCase 8 | from django.test.client import RequestFactory 9 | from django.test.utils import override_settings 10 | 11 | from users.admin import UserAdmin 12 | 13 | 14 | class AdminTest(TestCase): 15 | 16 | user_email = 'user@example.com' 17 | user_password = 'pa$sw0Rd' 18 | 19 | def setUp(self): 20 | get_user_model().objects.create_superuser(self.user_email, self.user_password) 21 | 22 | self.assertTrue(self.client.login( 23 | username=self.user_email, password=self.user_password), 24 | 'Failed to login user %s' % self.user_email) 25 | 26 | get_user_model().objects.create_user('user1@example.com', 'pa$sw0Rd1', is_active=False) 27 | 28 | factory = RequestFactory() 29 | self.request = factory.get('/admin') 30 | 31 | # Hack to test this function as it calls 'messages.add' 32 | # See https://code.djangoproject.com/ticket/17971 33 | setattr(self.request, 'session', 'session') 34 | messages = FallbackStorage(self.request) 35 | setattr(self.request, '_messages', messages) 36 | 37 | def test_get_queryset(self): 38 | user_admin = UserAdmin(get_user_model(), AdminSite()) 39 | self.assertQuerysetEqual( 40 | user_admin.get_queryset(self.request), 41 | ['', ''], ordered=False) 42 | 43 | @override_settings(USERS_VERIFY_EMAIL=True) 44 | def test_send_activation_email(self): 45 | user_admin = UserAdmin(get_user_model(), AdminSite()) 46 | 47 | qs = get_user_model().objects.all() 48 | user_admin.send_activation_email(self.request, qs) 49 | # we created 1 inactive user, so there should be one email in outbox 50 | self.assertEqual(len(mail.outbox), 1) 51 | 52 | def test_activate_users(self): 53 | user_admin = UserAdmin(get_user_model(), AdminSite()) 54 | 55 | qs = get_user_model().objects.all() 56 | user_admin.activate_users(self.request, qs) 57 | # both users should be active 58 | self.assertEqual(get_user_model().objects.filter(is_active=True).count(), 2) 59 | # superuser is automatically activated. so we test the attribute for user1@example.com 60 | user = get_user_model().objects.get(email='user1@example.com') 61 | self.assertTrue(user.is_active) 62 | 63 | def tearDown(self): 64 | self.client.logout() 65 | -------------------------------------------------------------------------------- /tests/test_fields.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from django import forms 4 | from django.test import TestCase 5 | from django.test.utils import override_settings 6 | 7 | from users.fields import (ComplexityValidator, EmailDomainValidator, 8 | LengthValidator) 9 | 10 | 11 | class LengthValidatorTest(TestCase): 12 | 13 | @override_settings(USERS_PASSWORD_MIN_LENGTH=6, USERS_PASSWORD_MAX_LENGTH=20) 14 | def setUp(self): 15 | self.length_validator = LengthValidator() 16 | 17 | def test_password_length_validator_min_length(self): 18 | value = 'abc' 19 | try: 20 | self.length_validator(value) 21 | except forms.ValidationError: 22 | pass 23 | else: 24 | self.fail('ValidationError not raised when validating \'%s\'' % value) 25 | 26 | def test_password_length_validator_max_length(self): 27 | value = 'qwertyuiopasdfghjklzxcvbnm' 28 | try: 29 | self.length_validator(value) 30 | except forms.ValidationError: 31 | pass 32 | else: 33 | self.fail('ValidationError not raised when validating \'%s\'' % value) 34 | 35 | 36 | class ComplexityValidatorTest(TestCase): 37 | password_policy = { 38 | 'UPPER': 1, 39 | 'LOWER': 1, 40 | 'DIGITS': 1, 41 | 'PUNCTUATION': 1 42 | } 43 | 44 | @override_settings(USERS_PASSWORD_POLICY={'UPPER': 1}) 45 | def test_complexity_validator_fails_no_uppercase(self): 46 | complexity_validator = ComplexityValidator() 47 | value = 'password' 48 | try: 49 | complexity_validator(value) 50 | except forms.ValidationError: 51 | pass 52 | else: 53 | self.fail('ValidationError not raised when validating \'%s\'' % value) 54 | 55 | @override_settings(USERS_PASSWORD_POLICY={'LOWER': 1}) 56 | def test_complexity_validator_fails_no_lowercase(self): 57 | complexity_validator = ComplexityValidator() 58 | value = 'PASSWORD' 59 | try: 60 | complexity_validator(value) 61 | except forms.ValidationError: 62 | pass 63 | else: 64 | self.fail('ValidationError not raised when validating \'%s\'' % value) 65 | 66 | @override_settings(USERS_PASSWORD_POLICY={'DIGITS': 1}) 67 | def test_complexity_validator_fails_no_digit(self): 68 | complexity_validator = ComplexityValidator() 69 | value = 'password' 70 | try: 71 | complexity_validator(value) 72 | except forms.ValidationError: 73 | pass 74 | else: 75 | self.fail('ValidationError not raised when validating \'%s\'' % value) 76 | 77 | @override_settings(USERS_PASSWORD_POLICY={'PUNCTUATION': 1}) 78 | def test_complexity_validator_fails_no_symbol(self): 79 | complexity_validator = ComplexityValidator() 80 | value = 'password' 81 | try: 82 | complexity_validator(value) 83 | except forms.ValidationError: 84 | pass 85 | else: 86 | self.fail('ValidationError not raised when validating \'%s\'' % value) 87 | 88 | @override_settings(USERS_PASSWORD_POLICY=password_policy) 89 | def test_complexity_validator_success(self): 90 | complexity_validator = ComplexityValidator() 91 | value = 'Pas$word1' 92 | try: 93 | complexity_validator(value) 94 | except forms.ValidationError: 95 | self.fail('ValidationError raised when validating \'%s\'' % value) 96 | 97 | 98 | class EmailDomainValidatorTest(TestCase): 99 | domains_blacklist = ('mailinator.com', ) 100 | domains_whitelist = ('djangoproject.com', ) 101 | 102 | @override_settings(USERS_EMAIL_DOMAINS_WHITELIST=domains_whitelist) 103 | def test_email_domain_validator_with_white_list(self): 104 | email_domain_validator = EmailDomainValidator() 105 | value = 'user@example.com' 106 | try: 107 | email_domain_validator(value) 108 | except forms.ValidationError: 109 | pass 110 | else: 111 | self.fail('ValidationError not raised when validating \'%s\'' % value) 112 | 113 | @override_settings(USERS_EMAIL_DOMAINS_BLACKLIST=domains_blacklist) 114 | def test_email_domain_validator_with_black_list(self): 115 | email_domain_validator = EmailDomainValidator() 116 | value = 'spammer@mailinator.com' 117 | try: 118 | email_domain_validator(value) 119 | except forms.ValidationError: 120 | pass 121 | else: 122 | self.fail('ValidationError not raised when validating \'%s\'' % value) 123 | -------------------------------------------------------------------------------- /tests/test_forms.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from django.contrib.auth import get_user_model 4 | from django.test import TestCase 5 | from django.utils.encoding import force_text 6 | from django.utils.translation import ugettext as _ 7 | 8 | from users.forms import (RegistrationFormHoneypot, 9 | RegistrationFormTermsOfService, UserChangeForm, 10 | UserCreationForm) 11 | 12 | 13 | class UserCreationFormTest(TestCase): 14 | 15 | def test_user_already_exists(self): 16 | get_user_model().objects.create_user('testuser@example.com', 'Pa$sw0rd') 17 | 18 | data = { 19 | 'email': 'testuser@example.com', 20 | 'password1': 'Pa$sw0rd', 21 | 'password2': 'Pa$sw0rd', 22 | } 23 | form = UserCreationForm(data) 24 | self.assertFalse(form.is_valid()) 25 | self.assertEqual(form['email'].errors, 26 | [force_text(form.error_messages['duplicate_email'])]) 27 | 28 | def test_invalid_email(self): 29 | data = { 30 | 'email': 'testuser', 31 | 'password1': 'Pa$sw0rd', 32 | 'password2': 'Pa$sw0rd', 33 | } 34 | form = UserCreationForm(data) 35 | self.assertFalse(form.is_valid()) 36 | self.assertIn(_('Enter a valid email address.'), form['email'].errors) 37 | 38 | def test_password_verification(self): 39 | # The verification password is incorrect. 40 | data = { 41 | 'email': 'testuser@example.com', 42 | 'password1': 'Pa$sw0rd1', 43 | 'password2': 'Pa$sw0rd2', 44 | } 45 | form = UserCreationForm(data) 46 | self.assertFalse(form.is_valid()) 47 | self.assertEqual(form['password2'].errors, 48 | [force_text(form.error_messages['password_mismatch'])]) 49 | 50 | def test_password_is_not_saved_raw(self): 51 | raw_password = 'Pa$sw0rd2' 52 | data = { 53 | 'email': 'testuser@example.com', 54 | 'password1': raw_password, 55 | 'password2': raw_password, 56 | } 57 | form = UserCreationForm(data) 58 | user = form.save() 59 | self.assertNotEqual(raw_password, user.password) 60 | 61 | def test_valid_user_are_saved(self): 62 | data = { 63 | 'email': 'validuser@example.com', 64 | 'password1': 'Pa$sw0rd', 65 | 'password2': 'Pa$sw0rd', 66 | } 67 | form = UserCreationForm(data) 68 | self.assertTrue(form.is_valid()) 69 | user = form.save() 70 | self.assertEqual(repr(user), '<%s: validuser@example.com>' % get_user_model().__name__) 71 | 72 | 73 | class UserChangeFormTest(TestCase): 74 | 75 | def test_username_validity(self): 76 | user = get_user_model().objects.create_user('testuser@example.com', 'Pa$sw0rd') 77 | data = { 78 | 'email': 'invalid-email' 79 | } 80 | form = UserChangeForm(data, instance=user) 81 | self.assertFalse(form.is_valid()) 82 | self.assertIn(_('Enter a valid email address.'), form['email'].errors) 83 | 84 | def test_unsuable_password(self): 85 | user = get_user_model().objects.create_user('testuser@example.com', 'Pa$sw0rd') 86 | user.set_unusable_password() 87 | user.save() 88 | form = UserChangeForm(instance=user) 89 | self.assertIn(_('No password set.'), form.as_table()) 90 | 91 | 92 | class RegistrationFormTermsOfServiceTest(TestCase): 93 | 94 | def test_registration_form_with_tos_checkbox_validates(self): 95 | data = { 96 | 'email': 'testuser@example.com', 97 | 'password1': 'Pa$sw0rd', 98 | 'password2': 'Pa$sw0rd', 99 | 'tos': True 100 | } 101 | form = RegistrationFormTermsOfService(data=data) 102 | self.assertTrue(form.is_valid()) 103 | 104 | def test_registration_form_with_tos_checkbox_fails(self): 105 | data = { 106 | 'email': 'testuser@example.com', 107 | 'password1': 'Pa$sw0rd', 108 | 'password2': 'Pa$sw0rd', 109 | } 110 | form = RegistrationFormTermsOfService(data=data) 111 | self.assertFalse(form.is_valid()) 112 | self.assertEqual(form.errors['tos'], [u'You must agree to the terms to register']) 113 | 114 | 115 | class RegistrationFormHoneypotTest(TestCase): 116 | def test_registration_form_with_honeypot_field(self): 117 | data = { 118 | 'email': 'testuser@example.com', 119 | 'password1': 'Pa$sw0rd', 120 | 'password2': 'Pa$sw0rd', 121 | } 122 | form = RegistrationFormHoneypot(data=data) 123 | self.assertTrue(form.is_valid()) 124 | 125 | def test_registration_form_with_honeypot_field_fails_as_expected(self): 126 | data = { 127 | 'email': 'testuser@example.com', 128 | 'password1': 'Pa$sw0rd', 129 | 'password2': 'Pa$sw0rd', 130 | 'accept_terms': True 131 | } 132 | form = RegistrationFormHoneypot(data=data) 133 | self.assertFalse(form.is_valid()) 134 | -------------------------------------------------------------------------------- /tests/test_managers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from django.contrib.auth import get_user_model 4 | from django.test import TestCase 5 | 6 | from example.models import Customer 7 | 8 | 9 | class UserManagerTest(TestCase): 10 | 11 | user_email = 'user@example.com' 12 | user_password = 'pa$sw0Rd' 13 | 14 | def test_create_user(self): 15 | user = get_user_model().objects.create_user(self.user_email) 16 | self.assertEqual(user.email, self.user_email) 17 | self.assertFalse(user.has_usable_password()) 18 | self.assertTrue(user.is_active) 19 | self.assertFalse(user.is_staff) 20 | self.assertFalse(user.is_superuser) 21 | 22 | def test_create_superuser(self): 23 | user = get_user_model().objects.create_superuser( 24 | self.user_email, self.user_password) 25 | 26 | self.assertEqual(user.email, self.user_email) 27 | self.assertTrue(user.check_password, self.user_password) 28 | self.assertTrue(user.is_active) 29 | self.assertTrue(user.is_staff) 30 | self.assertTrue(user.is_superuser) 31 | 32 | def test_inactive_user_creation(self): 33 | # Create deactivated user 34 | user = get_user_model().objects.create_user( 35 | self.user_email, self.user_password, is_active=False) 36 | self.assertFalse(user.is_active) 37 | 38 | def test_staff_user_creation(self): 39 | # Create staff user 40 | user = get_user_model().objects.create_user( 41 | self.user_email, self.user_password, is_staff=True) 42 | self.assertTrue(user.is_staff) 43 | 44 | def test_empty_username(self): 45 | self.assertRaises(ValueError, get_user_model().objects.create_user, email='') 46 | 47 | def test_automatic_downcasting_of_inherited_user_models(self): 48 | get_user_model().objects.create_superuser( 49 | self.user_email, self.user_password) 50 | Customer.objects.create_user('customer@example.com', 'cu$t0meR') 51 | self.assertQuerysetEqual( 52 | get_user_model().objects.all(), 53 | ['', ''], ordered=False) 54 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from django.contrib.auth import get_user_model 4 | from django.core import mail 5 | from django.test import TestCase 6 | 7 | 8 | class TestUsersModels(TestCase): 9 | 10 | user_email = 'user@example.com' 11 | user_password = 'pa$sw0Rd' 12 | 13 | def create_user(self): 14 | return get_user_model().objects.create_user(self.user_email, self.user_password) 15 | 16 | def test_user_creation(self): 17 | user = self.create_user() 18 | 19 | self.assertEqual(get_user_model().objects.all().count(), 1) 20 | self.assertEqual(user.email, self.user_email) 21 | 22 | self.assertTrue(user.is_active) 23 | self.assertFalse(user.is_staff) 24 | self.assertFalse(user.is_superuser) 25 | 26 | def test_user_get_full_name(self): 27 | user = self.create_user() 28 | self.assertEqual(user.get_full_name(), self.user_email) 29 | 30 | def test_user_get_short_name(self): 31 | user = self.create_user() 32 | self.assertEqual(user.get_short_name(), self.user_email) 33 | 34 | def test_email_user(self): 35 | # Email definition 36 | subject = 'email subject' 37 | message = 'email message' 38 | from_email = 'from@example.com' 39 | 40 | user = self.create_user() 41 | 42 | # Test that no message exists 43 | self.assertEqual(len(mail.outbox), 0) 44 | 45 | # Send test email 46 | user.email_user(subject, message, from_email) 47 | 48 | # Test that one message has been sent 49 | self.assertEqual(len(mail.outbox), 1) 50 | 51 | # Verify that the email is correct 52 | self.assertEqual(mail.outbox[0].subject, subject) 53 | self.assertEqual(mail.outbox[0].body, message) 54 | self.assertEqual(mail.outbox[0].from_email, from_email) 55 | self.assertEqual(mail.outbox[0].to, [user.email]) 56 | 57 | def test_user_activation(self): 58 | user = get_user_model().objects.create_user( 59 | self.user_email, self.user_password, is_active=False) 60 | # check user is not active by default 61 | self.assertFalse(user.is_active) 62 | # activate user 63 | user.activate() 64 | self.assertTrue(user.is_active) 65 | 66 | def test_(self): 67 | user = self.create_user() 68 | self.assertIsNotNone(user.user_type) 69 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from datetime import date, timedelta 4 | 5 | from django.contrib.auth import get_user_model 6 | from django.core import mail 7 | from django.core.urlresolvers import reverse 8 | from django.test import TestCase 9 | from django.test.client import RequestFactory 10 | from django.test.utils import override_settings 11 | 12 | from users.conf import settings 13 | from users.utils import (auto_create_superuser, EmailActivationTokenGenerator, 14 | send_activation_email) 15 | 16 | 17 | class CreateSuperuserTest(TestCase): 18 | 19 | user_email = 'user@example.com' 20 | user_password = 'pa$sw0Rd' 21 | 22 | @override_settings(USERS_CREATE_SUPERUSER=True, 23 | USERS_SUPERUSER_EMAIL=user_email, 24 | USERS_SUPERUSER_PASSWORD=user_password) 25 | def test_auto_create_superuser(self): 26 | auto_create_superuser(sender=None) 27 | 28 | user = get_user_model().objects.get(email=self.user_email) 29 | 30 | self.assertTrue(user.is_active) 31 | self.assertTrue(user.is_staff) 32 | self.assertTrue(user.is_superuser) 33 | 34 | 35 | class SendActivationEmailTest(TestCase): 36 | 37 | user_email = 'user@example.com' 38 | user_password = 'pa$sw0Rd' 39 | 40 | @override_settings(USERS_VERIFY_EMAIL=True) 41 | def test_send_activation_email(self): 42 | factory = RequestFactory() 43 | request = factory.get(reverse('users_register')) 44 | user = get_user_model().objects.create_user( 45 | self.user_email, self.user_password, is_active=False) 46 | 47 | send_activation_email(user=user, request=request) 48 | self.assertEqual(len(mail.outbox), 1) 49 | 50 | 51 | class EmailActivationTokenGeneratorTest(TestCase): 52 | user_email = 'user@example.com' 53 | user_password = 'pa$sw0Rd' 54 | 55 | def create_user(self): 56 | return get_user_model().objects.create_user(self.user_email, self.user_password) 57 | 58 | def test_make_token(self): 59 | """ 60 | Ensure that we can make a token and that it is valid 61 | """ 62 | user = self.create_user() 63 | 64 | token_generator = EmailActivationTokenGenerator() 65 | token = token_generator.make_token(user) 66 | self.assertTrue(token_generator.check_token(user, token)) 67 | 68 | def test_bad_token(self): 69 | """ 70 | Ensure bad activation keys are rejected 71 | """ 72 | user = self.create_user() 73 | 74 | token_generator = EmailActivationTokenGenerator() 75 | bad_activation_keys = ( 76 | 'emailactivationtokengenerator', 77 | 'emailactivation-tokengenerator', 78 | '3rd-bademailactivationkey' 79 | ) 80 | for key in bad_activation_keys: 81 | self.assertFalse(token_generator.check_token(user, key)) 82 | 83 | def test_timeout(self): 84 | """ 85 | Ensure we can use the token after n days, but no greater. 86 | """ 87 | # Uses a mocked version of EmailActivationTokenGenerator 88 | # so we can change the value of 'today' 89 | class Mocked(EmailActivationTokenGenerator): 90 | def __init__(self, today): 91 | self._today_val = today 92 | 93 | def _today(self): 94 | return self._today_val 95 | 96 | user = self.create_user() 97 | token_generator = EmailActivationTokenGenerator() 98 | token = token_generator.make_token(user) 99 | 100 | p1 = Mocked(date.today() + timedelta(settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS)) 101 | self.assertTrue(p1.check_token(user, token)) 102 | 103 | p2 = Mocked(date.today() + timedelta(settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS + 1)) 104 | self.assertFalse(p2.check_token(user, token)) 105 | -------------------------------------------------------------------------------- /tests/test_views.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import re 4 | 5 | from django.contrib.auth import get_user_model 6 | from django.core import mail 7 | from django.core.urlresolvers import reverse 8 | from django.test import TestCase 9 | from django.test.utils import override_settings 10 | 11 | from users.forms import RegistrationForm, RegistrationFormHoneypot 12 | 13 | 14 | class RegisterViewTest(TestCase): 15 | user_data = { 16 | 'email': 'user@example.com', 17 | 'password1': 'pa$sw0Rd', 18 | 'password2': 'pa$sw0Rd' 19 | } 20 | 21 | @override_settings(USERS_REGISTRATION_OPEN=True) 22 | def test_registration_allowed(self): 23 | resp = self.client.get(reverse('users_register')) 24 | self.assertEqual(200, resp.status_code) 25 | 26 | @override_settings(USERS_REGISTRATION_OPEN=False) 27 | def test_registration_closed(self): 28 | resp = self.client.get(reverse('users_register')) 29 | self.assertRedirects(resp, reverse('users_registration_closed')) 30 | 31 | @override_settings(USERS_SPAM_PROTECTION=False) 32 | def test_registration_form(self): 33 | resp = self.client.get(reverse('users_register')) 34 | self.assertEqual(200, resp.status_code) 35 | self.failUnless(isinstance(resp.context['form'], RegistrationForm)) 36 | 37 | @override_settings(USERS_SPAM_PROTECTION=True) 38 | def test_registration_form_with_honeypot(self): 39 | resp = self.client.get(reverse('users_register')) 40 | self.assertEqual(200, resp.status_code) 41 | self.failUnless(isinstance(resp.context['form'], RegistrationFormHoneypot)) 42 | 43 | def test_registration(self): 44 | resp = self.client.post(reverse('users_register'), self.user_data) 45 | self.assertRedirects(resp, reverse('users_registration_complete')) 46 | 47 | def test_registration_created_new_user(self): 48 | resp = self.client.post(reverse('users_register'), self.user_data) 49 | self.assertEqual(get_user_model().objects.all().count(), 1) 50 | 51 | @override_settings(LOGIN_REDIRECT_URL=reverse('users_registration_complete')) 52 | def test_authenticated_users_are_redirected(self): 53 | user = get_user_model().objects.create_user( 54 | self.user_data['email'], self.user_data['password1'], is_active=True) 55 | login = self.client.login( 56 | username=self.user_data['email'], 57 | password=self.user_data['password1']) 58 | self.assertEqual(login, True) 59 | resp = self.client.post(reverse('users_register'), self.user_data) 60 | self.assertRedirects(resp, reverse('users_registration_complete')) 61 | 62 | @override_settings(USERS_VERIFY_EMAIL=True) 63 | def test_registered_user_is_not_active(self): 64 | resp = self.client.post(reverse('users_register'), self.user_data) 65 | new_user = get_user_model().objects.get(email=self.user_data['email']) 66 | self.failIf(new_user.is_active) 67 | 68 | @override_settings(USERS_VERIFY_EMAIL=True) 69 | def test_activation_email_was_sent(self): 70 | resp = self.client.post(reverse('users_register'), self.user_data) 71 | self.assertEqual(len(mail.outbox), 1) 72 | 73 | 74 | class ActivationViewTest(TestCase): 75 | user_data = { 76 | 'email': 'user@example.com', 77 | 'password1': 'pa$sw0Rd', 78 | 'password2': 'pa$sw0Rd' 79 | } 80 | 81 | @override_settings(USERS_VERIFY_EMAIL=True) 82 | def test_activation_view(self): 83 | self.client.post(reverse('users_register'), self.user_data) 84 | activation_email = mail.outbox[0] 85 | urlmatch = re.search(r'https?://[^/]*(/.*activate/\S*)', activation_email.body) 86 | self.assertTrue(urlmatch is not None, 'No URL found in sent email') 87 | resp = self.client.get(urlmatch.groups()[0]) 88 | self.assertRedirects(resp, reverse('users_activation_complete')) 89 | 90 | new_user = get_user_model().objects.get(email=self.user_data['email']) 91 | self.assertTrue(new_user.is_active) 92 | 93 | @override_settings(USERS_VERIFY_EMAIL=True) 94 | def test_activation_view_fails_as_expected(self): 95 | url = reverse('users_activate', kwargs={ 96 | 'uidb64': 'MQ', 97 | 'token': 'bad-69b5cdcd57c6854d1b04' 98 | }) 99 | resp = self.client.get(url) 100 | self.assertEqual(200, resp.status_code) 101 | self.failUnless(resp.context['title'], 'Email confirmation unsuccessful') 102 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py26, py27, py33 3 | 4 | [testenv] 5 | setenv = 6 | PYTHONPATH = {toxinidir}:{toxinidir}/users 7 | commands = python runtests.py 8 | deps = 9 | -r{toxinidir}/requirements-test.txt -------------------------------------------------------------------------------- /users/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.2.2' 2 | -------------------------------------------------------------------------------- /users/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin, messages 2 | from django.contrib.auth.admin import UserAdmin as BaseUserAdmin 3 | from django.utils.translation import ugettext_lazy as _ 4 | 5 | from .conf import settings 6 | from .forms import UserChangeForm, UserCreationForm 7 | from .models import User 8 | from .utils import send_activation_email 9 | 10 | try: 11 | from django.contrib.admin.utils import model_ngettext 12 | except ImportError: # pragma: no cover 13 | from django.contrib.admin.util import model_ngettext 14 | 15 | 16 | class UserModelFilter(admin.SimpleListFilter): 17 | """ 18 | An admin list filter for the UserAdmin which enables 19 | filtering by its child models. 20 | """ 21 | title = _('user type') 22 | parameter_name = 'user_type' 23 | 24 | def lookups(self, request, model_admin): 25 | user_types = set([user.user_type for user in model_admin.model.objects.all()]) 26 | return [(user_type.id, user_type.name) for user_type in user_types] 27 | 28 | def queryset(self, request, queryset): 29 | try: 30 | value = int(self.value()) 31 | except TypeError: 32 | value = None 33 | 34 | if value: 35 | return queryset.filter(user_type_id__exact=value) 36 | else: 37 | return queryset 38 | 39 | 40 | class UserAdmin(BaseUserAdmin): 41 | fieldsets = ( 42 | (None, { 43 | 'fields': ('email', 'password') 44 | }), 45 | (_('Permissions'), { 46 | 'fields': ('is_active', 'is_staff', 'is_superuser', 47 | 'groups', 'user_permissions') 48 | }), 49 | (_('Important dates'), { 50 | 'fields': ('last_login', 'date_joined') 51 | }), 52 | ) 53 | 54 | add_fieldsets = ( 55 | (None, { 56 | 'classes': ('wide',), 57 | 'fields': ('email', 'password1', 'password2') 58 | }), 59 | ) 60 | 61 | form = UserChangeForm 62 | add_form = UserCreationForm 63 | 64 | list_display = ('email', 'is_active') 65 | list_filter = (UserModelFilter, 'is_staff', 'is_superuser', 'is_active',) 66 | search_fields = ('email',) 67 | ordering = ('email',) 68 | actions = ('activate_users', 'send_activation_email', ) 69 | readonly_fields = ('last_login', 'date_joined', ) 70 | 71 | def get_queryset(self, request): 72 | # optimize queryset for list display. 73 | qs = self.model.base_objects.get_queryset() 74 | ordering = self.get_ordering(request) 75 | if ordering: 76 | qs = qs.order_by(*ordering) 77 | return qs 78 | 79 | def activate_users(self, request, queryset): 80 | """ 81 | Activates the selected users, if they are not already 82 | activated. 83 | 84 | """ 85 | n = 0 86 | for user in queryset: 87 | if not user.is_active: 88 | user.activate() 89 | n += 1 90 | self.message_user( 91 | request, 92 | _('Successfully activated %(count)d %(items)s.') % 93 | {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS) 94 | activate_users.short_description = _('Activate selected %(verbose_name_plural)s') 95 | 96 | def send_activation_email(self, request, queryset): 97 | """ 98 | Send activation emails for the selected users, if they are not already 99 | activated. 100 | """ 101 | n = 0 102 | for user in queryset: 103 | if not user.is_active and settings.USERS_VERIFY_EMAIL: 104 | send_activation_email(user=user, request=request) 105 | n += 1 106 | 107 | self.message_user( 108 | request, _('Activation emails sent to %(count)d %(items)s.') % 109 | {'count': n, 'items': model_ngettext(self.opts, n)}, messages.SUCCESS) 110 | 111 | send_activation_email.short_description = \ 112 | _('Send activation emails to selected %(verbose_name_plural)s') 113 | 114 | 115 | admin.site.register(User, UserAdmin) 116 | -------------------------------------------------------------------------------- /users/compat.py: -------------------------------------------------------------------------------- 1 | import base64 2 | from binascii import Error as BinasciiError 3 | 4 | try: 5 | from django.utils.http import urlsafe_base64_encode 6 | except ImportError: 7 | def urlsafe_base64_encode(s): 8 | """ 9 | Encodes a bytestring in base64 for use in URLs, stripping any trailing 10 | equal signs. 11 | """ 12 | return base64.urlsafe_b64encode(s).rstrip(b'\n=') 13 | 14 | try: 15 | from django.utils.http import urlsafe_base64_decode 16 | except ImportError: 17 | def urlsafe_base64_decode(s): 18 | """ 19 | Decodes a base64 encoded string, adding back any trailing equal signs that 20 | might have been stripped. 21 | """ 22 | s = s.encode('utf-8') # base64encode should only return ASCII. 23 | try: 24 | return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'=')) 25 | except (LookupError, BinasciiError) as e: 26 | raise ValueError(e) 27 | -------------------------------------------------------------------------------- /users/conf.py: -------------------------------------------------------------------------------- 1 | from appconf import AppConf 2 | from django.conf import settings 3 | 4 | 5 | class UsersAppConf(AppConf): 6 | VERIFY_EMAIL = False 7 | CREATE_SUPERUSER = settings.DEBUG 8 | SUPERUSER_EMAIL = 'superuser@djangoproject.com' 9 | SUPERUSER_PASSWORD = 'django' 10 | EMAIL_CONFIRMATION_TIMEOUT_DAYS = 3 11 | SPAM_PROTECTION = True 12 | REGISTRATION_OPEN = True 13 | AUTO_LOGIN_ON_ACTIVATION = True 14 | AUTO_LOGIN_AFTER_REGISTRATION = False 15 | PASSWORD_MIN_LENGTH = 5 16 | PASSWORD_MAX_LENGTH = None 17 | CHECK_PASSWORD_COMPLEXITY = True 18 | PASSWORD_POLICY = { 19 | 'UPPER': 0, # Uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 20 | 'LOWER': 0, # Lowercase 'abcdefghijklmnopqrstuvwxyz' 21 | 'DIGITS': 0, # Digits '0123456789' 22 | 'PUNCTUATION': 0 # Punctuation """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" 23 | } 24 | VALIDATE_EMAIL_DOMAIN = True 25 | EMAIL_DOMAINS_BLACKLIST = [] 26 | EMAIL_DOMAINS_WHITELIST = [] 27 | 28 | class Meta: 29 | prefix = 'users' 30 | -------------------------------------------------------------------------------- /users/fields.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | from django import forms 4 | from django.core.validators import validate_email 5 | from django.forms.widgets import CheckboxInput 6 | from django.utils.encoding import force_text 7 | from django.utils.translation import ugettext_lazy as _ 8 | 9 | from .conf import settings 10 | 11 | 12 | class LengthValidator(object): 13 | code = 'length' 14 | 15 | def __init__(self, min_length=None, max_length=None): 16 | self.min_length = min_length or settings.USERS_PASSWORD_MIN_LENGTH 17 | self.max_length = max_length or settings.USERS_PASSWORD_MAX_LENGTH 18 | 19 | def __call__(self, value): 20 | if self.min_length and len(value) < self.min_length: 21 | raise forms.ValidationError( 22 | _('Password too short (must be %s characters or more)') % self.min_length, 23 | code=self.code) 24 | elif self.max_length and len(value) > self.max_length: 25 | raise forms.ValidationError( 26 | _('Password too long (must be %s characters or less)') % self.max_length, 27 | code=self.code) 28 | 29 | length_validator = LengthValidator() 30 | 31 | 32 | class ComplexityValidator(object): 33 | code = 'complexity' 34 | message = _('Weak password, %s') 35 | 36 | def __init__(self): 37 | self.password_policy = settings.USERS_PASSWORD_POLICY 38 | 39 | def __call__(self, value): 40 | if not settings.USERS_CHECK_PASSWORD_COMPLEXITY: # pragma: no cover 41 | return 42 | 43 | uppercase, lowercase, digits, non_ascii, punctuation = set(), set(), set(), set(), set() 44 | 45 | for char in value: 46 | if char.isupper(): 47 | uppercase.add(char) 48 | elif char.islower(): 49 | lowercase.add(char) 50 | elif char.isdigit(): 51 | digits.add(char) 52 | elif char in string.punctuation: 53 | punctuation.add(char) 54 | else: 55 | non_ascii.add(char) 56 | 57 | if len(uppercase) < self.password_policy.get('UPPER', 0): 58 | raise forms.ValidationError( 59 | self.message % _('must contain %(UPPER)s or ' 60 | 'more uppercase characters (A-Z)') % self.password_policy, 61 | code=self.code) 62 | elif len(lowercase) < self.password_policy.get('LOWER', 0): 63 | raise forms.ValidationError( 64 | self.message % _('Must contain %(LOWER)s or ' 65 | 'more lowercase characters (a-z)') % self.password_policy, 66 | code=self.code) 67 | elif len(digits) < self.password_policy.get('DIGITS', 0): 68 | raise forms.ValidationError( 69 | self.message % _('must contain %(DIGITS)s or ' 70 | 'more numbers (0-9)') % self.password_policy, 71 | code=self.code) 72 | elif len(punctuation) < self.password_policy.get('PUNCTUATION', 0): 73 | raise forms.ValidationError( 74 | self.message % _('must contain %(PUNCTUATION)s or more ' 75 | 'symbols') % self.password_policy, 76 | code=self.code) 77 | 78 | 79 | complexity_validator = ComplexityValidator() 80 | 81 | 82 | class PasswordField(forms.CharField): 83 | widget = forms.PasswordInput() 84 | default_validators = [length_validator, complexity_validator, ] 85 | 86 | 87 | class HoneyPotField(forms.BooleanField): 88 | widget = CheckboxInput 89 | 90 | def __init__(self, *args, **kwargs): 91 | super(HoneyPotField, self).__init__(*args, **kwargs) 92 | self.required = False 93 | if not self.label: 94 | self.label = _('Are you human? (Sorry, we have to ask!)') 95 | if not self.help_text: 96 | self.help_text = _('Please don\'t check this box if you are a human.') 97 | 98 | def validate(self, value): 99 | if value: 100 | raise forms.ValidationError(_('Doh! You are a robot!')) 101 | 102 | 103 | class EmailDomainValidator(object): 104 | message = _('Sorry, %s emails are not allowed. Please use a different email address.') 105 | code = 'invalid' 106 | 107 | def __init__(self, ): 108 | self.domain_blacklist = settings.USERS_EMAIL_DOMAINS_BLACKLIST 109 | self.domain_whitelist = settings.USERS_EMAIL_DOMAINS_WHITELIST 110 | 111 | def __call__(self, value): 112 | if not settings.USERS_VALIDATE_EMAIL_DOMAIN: # pragma: no cover 113 | return 114 | 115 | if not value or '@' not in value: 116 | raise forms.ValidationError(_('Enter a valid email address.'), code=self.code) 117 | 118 | value = force_text(value) 119 | user_part, domain_part = value.rsplit('@', 1) 120 | 121 | if self.domain_blacklist and domain_part in self.domain_blacklist: 122 | raise forms.ValidationError(self.message % domain_part, code=self.code) 123 | 124 | if self.domain_whitelist and domain_part not in self.domain_whitelist: 125 | raise forms.ValidationError(self.message % domain_part, code=self.code) 126 | 127 | 128 | validate_email_domain = EmailDomainValidator() 129 | 130 | 131 | class UsersEmailField(forms.EmailField): 132 | default_validators = [validate_email, validate_email_domain] 133 | -------------------------------------------------------------------------------- /users/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from django.contrib.auth import get_user_model 3 | from django.contrib.auth.forms import ReadOnlyPasswordHashField 4 | from django.utils.translation import ugettext_lazy as _ 5 | 6 | from .conf import settings 7 | from .fields import HoneyPotField, PasswordField, UsersEmailField 8 | 9 | 10 | class UserCreationForm(forms.ModelForm): 11 | 12 | error_messages = { 13 | 'duplicate_email': _('A user with that email already exists.'), 14 | 'password_mismatch': _('The two password fields didn\'t match.'), 15 | } 16 | 17 | email = UsersEmailField(label=_('Email Address'), max_length=255) 18 | password1 = PasswordField(label=_('Password')) 19 | password2 = PasswordField( 20 | label=_('Password Confirmation'), 21 | help_text=_('Enter the same password as above, for verification.')) 22 | 23 | class Meta: 24 | model = get_user_model() 25 | fields = ('email',) 26 | 27 | def clean_email(self): 28 | 29 | # Since User.email is unique, this check is redundant, 30 | # but it sets a nicer error message than the ORM. See #13147. 31 | email = self.cleaned_data['email'] 32 | try: 33 | get_user_model()._default_manager.get(email=email) 34 | except get_user_model().DoesNotExist: 35 | return email 36 | raise forms.ValidationError( 37 | self.error_messages['duplicate_email'], 38 | code='duplicate_email', 39 | ) 40 | 41 | def clean_password2(self): 42 | 43 | password1 = self.cleaned_data.get('password1') 44 | password2 = self.cleaned_data.get('password2') 45 | if password1 and password2 and password1 != password2: 46 | raise forms.ValidationError( 47 | self.error_messages['password_mismatch'], 48 | code='password_mismatch', 49 | ) 50 | return password2 51 | 52 | def save(self, commit=True): 53 | user = super(UserCreationForm, self).save(commit=False) 54 | user.set_password(self.cleaned_data['password1']) 55 | user.is_active = not settings.USERS_VERIFY_EMAIL 56 | if commit: 57 | user.save() 58 | return user 59 | 60 | 61 | class UserChangeForm(forms.ModelForm): 62 | 63 | password = ReadOnlyPasswordHashField(label=_('Password'), help_text=_( 64 | 'Raw passwords are not stored, so there is no way to see ' 65 | 'this user\'s password, but you can change the password ' 66 | 'using this form.')) 67 | 68 | class Meta: 69 | model = get_user_model() 70 | exclude = () 71 | 72 | def __init__(self, *args, **kwargs): 73 | super(UserChangeForm, self).__init__(*args, **kwargs) 74 | f = self.fields.get('user_permissions', None) 75 | if f is not None: 76 | f.queryset = f.queryset.select_related('content_type') 77 | 78 | def clean_password(self): 79 | return self.initial['password'] 80 | 81 | 82 | class RegistrationForm(UserCreationForm): 83 | error_css_class = 'error' 84 | required_css_class = 'required' 85 | 86 | 87 | class RegistrationFormTermsOfService(RegistrationForm): 88 | """ 89 | Subclass of ``RegistrationForm`` which adds a required checkbox 90 | for agreeing to a site's Terms of Service. 91 | 92 | """ 93 | tos = forms.BooleanField( 94 | label=_('I have read and agree to the Terms of Service'), 95 | widget=forms.CheckboxInput, 96 | error_messages={ 97 | 'required': _('You must agree to the terms to register') 98 | }) 99 | 100 | 101 | class RegistrationFormHoneypot(RegistrationForm): 102 | """ 103 | Subclass of ``RegistrationForm`` which adds a honeypot field 104 | for Spam Prevention 105 | 106 | """ 107 | accept_terms = HoneyPotField() 108 | -------------------------------------------------------------------------------- /users/managers.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import BaseUserManager 2 | from django.utils import timezone 3 | 4 | from model_utils.managers import InheritanceQuerySet 5 | 6 | from .conf import settings 7 | 8 | 9 | class UserManager(BaseUserManager): 10 | 11 | def get_queryset(self): 12 | """ 13 | Fixes get_query_set vs get_queryset for Django <1.6 14 | """ 15 | try: 16 | qs = super(UserManager, self).get_queryset() 17 | except AttributeError: # pragma: no cover 18 | qs = super(UserManager, self).get_query_set() 19 | return qs 20 | 21 | get_query_set = get_queryset 22 | 23 | def _create_user(self, email, password, 24 | is_staff, is_superuser, **extra_fields): 25 | 26 | users_auto_activate = not settings.USERS_VERIFY_EMAIL 27 | now = timezone.now() 28 | if not email: 29 | raise ValueError('The given email must be set') 30 | email = self.normalize_email(email) 31 | 32 | is_active = extra_fields.pop('is_active', users_auto_activate) 33 | user = self.model(email=email, is_staff=is_staff, is_active=is_active, 34 | is_superuser=is_superuser, last_login=now, 35 | date_joined=now, **extra_fields) 36 | user.set_password(password) 37 | user.save(using=self._db) 38 | return user 39 | 40 | def create_user(self, email, password=None, **extra_fields): 41 | 42 | is_staff = extra_fields.pop('is_staff', False) 43 | return self._create_user(email=email, password=password, 44 | is_staff=is_staff, is_superuser=False, 45 | **extra_fields) 46 | 47 | def create_superuser(self, email, password, **extra_fields): 48 | return self._create_user(email=email, password=password, 49 | is_staff=True, is_superuser=True, 50 | is_active=True, **extra_fields) 51 | 52 | 53 | class UserInheritanceManager(UserManager): 54 | def get_queryset(self): 55 | return InheritanceQuerySet(self.model).select_subclasses() 56 | 57 | get_query_set = get_queryset 58 | -------------------------------------------------------------------------------- /users/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | import django.utils.timezone 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('auth', '0001_initial'), 12 | ('contenttypes', '0001_initial'), 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='User', 18 | fields=[ 19 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 20 | ('password', models.CharField(max_length=128, verbose_name='password')), 21 | ('last_login', models.DateTimeField(default=django.utils.timezone.now, verbose_name='last login')), 22 | ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), 23 | ('email', models.EmailField(unique=True, max_length=255, verbose_name='email address', db_index=True)), 24 | ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), 25 | ('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')), 26 | ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), 27 | ('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')), 28 | ('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')), 29 | ('user_type', models.ForeignKey(editable=False, on_delete=models.SET_NULL, to='contenttypes.ContentType', null=True)), 30 | ], 31 | options={ 32 | 'abstract': False, 33 | 'verbose_name': 'User', 34 | 'swappable': 'AUTH_USER_MODEL', 35 | 'verbose_name_plural': 'Users', 36 | }, 37 | bases=(models.Model,), 38 | ), 39 | ] 40 | -------------------------------------------------------------------------------- /users/migrations/0002_alter_user_last_login_null.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('users', '0001_initial'), 11 | ] 12 | 13 | operations = [ 14 | migrations.AlterField( 15 | model_name='user', 16 | name='last_login', 17 | field=models.DateTimeField(null=True, verbose_name='last login', blank=True), 18 | ), 19 | ] 20 | -------------------------------------------------------------------------------- /users/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mishbahr/django-users2/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/migrations/__init__.py -------------------------------------------------------------------------------- /users/models.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin 2 | from django.contrib.contenttypes.models import ContentType 3 | from django.core.mail import send_mail 4 | from django.db import models 5 | from django.utils import timezone 6 | from django.utils.translation import ugettext_lazy as _ 7 | 8 | from .conf import settings 9 | from .managers import UserInheritanceManager, UserManager 10 | 11 | 12 | class AbstractUser(AbstractBaseUser, PermissionsMixin): 13 | USERS_AUTO_ACTIVATE = not settings.USERS_VERIFY_EMAIL 14 | 15 | email = models.EmailField( 16 | _('email address'), max_length=255, unique=True, db_index=True) 17 | is_staff = models.BooleanField( 18 | _('staff status'), default=False, 19 | help_text=_('Designates whether the user can log into this admin site.')) 20 | 21 | is_active = models.BooleanField( 22 | _('active'), default=USERS_AUTO_ACTIVATE, 23 | help_text=_('Designates whether this user should be treated as ' 24 | 'active. Unselect this instead of deleting accounts.')) 25 | date_joined = models.DateTimeField(_('date joined'), default=timezone.now) 26 | user_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True, editable=False) 27 | 28 | objects = UserInheritanceManager() 29 | base_objects = UserManager() 30 | 31 | USERNAME_FIELD = 'email' 32 | REQUIRED_FIELDS = [] 33 | 34 | class Meta: 35 | verbose_name = _('User') 36 | verbose_name_plural = _('Users') 37 | abstract = True 38 | 39 | def get_full_name(self): 40 | """ Return the email.""" 41 | return self.email 42 | 43 | def get_short_name(self): 44 | """ Return the email.""" 45 | return self.email 46 | 47 | def email_user(self, subject, message, from_email=None): 48 | """ Send an email to this User.""" 49 | send_mail(subject, message, from_email, [self.email]) 50 | 51 | def activate(self): 52 | self.is_active = True 53 | self.save() 54 | 55 | def save(self, *args, **kwargs): 56 | if not self.user_type_id: 57 | self.user_type = ContentType.objects.get_for_model(self, for_concrete_model=False) 58 | super(AbstractUser, self).save(*args, **kwargs) 59 | 60 | 61 | class User(AbstractUser): 62 | 63 | """ 64 | Concrete class of AbstractUser. 65 | Use this if you don't need to extend User. 66 | """ 67 | 68 | class Meta(AbstractUser.Meta): 69 | swappable = 'AUTH_USER_MODEL' 70 | -------------------------------------------------------------------------------- /users/signals.py: -------------------------------------------------------------------------------- 1 | from django.dispatch import Signal 2 | 3 | # A new user has registered. 4 | user_registered = Signal(providing_args=['user', 'request']) 5 | 6 | # A user has activated his or her account. 7 | user_activated = Signal(providing_args=['user', 'request']) 8 | -------------------------------------------------------------------------------- /users/templates/base.html: -------------------------------------------------------------------------------- 1 | {% load i18n staticfiles %} 2 | 3 | 4 | 5 | {% block title %}{{ title|default:"django-users2"}}{% endblock %} 6 | 7 | 8 | 9 | 10 | 11 | 12 | 17 |
18 | {% if messages %} 19 | {% for message in messages %} 20 |
{{ message }}
21 | {% endfor %} 22 | {% endif %} 23 | {% block content %} 24 |

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

25 | {% endblock content %} 26 |
27 | 28 | 29 | -------------------------------------------------------------------------------- /users/templates/users/activate.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |

{% trans "Account activation failed" %}

6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /users/templates/users/activation_complete.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |

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

6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /users/templates/users/activation_email.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | 3 | {% trans "Thank you for registering an account at" %} {{ site.name }} 4 | {% trans "To activate your registration, please visit the following page:" %} 5 | 6 | {{ protocol }}://{{ site.domain }}{% url 'users_activate' uid token %} 7 | 8 | {% blocktrans %}This link will expire in {{ expiration_days }} days.{% endblocktrans %} 9 | 10 | {% trans "If you didn't register this account you can simply delete this email and we won't bother you again." %} 11 | -------------------------------------------------------------------------------- /users/templates/users/activation_email_subject.html: -------------------------------------------------------------------------------- 1 | {% load i18n %}{% trans "Account activation on" %} {{ site.name }} 2 | -------------------------------------------------------------------------------- /users/templates/users/login.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |
6 |
7 | {% if form.errors %} 8 | {% include "users/partials/errors.html" %} 9 | {% endif %} 10 | {% csrf_token %} 11 | {% for field in form %} 12 | {% include "users/partials/field.html" %} 13 | {% endfor %} 14 |
15 | 16 |
17 | 18 |

{% trans "Forgot password" %}

19 |

{% trans "Register" %}

20 |
21 |
22 | {% endblock %} 23 | -------------------------------------------------------------------------------- /users/templates/users/logout.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |

{% trans "Logged out" %}

6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /users/templates/users/partials/errors.html: -------------------------------------------------------------------------------- 1 | {% if form.errors and form.non_field_errors %} 2 |
3 |
    4 | {{ form.non_field_errors|unordered_list }} 5 |
6 |
7 | {% endif %} 8 | -------------------------------------------------------------------------------- /users/templates/users/partials/field.html: -------------------------------------------------------------------------------- 1 | {% load form_tags %} 2 | 3 | {% if field.is_hidden %} 4 | {{ field }} 5 | {% elif field|is_honeypot %} 6 | {% include "users/partials/honeypot.html" %} 7 | {% else %} 8 |
9 | {% if field.errors %} 10 |
    11 | {{ field.errors|unordered_list }} 12 |
13 | {% endif %} 14 | {% if field|is_checkbox %} 15 | {{ field }} 16 | {% endif %} 17 | 20 | {% if not field|is_checkbox %} 21 | {{ field }} 22 | {% endif %} 23 | {% if field.help_text %} 24 |
{{ field.help_text|safe }}
25 | {% endif %} 26 |
27 | {% endif %} 28 | -------------------------------------------------------------------------------- /users/templates/users/partials/honeypot.html: -------------------------------------------------------------------------------- 1 | {% load form_tags %} 2 | 3 |
4 | {% if field.errors %} 5 |
    6 | {{ field.errors|unordered_list }} 7 |
8 | {% endif %} 9 | {% if field|is_checkbox %} 10 | {{ field }} 11 | {% endif %} 12 | 15 | {% if not field|is_checkbox %} 16 | {{ field }} 17 | {% endif %} 18 | {% if field.help_text %} 19 |
{{ field.help_text|safe }}
20 | {% endif %} 21 |
22 | -------------------------------------------------------------------------------- /users/templates/users/password_change_done.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |

{% trans "Password changed" %}

6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /users/templates/users/password_change_form.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |
6 |
7 | {% if form.errors %} 8 | {% include "users/partials/errors.html" %} 9 | {% endif %} 10 | {% csrf_token %} 11 | {% for field in form %} 12 | {% include "users/partials/field.html" %} 13 | {% endfor %} 14 |
15 | 16 |
17 |
18 |
19 | {% endblock %} 20 | -------------------------------------------------------------------------------- /users/templates/users/password_reset_complete.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |

{% trans "Password reset successfully" %}

6 |

{% trans "Log in" %}

7 | {% endblock %} 8 | -------------------------------------------------------------------------------- /users/templates/users/password_reset_confirm.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 | {% if validlink %} 6 |
7 |
8 | {% if form.errors %} 9 | {% include "users/partials/errors.html" %} 10 | {% endif %} 11 | {% csrf_token %} 12 | {% for field in form %} 13 | {% include "users/partials/field.html" %} 14 | {% endfor %} 15 |
16 | 17 |
18 |
19 |
20 | {% else %} 21 |

{% trans "Password reset failed" %}

22 | {% endif %} 23 | {% endblock %} 24 | -------------------------------------------------------------------------------- /users/templates/users/password_reset_done.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |

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

6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /users/templates/users/password_reset_email.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | {% blocktrans %}Reset password at {{ site_name }}{% endblocktrans %}: 3 | {% block reset_link %} 4 | 5 | {{ protocol }}://{{ domain }}{% url 'users_password_reset_confirm' uid token %} 6 | 7 | {% endblock %} 8 | -------------------------------------------------------------------------------- /users/templates/users/password_reset_form.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |
6 |
7 | {% if form.errors %} 8 | {% include "users/partials/errors.html" %} 9 | {% endif %} 10 | {% csrf_token %} 11 | {% for field in form %} 12 | {% include "users/partials/field.html" %} 13 | {% endfor %} 14 |
15 | 16 |
17 |
18 |
19 | {% endblock %} 20 | -------------------------------------------------------------------------------- /users/templates/users/password_reset_subject.html: -------------------------------------------------------------------------------- 1 | {% load i18n %}{% autoescape off %} 2 | {% blocktrans %}Password reset on {{ site_name }}{% endblocktrans %} 3 | {% endautoescape %} 4 | -------------------------------------------------------------------------------- /users/templates/users/registration_closed.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |

{% trans "Sign Up Closed" %}

6 |

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

7 | {% endblock %} 8 | -------------------------------------------------------------------------------- /users/templates/users/registration_complete.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |

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

6 | {% endblock %} -------------------------------------------------------------------------------- /users/templates/users/registration_form.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load i18n %} 3 | 4 | {% block content %} 5 |
6 |
7 | {% if form.errors %} 8 | {% include "users/partials/errors.html" %} 9 | {% endif %} 10 | {% csrf_token %} 11 | {% for field in form %} 12 | {% include "users/partials/field.html" %} 13 | {% endfor %} 14 |
15 | 16 |
17 |
18 |
19 | {% endblock %} 20 | -------------------------------------------------------------------------------- /users/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mishbahr/django-users2/1ee244dc4ca162b2331d2a44d45848fdcb80f329/users/templatetags/__init__.py -------------------------------------------------------------------------------- /users/templatetags/form_tags.py: -------------------------------------------------------------------------------- 1 | from django import forms, template 2 | 3 | from users.fields import HoneyPotField 4 | 5 | register = template.Library() 6 | 7 | 8 | @register.filter 9 | def is_checkbox(field): 10 | return isinstance(field.field.widget, forms.CheckboxInput) 11 | 12 | 13 | @register.filter 14 | def input_class(field): 15 | """ 16 | Returns widgets class name in lowercase 17 | """ 18 | return field.field.widget.__class__.__name__.lower() 19 | 20 | 21 | @register.filter 22 | def is_honeypot(field): 23 | return isinstance(field.field, HoneyPotField) 24 | -------------------------------------------------------------------------------- /users/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from django.contrib.auth import views as auth_views 3 | 4 | from .views import (activate, activation_complete, register, 5 | registration_closed, registration_complete) 6 | 7 | urlpatterns = [ 8 | url(r'^register/$', register, name='users_register'), 9 | url(r'^register/closed/$', registration_closed, 10 | name='users_registration_closed'), 11 | url(r'^register/complete/$', registration_complete, 12 | name='users_registration_complete'), 13 | url(r'^activate/complete/$', activation_complete, 14 | name='users_activation_complete'), 15 | url(r'^activate/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 16 | activate, name='users_activate'), 17 | 18 | url(r'^login/$', auth_views.LoginView.as_view( 19 | template_name='users/login.html'), 20 | name='users_login'), 21 | url(r'^logout/$', auth_views.LogoutView.as_view( 22 | template_name='users/logout.html'), 23 | 24 | name='users_logout'), 25 | url(r'^password_change/$', auth_views.PasswordChangeView.as_view( 26 | template_name='users/password_change_form.html', 27 | success_url='users_password_change_done'), 28 | name='users_password_change'), 29 | url(r'^password_change/done/$', auth_views.PasswordChangeDoneView.as_view( 30 | template_name='users/password_change_done.html'), 31 | name='users_password_change_done'), 32 | url(r'^password_reset/$', auth_views.PasswordResetView.as_view( 33 | template_name='users/password_reset_form.html', 34 | email_template_name='users/password_reset_email.html', 35 | subject_template_name='users/password_reset_subject.html', 36 | success_url='users_password_reset_done'), 37 | name='users_password_reset'), 38 | url(r'^password_reset/done/$', 39 | auth_views.PasswordResetDoneView.as_view( 40 | template_name='users/password_reset_done.html'), 41 | name='users_password_reset_done'), 42 | url(r'^reset/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 43 | auth_views.PasswordResetConfirmView.as_view( 44 | template_name='users/password_reset_confirm.html', 45 | success_url='users_password_reset_complete'), 46 | name='users_password_reset_confirm'), 47 | url(r'^reset/done/$', auth_views.PasswordResetCompleteView.as_view( 48 | template_name='users/password_reset_complete.html'), 49 | name='users_password_reset_complete'), 50 | ] 51 | -------------------------------------------------------------------------------- /users/utils.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from django.contrib.auth import get_user_model 4 | from django.core.mail import EmailMultiAlternatives 5 | from django.template.loader import render_to_string 6 | from django.utils import six 7 | from django.utils.crypto import constant_time_compare, salted_hmac 8 | from django.utils.encoding import force_bytes 9 | from django.utils.http import base36_to_int, int_to_base36 10 | 11 | from .compat import urlsafe_base64_encode 12 | from .conf import settings 13 | 14 | try: 15 | from django.contrib.sites.shortcuts import get_current_site 16 | except ImportError: # pragma: no cover 17 | from django.contrib.sites.models import get_current_site 18 | 19 | try: 20 | from django.db.models.signals import post_migrate 21 | except ImportError: # pragma: no cover 22 | from django.db.models.signals import post_syncdb as post_migrate 23 | 24 | 25 | if settings.USERS_CREATE_SUPERUSER: 26 | try: 27 | # create_superuser is removed in django 1.7 28 | from django.contrib.auth.management import create_superuser 29 | except ImportError: # pragma: no cover 30 | pass 31 | else: 32 | # Prevent interactive question about wanting a superuser created. 33 | from django.contrib.auth import models as auth_app 34 | post_migrate.disconnect( 35 | create_superuser, 36 | sender=auth_app, 37 | dispatch_uid='django.contrib.auth.management.create_superuser') 38 | 39 | 40 | def auto_create_superuser(sender, **kwargs): 41 | if not settings.USERS_CREATE_SUPERUSER: 42 | return 43 | 44 | email = settings.USERS_SUPERUSER_EMAIL 45 | password = settings.USERS_SUPERUSER_PASSWORD 46 | 47 | User = get_user_model() 48 | try: 49 | User.base_objects.get(email=email) 50 | except User.DoesNotExist: 51 | print('Creating superuser ({0}:{1})'.format(email, password)) 52 | User.objects.create_superuser(email, password) 53 | 54 | post_migrate.connect(auto_create_superuser, sender=None) 55 | 56 | 57 | class EmailActivationTokenGenerator(object): 58 | 59 | def make_token(self, user): 60 | return self._make_token_with_timestamp(user, self._num_days(self._today())) 61 | 62 | def check_token(self, user, token): 63 | """ 64 | Check that a activation token is correct for a given user. 65 | """ 66 | # Parse the token 67 | try: 68 | ts_b36, hash = token.split('-') 69 | except ValueError: 70 | return False 71 | 72 | try: 73 | ts = base36_to_int(ts_b36) 74 | except ValueError: 75 | return False 76 | 77 | # Check that the timestamp/uid has not been tampered with 78 | if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): 79 | return False 80 | 81 | # Check the timestamp is within limit 82 | if (self._num_days(self._today()) - ts) > settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS: 83 | return False 84 | 85 | return True 86 | 87 | def _make_token_with_timestamp(self, user, timestamp): 88 | 89 | ts_b36 = int_to_base36(timestamp) 90 | key_salt = 'users.utils.EmailActivationTokenGenerator' 91 | login_timestamp = '' if user.last_login is None else \ 92 | user.last_login.replace(microsecond=0, tzinfo=None) 93 | value = (six.text_type(user.pk) + six.text_type(user.email) + 94 | six.text_type(login_timestamp) + six.text_type(timestamp)) 95 | hash = salted_hmac(key_salt, value).hexdigest()[::2] 96 | return '%s-%s' % (ts_b36, hash) 97 | 98 | @staticmethod 99 | def _num_days(dt): 100 | return (dt - date(2001, 1, 1)).days 101 | 102 | @staticmethod 103 | def _today(): 104 | # Used for mocking in tests 105 | return date.today() 106 | 107 | 108 | def send_activation_email( 109 | user=None, request=None, from_email=None, 110 | subject_template='users/activation_email_subject.html', 111 | email_template='users/activation_email.html', html_email_template=None): 112 | 113 | if not user.is_active and settings.USERS_VERIFY_EMAIL: 114 | token_generator = EmailActivationTokenGenerator() 115 | 116 | current_site = get_current_site(request) 117 | 118 | context = { 119 | 'email': user.email, 120 | 'site': current_site, 121 | 'expiration_days': settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS, 122 | 'user': user, 123 | 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 124 | 'token': token_generator.make_token(user=user), 125 | 'protocol': 'https' if request.is_secure() else 'http', 126 | } 127 | 128 | subject = render_to_string(subject_template, context) 129 | # email subject *must not* contain newlines 130 | subject = ''.join(subject.splitlines()) 131 | body = render_to_string(email_template, context) 132 | 133 | email_message = EmailMultiAlternatives(subject, body, from_email, [user.email]) 134 | if html_email_template is not None: 135 | html_email = render_to_string(html_email_template, context) 136 | email_message.attach_alternative(html_email, 'text/html') 137 | 138 | email_message.send() 139 | -------------------------------------------------------------------------------- /users/views.py: -------------------------------------------------------------------------------- 1 | from django.contrib import messages 2 | from django.contrib.auth import get_user_model, login 3 | from django.urls import reverse 4 | from django.shortcuts import redirect, resolve_url 5 | from django.template.response import TemplateResponse 6 | from django.utils.translation import ugettext as _ 7 | from django.views.decorators.cache import never_cache 8 | from django.views.decorators.csrf import csrf_protect 9 | 10 | from .compat import urlsafe_base64_decode 11 | from .conf import settings 12 | from .signals import user_activated, user_registered 13 | from .utils import EmailActivationTokenGenerator, send_activation_email 14 | 15 | try: 16 | from django.contrib.sites.shortcuts import get_current_site 17 | except ImportError: # pragma: no cover 18 | from django.contrib.sites.models import get_current_site 19 | 20 | 21 | if settings.USERS_SPAM_PROTECTION: # pragma: no cover 22 | from .forms import RegistrationFormHoneypot as RegistrationForm 23 | else: 24 | from .forms import RegistrationForm 25 | 26 | 27 | @csrf_protect 28 | @never_cache 29 | def register(request, 30 | template_name='users/registration_form.html', 31 | activation_email_template_name='users/activation_email.html', 32 | activation_email_subject_template_name='users/activation_email_subject.html', 33 | activation_email_html_template_name=None, 34 | registration_form=RegistrationForm, 35 | registered_user_redirect_to=None, 36 | post_registration_redirect=None, 37 | activation_from_email=None, 38 | current_app=None, 39 | extra_context=None): 40 | 41 | if registered_user_redirect_to is None: 42 | registered_user_redirect_to = getattr(settings, 'LOGIN_REDIRECT_URL') 43 | 44 | if request.user.is_authenticated: 45 | return redirect(registered_user_redirect_to) 46 | 47 | if not settings.USERS_REGISTRATION_OPEN: 48 | return redirect(reverse('users_registration_closed')) 49 | 50 | if post_registration_redirect is None: 51 | post_registration_redirect = reverse('users_registration_complete') 52 | 53 | if request.method == 'POST': 54 | form = registration_form(request.POST) 55 | if form.is_valid(): 56 | user = form.save() 57 | if settings.USERS_AUTO_LOGIN_AFTER_REGISTRATION: 58 | user.backend = 'django.contrib.auth.backends.ModelBackend' 59 | login(request, user) 60 | elif not user.is_active and settings.USERS_VERIFY_EMAIL: 61 | opts = { 62 | 'user': user, 63 | 'request': request, 64 | 'from_email': activation_from_email, 65 | 'email_template': activation_email_template_name, 66 | 'subject_template': activation_email_subject_template_name, 67 | 'html_email_template': activation_email_html_template_name, 68 | } 69 | send_activation_email(**opts) 70 | user_registered.send(sender=user.__class__, request=request, user=user) 71 | return redirect(post_registration_redirect) 72 | else: 73 | form = registration_form() 74 | 75 | current_site = get_current_site(request) 76 | 77 | context = { 78 | 'form': form, 79 | 'site': current_site, 80 | 'site_name': current_site.name, 81 | 'title': _('Register'), 82 | } 83 | 84 | if extra_context is not None: # pragma: no cover 85 | context.update(extra_context) 86 | return TemplateResponse(request, template_name, context) 87 | 88 | 89 | def registration_closed(request, 90 | template_name='users/registration_closed.html', 91 | current_app=None, 92 | extra_context=None): 93 | context = { 94 | 'title': _('Registration closed'), 95 | } 96 | if extra_context is not None: # pragma: no cover 97 | context.update(extra_context) 98 | return TemplateResponse(request, template_name, context) 99 | 100 | 101 | def registration_complete(request, 102 | template_name='users/registration_complete.html', 103 | current_app=None, 104 | extra_context=None): 105 | context = { 106 | 'login_url': resolve_url(settings.LOGIN_URL), 107 | 'title': _('Registration complete'), 108 | } 109 | if extra_context is not None: # pragma: no cover 110 | context.update(extra_context) 111 | return TemplateResponse(request, template_name, context) 112 | 113 | 114 | @never_cache 115 | def activate(request, 116 | uidb64=None, 117 | token=None, 118 | template_name='users/activate.html', 119 | post_activation_redirect=None, 120 | current_app=None, 121 | extra_context=None): 122 | 123 | context = { 124 | 'title': _('Account activation '), 125 | } 126 | 127 | if post_activation_redirect is None: 128 | post_activation_redirect = reverse('users_activation_complete') 129 | 130 | UserModel = get_user_model() 131 | assert uidb64 is not None and token is not None 132 | 133 | token_generator = EmailActivationTokenGenerator() 134 | 135 | try: 136 | uid = urlsafe_base64_decode(uidb64) 137 | user = UserModel._default_manager.get(pk=uid) 138 | except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): 139 | user = None 140 | 141 | if user is not None and token_generator.check_token(user, token): 142 | user.activate() 143 | user_activated.send(sender=user.__class__, request=request, user=user) 144 | if settings.USERS_AUTO_LOGIN_ON_ACTIVATION: 145 | user.backend = 'django.contrib.auth.backends.ModelBackend' # todo - remove this hack 146 | login(request, user) 147 | messages.info(request, 'Thanks for registering. You are now logged in.') 148 | return redirect(post_activation_redirect) 149 | else: 150 | title = _('Email confirmation unsuccessful') 151 | context = { 152 | 'title': title, 153 | } 154 | 155 | if extra_context is not None: # pragma: no cover 156 | context.update(extra_context) 157 | return TemplateResponse(request, template_name, context) 158 | 159 | 160 | def activation_complete(request, 161 | template_name='users/activation_complete.html', 162 | current_app=None, 163 | extra_context=None): 164 | context = { 165 | 'title': _('Activation complete'), 166 | } 167 | if extra_context is not None: # pragma: no cover 168 | context.update(extra_context) 169 | return TemplateResponse(request, template_name, context) 170 | --------------------------------------------------------------------------------