├── .circleci └── config.yml ├── .coveragerc ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── Makefile ├── changelog.rst ├── conf.py ├── index.rst ├── rest.rst ├── settings.rst └── usage.rst ├── manage.py ├── nopassword ├── __init__.py ├── admin.py ├── backends │ ├── __init__.py │ ├── base.py │ ├── email.py │ └── sms.py ├── forms.py ├── locale │ └── es │ │ └── LC_MESSAGES │ │ ├── django.mo │ │ └── django.po ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20190406_1322.py │ └── __init__.py ├── models.py ├── rest │ ├── __init__.py │ ├── serializers.py │ ├── urls.py │ └── views.py ├── templates │ └── registration │ │ ├── logged_out.html │ │ ├── login_code.html │ │ ├── login_email.txt │ │ ├── login_form.html │ │ ├── login_sms.txt │ │ └── login_subject.txt ├── urls.py └── views.py ├── requirements.txt ├── runtests.py ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── models.py ├── settings.py ├── templates │ └── 404.html ├── test_backends.py ├── test_forms.py ├── test_models.py ├── test_rest_views.py ├── test_views.py ├── tests.py └── urls.py └── tox.ini /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | jobs: 4 | flake8: 5 | docker: 6 | - image: circleci/python:3.6 7 | 8 | steps: 9 | - checkout 10 | - run: sudo pip install tox 11 | - restore_cache: 12 | keys: 13 | - v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }} 14 | - run: tox --notest 15 | - save_cache: 16 | key: v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }} 17 | paths: 18 | - .tox 19 | - run: tox -e flake8 20 | 21 | isort: 22 | docker: 23 | - image: circleci/python:3.6 24 | 25 | steps: 26 | - checkout 27 | - run: sudo pip install tox 28 | - restore_cache: 29 | keys: 30 | - v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }} 31 | - run: tox --notest 32 | - save_cache: 33 | key: v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }} 34 | paths: 35 | - .tox 36 | - run: tox -e isort 37 | 38 | tests: 39 | docker: 40 | - image: circleci/python:3.6 41 | 42 | steps: 43 | - checkout 44 | - run: sudo pip install tox 45 | - restore_cache: 46 | keys: 47 | - v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }} 48 | - run: tox --notest 49 | - save_cache: 50 | key: v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }} 51 | paths: 52 | - .tox 53 | - run: tox -e py2-django1_11 54 | - run: tox -e py3-django1_11 55 | - run: tox -e py3-django2_0 56 | - run: tox -e py3-django2_1 57 | - run: tox -e coverage 58 | 59 | workflows: 60 | version: 2 61 | 62 | build: 63 | jobs: 64 | - flake8 65 | - isort 66 | - tests 67 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | show_missing = True 3 | exclude_lines = 4 | pragma: no cover 5 | raise NotImplementedError 6 | if __name__ == .__main__.: 7 | if settings.DEBUG: 8 | if settings.DEBUG and*: 9 | if settings.DEBUG or*: 10 | 11 | omit = 12 | nopassword/migrations/* 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | 60 | 61 | tests/local.py 62 | docs/_build/ 63 | venv 64 | .python-version 65 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013 Rolf Erik Lekang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include setup.py README.md MANIFEST.in 2 | recursive-include nopassword/templates * 3 | recursive-include nopassword/static * 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-nopassword 2 | [![CircleCI](https://circleci.com/gh/relekang/django-nopassword.svg?style=svg)](https://circleci.com/gh/relekang/django-nopassword) 3 | 4 | _Authentication backend for django that uses a one time code instead of passwords._ 5 | 6 | This project was originally inspired by [Is it time for password-less login?](http://notes.xoxco.com/post/27999787765/is-it-time-for-password-less-login) by [Ben Brown](http://twitter.com/benbrown) 7 | 8 | ## Installation 9 | Run this command to install django-nopassword 10 | 11 | pip install django-nopassword 12 | 13 | ### Requirements 14 | Django >= 1.11 (custom user is supported) 15 | 16 | ## Usage 17 | Add the app to installed apps 18 | 19 | ```python 20 | INSTALLED_APPS = ( 21 | ... 22 | 'nopassword', 23 | ... 24 | ) 25 | ``` 26 | 27 | Add the authentication backend *EmailBackend* 28 | 29 | ```python 30 | AUTHENTICATION_BACKENDS = ( 31 | # Needed to login by username in Django admin, regardless of `nopassword` 32 | 'django.contrib.auth.backends.ModelBackend', 33 | 34 | # Send login codes via email 35 | 'nopassword.backends.email.EmailBackend', 36 | ) 37 | ``` 38 | 39 | Add urls to your *urls.py* 40 | 41 | ```python 42 | urlpatterns = patterns('', 43 | ... 44 | url(r'^accounts/', include('nopassword.urls')), 45 | ... 46 | ) 47 | ``` 48 | 49 | ### REST API 50 | 51 | To use the REST API, *djangorestframework* must be installed 52 | 53 | pip install djangorestframework 54 | 55 | Add rest framework to installed apps 56 | 57 | ```python 58 | INSTALLED_APPS = ( 59 | ... 60 | 'rest_framework', 61 | 'rest_framework.authtoken', 62 | 'nopassword', 63 | ... 64 | ) 65 | ``` 66 | 67 | Add *TokenAuthentication* to default authentication classes 68 | 69 | ```python 70 | REST_FRAMEWORK = { 71 | 'DEFAULT_AUTHENTICATION_CLASSES': ( 72 | 'rest_framework.authentication.TokenAuthentication', 73 | ) 74 | } 75 | ``` 76 | 77 | Add urls to your *urls.py* 78 | 79 | ```python 80 | urlpatterns = patterns('', 81 | ... 82 | url(r'^api/accounts/', include('nopassword.rest.urls')), 83 | ... 84 | ) 85 | ``` 86 | 87 | You will have the following endpoints available: 88 | 89 | - `/api/accounts/login/` (POST) 90 | - username 91 | - next (optional, will be returned in `/api/accounts/login/code/` to be handled by the frontend) 92 | - Sends a login code to the user 93 | - `/api/accounts/login/code/` (POST) 94 | - code 95 | - Returns `key` (authentication token) and `next` (provided by `/api/accounts/login/`) 96 | - `/api/accounts/logout/` (POST) 97 | - Performs logout 98 | 99 | ### Settings 100 | Information about the available settings can be found in the [docs](http://django-nopassword.readthedocs.org/en/latest/#settings) 101 | 102 | ## Tests 103 | Run with `python setup.py test`. 104 | 105 | -------- 106 | MIT © Rolf Erik Lekang 107 | -------------------------------------------------------------------------------- /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/django_nopassword.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django_nopassword.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/django_nopassword" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django_nopassword" 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." 178 | -------------------------------------------------------------------------------- /docs/changelog.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | 5.0.0 5 | ----- 6 | 7 | Breaking changes: 8 | 9 | - Removed custom length of login codes 10 | - Do not store the code in the database. Hash and compare on login instead. This might have an performance impact. 11 | - Add user id to the login code form and urls sent to the user. 12 | - Changing the secret key will now invalidate all login codes. 13 | 14 | 4.0.1 15 | ----- 16 | 17 | Set the default length of codes to 64. The setting ``NOPASSWORD_CODE_LENGTH`` is considered 18 | deprecated. 19 | 20 | 4.0.0 21 | ----- 22 | 23 | Added: 24 | 25 | - Added ``LoginCodeAdmin`` 26 | - Added rest support 27 | 28 | Breaking changes: 29 | 30 | - Remove support for Django < 1.11 31 | - Add support for Django 2 32 | - ``NoPasswordBackend.authenticate`` doesn't have side effects anymore, it only checks if a login code is valid. 33 | - ``NoPasswordBackend`` now uses the default django method ``user_can_authenticate`` instead of ``verify_user``. 34 | - Changed signature of ``NoPasswordBackend.send_login_code`` to ``send_login_code(code, context, **kwargs)``, to support custom template context. 35 | - ``EmailBackend`` doesn't attach a html message to the email by default. You can provide a template ``registration/login_email.html`` to do so. 36 | - Removed setting ``NOPASSWORD_LOGIN_EMAIL_SUBJECT`` in favor of template ``registration/login_subject.txt`` 37 | - Renamed form ``AuthenticationForm`` to ``LoginForm`` 38 | - ``LoginForm`` (previously ``AuthenticationForm``) doesn't have side effects anymore while cleaning. 39 | - ``LoginForm`` (previously ``AuthenticationForm``) doesn't check for cookie support anymore. 40 | - Removed methods ``get_user`` and ``get_user_id`` from ``LoginForm`` (previously ``AuthenticationForm``). 41 | - Removed method ``login_url`` and ``send_login_code`` from ``LoginCode`` (previously ``AuthenticationForm``). 42 | - Renamed template ``registration/login.html`` to ``registration/login_form.html``. 43 | - Changed content of default templates. 44 | - Removed views ``login_with_code_and_username``. 45 | - Refactored views to be class based views and to use forms instead of url parameters. 46 | - Changed url paths 47 | - Removed setting ``NOPASSWORD_POST_REDIRECT``, use ``NOPASSWORD_LOGIN_ON_GET`` instead. 48 | - Removed setting ``NOPASSWORD_NAMESPACE``. 49 | - Removed setting ``NOPASSWORD_HIDE_USERNAME``. 50 | - Removed setting ``NOPASSWORD_LOGIN_EMAIL_SUBJECT``. 51 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django_nopassword documentation build configuration file, created by 4 | # sphinx-quickstart on Thu Feb 27 20:16:47 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | # import sys 16 | # import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | # sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | # needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.doctest', 33 | 'sphinx.ext.coverage', 34 | 'sphinx.ext.viewcode', 35 | ] 36 | 37 | # Add any paths that contain templates here, relative to this directory. 38 | templates_path = ['_templates'] 39 | 40 | # The suffix of source filenames. 41 | source_suffix = '.rst' 42 | 43 | # The encoding of source files. 44 | # source_encoding = 'utf-8-sig' 45 | 46 | # The master toctree document. 47 | master_doc = 'index' 48 | 49 | # General information about the project. 50 | project = u'django_nopassword' 51 | copyright = u'2014, Rolf Erik Lekang' 52 | 53 | # The version info for the project you're documenting, acts as replacement for 54 | # |version| and |release|, also used in various other places throughout the 55 | # built documents. 56 | # 57 | # The short X.Y version. 58 | version = '0.6' 59 | # The full version, including alpha/beta/rc tags. 60 | release = '0.6.0' 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # language = None 65 | 66 | # There are two options for replacing |today|: either, you set today to some 67 | # non-false value, then it is used: 68 | # today = '' 69 | # Else, today_fmt is used as the format for a strftime call. 70 | # today_fmt = '%B %d, %Y' 71 | 72 | # List of patterns, relative to source directory, that match files and 73 | # directories to ignore when looking for source files. 74 | exclude_patterns = ['_build'] 75 | 76 | # The reST default role (used for this markup: `text`) to use for all 77 | # documents. 78 | # default_role = None 79 | 80 | # If true, '()' will be appended to :func: etc. cross-reference text. 81 | # add_function_parentheses = True 82 | 83 | # If true, the current module name will be prepended to all description 84 | # unit titles (such as .. function::). 85 | # add_module_names = True 86 | 87 | # If true, sectionauthor and moduleauthor directives will be shown in the 88 | # output. They are ignored by default. 89 | # show_authors = False 90 | 91 | # The name of the Pygments (syntax highlighting) style to use. 92 | pygments_style = 'sphinx' 93 | 94 | # A list of ignored prefixes for module index sorting. 95 | # modindex_common_prefix = [] 96 | 97 | # If true, keep warnings as "system message" paragraphs in the built documents. 98 | # keep_warnings = False 99 | 100 | 101 | # -- Options for HTML output ---------------------------------------------- 102 | 103 | # The theme to use for HTML and HTML Help pages. See the documentation for 104 | # a list of builtin themes. 105 | html_theme = 'default' 106 | 107 | # Theme options are theme-specific and customize the look and feel of a theme 108 | # further. For a list of options available for each theme, see the 109 | # documentation. 110 | # html_theme_options = {} 111 | 112 | # Add any paths that contain custom themes here, relative to this directory. 113 | # html_theme_path = [] 114 | 115 | # The name for this set of Sphinx documents. If None, it defaults to 116 | # " v documentation". 117 | # html_title = None 118 | 119 | # A shorter title for the navigation bar. Default is the same as html_title. 120 | # html_short_title = None 121 | 122 | # The name of an image file (relative to this directory) to place at the top 123 | # of the sidebar. 124 | # html_logo = None 125 | 126 | # The name of an image file (within the static path) to use as favicon of the 127 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 128 | # pixels large. 129 | # html_favicon = None 130 | 131 | # Add any paths that contain custom static files (such as style sheets) here, 132 | # relative to this directory. They are copied after the builtin static files, 133 | # so a file named "default.css" will overwrite the builtin "default.css". 134 | html_static_path = ['_static'] 135 | 136 | # Add any extra paths that contain custom files (such as robots.txt or 137 | # .htaccess) here, relative to this directory. These files are copied 138 | # directly to the root of the documentation. 139 | # html_extra_path = [] 140 | 141 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 142 | # using the given strftime format. 143 | # html_last_updated_fmt = '%b %d, %Y' 144 | 145 | # If true, SmartyPants will be used to convert quotes and dashes to 146 | # typographically correct entities. 147 | # html_use_smartypants = True 148 | 149 | # Custom sidebar templates, maps document names to template names. 150 | # html_sidebars = {} 151 | 152 | # Additional templates that should be rendered to pages, maps page names to 153 | # template names. 154 | # html_additional_pages = {} 155 | 156 | # If false, no module index is generated. 157 | # html_domain_indices = True 158 | 159 | # If false, no index is generated. 160 | # html_use_index = True 161 | 162 | # If true, the index is split into individual pages for each letter. 163 | # html_split_index = False 164 | 165 | # If true, links to the reST sources are added to the pages. 166 | # html_show_sourcelink = True 167 | 168 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 169 | # html_show_sphinx = True 170 | 171 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 172 | # html_show_copyright = True 173 | 174 | # If true, an OpenSearch description file will be output, and all pages will 175 | # contain a tag referring to it. The value of this option must be the 176 | # base URL from which the finished HTML is served. 177 | # html_use_opensearch = '' 178 | 179 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 180 | # html_file_suffix = None 181 | 182 | # Output file base name for HTML help builder. 183 | htmlhelp_basename = 'django_nopassworddoc' 184 | 185 | 186 | # -- Options for LaTeX output --------------------------------------------- 187 | 188 | latex_elements = { 189 | # The paper size ('letterpaper' or 'a4paper'). 190 | # 'papersize': 'letterpaper', 191 | 192 | # The font size ('10pt', '11pt' or '12pt'). 193 | # 'pointsize': '10pt', 194 | 195 | # Additional stuff for the LaTeX preamble. 196 | # 'preamble': '', 197 | } 198 | 199 | # Grouping the document tree into LaTeX files. List of tuples 200 | # (source start file, target name, title, 201 | # author, documentclass [howto, manual, or own class]). 202 | latex_documents = [ 203 | ('index', 'django_nopassword.tex', u'django\\_nopassword Documentation', 204 | u'Rolf Erik Lekang', 'manual'), 205 | ] 206 | 207 | # The name of an image file (relative to this directory) to place at the top of 208 | # the title page. 209 | # latex_logo = None 210 | 211 | # For "manual" documents, if this is true, then toplevel headings are parts, 212 | # not chapters. 213 | # latex_use_parts = False 214 | 215 | # If true, show page references after internal links. 216 | # latex_show_pagerefs = False 217 | 218 | # If true, show URL addresses after external links. 219 | # latex_show_urls = False 220 | 221 | # Documents to append as an appendix to all manuals. 222 | # latex_appendices = [] 223 | 224 | # If false, no module index is generated. 225 | # latex_domain_indices = True 226 | 227 | 228 | # -- Options for manual page output --------------------------------------- 229 | 230 | # One entry per manual page. List of tuples 231 | # (source start file, name, description, authors, manual section). 232 | man_pages = [ 233 | ('index', 'django_nopassword', u'django_nopassword Documentation', 234 | [u'Rolf Erik Lekang'], 1) 235 | ] 236 | 237 | # If true, show URL addresses after external links. 238 | # man_show_urls = False 239 | 240 | 241 | # -- Options for Texinfo output ------------------------------------------- 242 | 243 | # Grouping the document tree into Texinfo files. List of tuples 244 | # (source start file, target name, title, author, 245 | # dir menu entry, description, category) 246 | texinfo_documents = [ 247 | ('index', 'django_nopassword', u'django_nopassword Documentation', 248 | u'Rolf Erik Lekang', 'django_nopassword', 'One line description of project.', 249 | 'Miscellaneous'), 250 | ] 251 | 252 | # Documents to append as an appendix to all manuals. 253 | # texinfo_appendices = [] 254 | 255 | # If false, no module index is generated. 256 | # texinfo_domain_indices = True 257 | 258 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 259 | # texinfo_show_urls = 'footnote' 260 | 261 | # If true, do not generate a @detailmenu in the "Top" node's menu. 262 | # texinfo_no_detailmenu = False 263 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. django_nopassword documentation master file, created by 2 | sphinx-quickstart on Thu Feb 27 20:16:47 2014. 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_nopassword's documentation! 7 | ============================================= 8 | 9 | Authentication backend for django that uses a one time code instead of passwords. 10 | 11 | Installation 12 | ------------ 13 | Run this command to install django-nopassword:: 14 | 15 | pip install django-nopassword 16 | 17 | Requirements: 18 | Django >= 1.11 (custom user is supported) 19 | 20 | .. include:: usage.rst 21 | .. include:: rest.rst 22 | .. include:: settings.rst 23 | .. include:: changelog.rst 24 | -------------------------------------------------------------------------------- /docs/rest.rst: -------------------------------------------------------------------------------- 1 | REST API 2 | -------- 3 | To use the REST API, *djangorestframework* must be installed:: 4 | 5 | pip install djangorestframework 6 | 7 | Add rest framework to installed apps:: 8 | 9 | INSTALLED_APPS = ( 10 | ... 11 | 'rest_framework', 12 | 'rest_framework.authtoken', 13 | 'nopassword', 14 | ... 15 | ) 16 | 17 | Add *TokenAuthentication* to default authentication classes:: 18 | 19 | REST_FRAMEWORK = { 20 | 'DEFAULT_AUTHENTICATION_CLASSES': ( 21 | 'rest_framework.authentication.TokenAuthentication', 22 | ) 23 | } 24 | 25 | Add urls to your *urls.py*:: 26 | 27 | urlpatterns = patterns('', 28 | ... 29 | url(r'^api/accounts/', include('nopassword.rest.urls')), 30 | ... 31 | ) 32 | 33 | You will have the following endpoints available: 34 | 35 | - `/api/accounts/login/` (POST) 36 | - username 37 | - next (optional, will be returned in ``/api/accounts/login/code/`` to be handled by the frontend) 38 | - Sends a login code to the user 39 | - `/api/accounts/login/code/` (POST) 40 | - code 41 | - Returns ``key`` (authentication token) and ``next`` (provided by ``/api/accounts/login/``) 42 | - `/api/accounts/logout/` (POST) 43 | - Performs logout 44 | -------------------------------------------------------------------------------- /docs/settings.rst: -------------------------------------------------------------------------------- 1 | Settings 2 | -------- 3 | 4 | django-nopassword settings 5 | ++++++++++++++++++++++++++ 6 | 7 | .. currentmodule:: django.conf.settings 8 | 9 | .. attribute:: NOPASSWORD_LOGIN_CODE_TIMEOUT 10 | 11 | Default: ``900`` 12 | 13 | Defines how long a login code is valid in seconds. 14 | 15 | .. attribute:: NOPASSWORD_HASH_ALGORITHM 16 | 17 | Default: ``'sha256'`` 18 | 19 | Set the algorithm for used in logincode generation. Possible values are those who are supported in hashlib. The value should be set as the name of the attribute in hashlib. Example `hashlib.sha256()` would be `NOPASSWORD_HASH_ALGORITHM = 'sha256'. 20 | 21 | .. attribute:: NOPASSWORD_LOGIN_ON_GET 22 | 23 | Default: ``False`` 24 | 25 | By default, the login code url requires a POST request to authenticate the user. A GET request renders a form that must be submitted by the user to perform authentication. To authenticate directly inside the initial GET request instead, set this to ``True``. 26 | 27 | .. attribute:: NOPASSWORD_TWILIO_SID 28 | 29 | Account ID for Twilio. 30 | 31 | .. attribute:: NOPASSWORD_TWILIO_AUTH_TOKEN 32 | 33 | Account secret for Twilio 34 | 35 | .. attribute:: NOPASSWORD_NUMERIC_CODES 36 | 37 | Default: ``False`` 38 | 39 | A boolean flag if set to True, codes will contain numeric characters only (0-9). 40 | 41 | Django settings used in django-nopassword 42 | +++++++++++++++++++++++++++++++++++++++++ 43 | 44 | .. attribute:: DEFAULT_FROM_EMAIL 45 | 46 | Default: ``'root@example.com'`` 47 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | ----- 3 | Add the app to installed apps:: 4 | 5 | INSTALLED_APPS = ( 6 | 'nopassword', 7 | ) 8 | 9 | Add the authentication backend *EmailBackend*:: 10 | 11 | AUTHENTICATION_BACKENDS = ( 12 | # Needed to login by username in Django admin, regardless of `nopassword` 13 | 'django.contrib.auth.backends.ModelBackend', 14 | 15 | # Send login codes via email 16 | 'nopassword.backends.email.EmailBackend', 17 | ) 18 | 19 | Add urls to your *urls.py*:: 20 | 21 | urlpatterns = patterns('', 22 | url(r'^accounts/', include('nopassword.urls')), 23 | ) 24 | 25 | Backends 26 | ++++++++ 27 | There are several predefined backends. Usage of those backends are listed below. 28 | 29 | .. currentmodule:: nopassword.backends.email 30 | 31 | .. class:: EmailBackend 32 | Delivers the code by email. It uses the django send email functionality to send 33 | the emails. 34 | 35 | Override the following templates to customize emails: 36 | 37 | - ``registration/login_email.txt`` - Plain text message 38 | - ``registration/login_email.html`` - HTML message (note that no default html message is attached) 39 | - ``registration/login_subject.txt`` - Subject 40 | 41 | .. currentmodule:: nopassword.backends.sms 42 | 43 | .. class:: TwilioBackend 44 | Delivers the code by sms sent through the twilio service. 45 | 46 | Override the following template to customize messages: 47 | 48 | - ``registration/login_sms.txt`` - SMS message 49 | 50 | 51 | Custom backends 52 | ~~~~~~~~~~~~~~~ 53 | In backends.py there is a *NoPasswordBackend*, from which it is possible 54 | to build custom backends. The *EmailBackend* described above inherits from 55 | this backend. Creating your own backend can be done by creating a subclass 56 | of *NoPasswordBackend* and implementing *send_login_code*.:: 57 | 58 | class CustomBackend(NoPasswordBackend): 59 | 60 | def send_login_code(self, code, context, **kwargs): 61 | """ 62 | Use code.user to get contact information 63 | Use context to render a custom template 64 | Use kwargs in case you have a custom view that provides additional configuration 65 | """ 66 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | 7 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") 8 | 9 | from django.core.management import execute_from_command_line 10 | 11 | execute_from_command_line(sys.argv) 12 | -------------------------------------------------------------------------------- /nopassword/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '5.0.0' 2 | -------------------------------------------------------------------------------- /nopassword/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.contrib import admin 3 | 4 | from nopassword import models 5 | 6 | 7 | @admin.register(models.LoginCode) 8 | class LoginCodeAdmin(admin.ModelAdmin): 9 | list_display = ('code', 'user', 'timestamp') 10 | ordering = ('-timestamp',) 11 | readonly_fields = ('code', 'user', 'timestamp', 'next') 12 | -------------------------------------------------------------------------------- /nopassword/backends/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from .email import EmailBackend # noqa 3 | 4 | try: 5 | from .sms import TwilioBackend # noqa 6 | except ImportError: # pragma: no cover 7 | pass 8 | -------------------------------------------------------------------------------- /nopassword/backends/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from datetime import timedelta 3 | 4 | from django.conf import settings 5 | from django.contrib.auth import get_user_model 6 | from django.contrib.auth.backends import ModelBackend 7 | from django.utils import timezone 8 | 9 | from nopassword.models import LoginCode 10 | 11 | 12 | class NoPasswordBackend(ModelBackend): 13 | 14 | def authenticate(self, request, username=None, code=None, **kwargs): 15 | if username is None: 16 | username = kwargs.get(get_user_model().USERNAME_FIELD) 17 | 18 | if not username or not code: 19 | return 20 | 21 | try: 22 | user = get_user_model()._default_manager.get_by_natural_key(username) 23 | 24 | if not self.user_can_authenticate(user): 25 | return 26 | 27 | timeout = getattr(settings, 'NOPASSWORD_LOGIN_CODE_TIMEOUT', 900) 28 | timestamp = timezone.now() - timedelta(seconds=timeout) 29 | 30 | # We don't delete the login code when authenticating, 31 | # as that is done during validation of the login form 32 | # and validation should not have any side effects. 33 | # It is the responsibility of the view/form to delete the token 34 | # as soon as the login was successful. 35 | 36 | for c in LoginCode.objects.filter(user=user, timestamp__gt=timestamp): 37 | if c.code == code: 38 | user.login_code = c 39 | return user 40 | return 41 | 42 | except (get_user_model().DoesNotExist, LoginCode.DoesNotExist): 43 | return 44 | 45 | def send_login_code(self, code, context, **kwargs): 46 | raise NotImplementedError 47 | -------------------------------------------------------------------------------- /nopassword/backends/email.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.core.mail import EmailMultiAlternatives 3 | from django.template.exceptions import TemplateDoesNotExist 4 | from django.template.loader import render_to_string 5 | 6 | from nopassword.backends.base import NoPasswordBackend 7 | 8 | 9 | class EmailBackend(NoPasswordBackend): 10 | template_name = 'registration/login_email.txt' 11 | html_template_name = 'registration/login_email.html' 12 | subject_template_name = 'registration/login_subject.txt' 13 | from_email = None 14 | 15 | def send_login_code(self, code, context, **kwargs): 16 | to_email = code.user.email 17 | subject = render_to_string(self.subject_template_name, context) 18 | # Email subject *must not* contain newlines 19 | subject = ''.join(subject.splitlines()) 20 | body = render_to_string(self.template_name, context) 21 | 22 | email_message = EmailMultiAlternatives(subject, body, self.from_email, [to_email]) 23 | 24 | try: 25 | html_email = render_to_string(self.html_template_name, context) 26 | email_message.attach_alternative(html_email, 'text/html') 27 | except TemplateDoesNotExist: 28 | pass 29 | 30 | email_message.send() 31 | -------------------------------------------------------------------------------- /nopassword/backends/sms.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf import settings 3 | from django.template.loader import render_to_string 4 | from twilio.rest import TwilioRestClient 5 | 6 | from nopassword.backends.base import NoPasswordBackend 7 | 8 | 9 | class TwilioBackend(NoPasswordBackend): 10 | template_name = 'registration/login_sms.txt' 11 | from_number = None 12 | 13 | def __init__(self): 14 | self.twilio_client = TwilioRestClient( 15 | settings.NOPASSWORD_TWILIO_SID, 16 | settings.NOPASSWORD_TWILIO_AUTH_TOKEN 17 | ) 18 | super(TwilioBackend, self).__init__() 19 | 20 | def send_login_code(self, code, context, **kwargs): 21 | """ 22 | Send a login code via SMS 23 | """ 24 | from_number = self.from_number or getattr(settings, 'DEFAULT_FROM_NUMBER') 25 | sms_content = render_to_string(self.template_name, context) 26 | 27 | self.twilio_client.messages.create( 28 | to=code.user.phone_number, 29 | from_=from_number, 30 | body=sms_content 31 | ) 32 | -------------------------------------------------------------------------------- /nopassword/forms.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django import forms 3 | from django.contrib.auth import authenticate, get_backends, get_user_model 4 | from django.contrib.sites.shortcuts import get_current_site 5 | from django.core.exceptions import ImproperlyConfigured 6 | from django.shortcuts import resolve_url 7 | from django.utils.translation import ugettext_lazy as _ 8 | 9 | from nopassword import models 10 | 11 | 12 | class LoginForm(forms.Form): 13 | error_messages = { 14 | 'invalid_username': _( 15 | "Please enter a correct %(username)s. " 16 | "Note that it is case-sensitive." 17 | ), 18 | 'inactive': _("This account is inactive."), 19 | } 20 | 21 | next = forms.CharField(max_length=200, required=False, widget=forms.HiddenInput) 22 | 23 | def __init__(self, *args, **kwargs): 24 | super(LoginForm, self).__init__(*args, **kwargs) 25 | 26 | self.username_field = get_user_model()._meta.get_field(get_user_model().USERNAME_FIELD) 27 | self.fields['username'] = self.username_field.formfield() 28 | 29 | def clean_username(self): 30 | username = self.cleaned_data['username'] 31 | 32 | try: 33 | user = get_user_model()._default_manager.get_by_natural_key(username) 34 | except get_user_model().DoesNotExist: 35 | raise forms.ValidationError( 36 | self.error_messages['invalid_username'], 37 | code='invalid_username', 38 | params={'username': self.username_field.verbose_name}, 39 | ) 40 | 41 | if not user.is_active: 42 | raise forms.ValidationError( 43 | self.error_messages['inactive'], 44 | code='inactive', 45 | ) 46 | 47 | self.cleaned_data['user'] = user 48 | 49 | return username 50 | 51 | def save(self, request, login_code_url='login_code', domain_override=None, extra_context=None): 52 | login_code = models.LoginCode.create_code_for_user( 53 | user=self.cleaned_data['user'], 54 | next=self.cleaned_data['next'], 55 | ) 56 | 57 | if not domain_override: 58 | current_site = get_current_site(request) 59 | site_name = current_site.name 60 | domain = current_site.domain 61 | else: 62 | site_name = domain = domain_override 63 | 64 | url = '{}://{}{}?user={}&code={}'.format( 65 | 'https' if request.is_secure() else 'http', 66 | domain, 67 | resolve_url(login_code_url), 68 | login_code.user.pk, 69 | login_code.code, 70 | ) 71 | 72 | context = { 73 | 'domain': domain, 74 | 'site_name': site_name, 75 | 'code': login_code.code, 76 | 'url': url, 77 | } 78 | 79 | if extra_context: 80 | context.update(extra_context) 81 | 82 | self.send_login_code(login_code, context) 83 | 84 | return login_code 85 | 86 | def send_login_code(self, login_code, context, **kwargs): 87 | for backend in get_backends(): 88 | if hasattr(backend, 'send_login_code'): 89 | backend.send_login_code(login_code, context, **kwargs) 90 | break 91 | else: 92 | raise ImproperlyConfigured( 93 | 'Please add a nopassword authentication backend to settings, ' 94 | 'e.g. `nopassword.backends.EmailBackend`' 95 | ) 96 | 97 | 98 | class LoginCodeForm(forms.Form): 99 | user = forms.CharField() 100 | code = forms.CharField( 101 | label=_('Login code'), 102 | error_messages={ 103 | 'invalid_choice': _('Login code is invalid. It might have expired.'), 104 | }, 105 | ) 106 | 107 | error_messages = { 108 | 'invalid_code': _("Unable to log in with provided login code."), 109 | } 110 | 111 | def __init__(self, request=None, *args, **kwargs): 112 | super(LoginCodeForm, self).__init__(*args, **kwargs) 113 | 114 | self.request = request 115 | 116 | def clean(self): 117 | user_id = self.cleaned_data.get('user', None) 118 | if user_id is None: 119 | raise forms.ValidationError( 120 | self.error_messages['invalid_code'], 121 | code='invalid_code', 122 | ) 123 | 124 | user = get_user_model().objects.get(pk=user_id) 125 | code = self.cleaned_data['code'] 126 | user = authenticate(self.request, **{ 127 | get_user_model().USERNAME_FIELD: user.username, 128 | 'code': code, 129 | }) 130 | 131 | if not user: 132 | raise forms.ValidationError( 133 | self.error_messages['invalid_code'], 134 | code='invalid_code', 135 | ) 136 | 137 | self.cleaned_data['user'] = user 138 | 139 | return self.cleaned_data 140 | 141 | def get_user(self): 142 | return self.cleaned_data.get('user') 143 | 144 | def save(self): 145 | if self.get_user().login_code: 146 | self.get_user().login_code.delete() 147 | -------------------------------------------------------------------------------- /nopassword/locale/es/LC_MESSAGES/django.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/relekang/django-nopassword/d1d0f99617b1394c860864852326be673f9b935f/nopassword/locale/es/LC_MESSAGES/django.mo -------------------------------------------------------------------------------- /nopassword/locale/es/LC_MESSAGES/django.po: -------------------------------------------------------------------------------- 1 | # SOME DESCRIPTIVE TITLE. 2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER 3 | # This file is distributed under the same license as the PACKAGE package. 4 | # Alejandro Varas , 2014. 5 | # 6 | #, fuzzy 7 | msgid "" 8 | msgstr "" 9 | "Project-Id-Version: PACKAGE VERSION\n" 10 | "Report-Msgid-Bugs-To: \n" 11 | "POT-Creation-Date: 2014-01-06 09:05-0300\n" 12 | "PO-Revision-Date: 2014-01-06 09:07-0300\n" 13 | "Last-Translator: FULL NAME \n" 14 | "Language-Team: LANGUAGE \n" 15 | "Language: \n" 16 | "MIME-Version: 1.0\n" 17 | "Content-Type: text/plain; charset=UTF-8\n" 18 | "Content-Transfer-Encoding: 8bit\n" 19 | "Plural-Forms: nplurals=2; plural=(n != 1);\n" 20 | 21 | #: forms.py:15 22 | msgid "Username" 23 | msgstr "Nombre de usuario" 24 | 25 | #: forms.py:18 26 | msgid "" 27 | "Please enter a correct username and password. Note that both fields are case-" 28 | "sensitive." 29 | msgstr "" 30 | "Por favor, introduce un nombre de usuario y clave correctos. Observa que " 31 | "ambos campos pueden ser sensibles a mayúsculas" 32 | 33 | #: forms.py:20 34 | msgid "" 35 | "Your Web browser doesn't appear to have cookies enabled. Cookies are " 36 | "required for logging in." 37 | msgstr "" 38 | "Su navegador no parece tener las cookies habilitadas. Las cookies se " 39 | "necesitan para poder ingresar" 40 | 41 | #: forms.py:22 42 | msgid "This account is inactive." 43 | msgstr "Esta cuenta está inactiva." 44 | 45 | #: models.py:17 46 | msgid "user" 47 | msgstr "usuario" 48 | 49 | #: models.py:18 50 | msgid "code" 51 | msgstr "código" 52 | 53 | #: models.py:45 54 | msgid "Login code" 55 | msgstr "Código de inicio de sesión" 56 | 57 | #: templates/registration/login.html:10 58 | msgid "Login" 59 | msgstr "Iniciar sesión" 60 | 61 | #: templates/registration/login_email.html:1 62 | #: templates/registration/login_email.txt:1 63 | msgid "Login with this url " 64 | msgstr "Iniciar sesión con esta url" 65 | 66 | #: templates/registration/sent_mail.html:1 67 | msgid "We sent you a mail with a login link" 68 | msgstr "Le enviamos un correo electronico con un link para iniciar sesión" 69 | -------------------------------------------------------------------------------- /nopassword/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.conf import settings 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='LoginCode', 17 | fields=[ 18 | ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', 19 | auto_created=True)), 20 | ('code', models.CharField(editable=False, verbose_name='code', max_length=20)), 21 | ('timestamp', models.DateTimeField(editable=False)), 22 | ('next', models.TextField(blank=True, editable=False)), 23 | ('user', models.ForeignKey(related_name='login_codes', verbose_name='user', 24 | to=settings.AUTH_USER_MODEL, editable=False, on_delete=models.CASCADE)), 25 | ], 26 | options={ 27 | }, 28 | bases=(models.Model,), 29 | ), 30 | ] 31 | -------------------------------------------------------------------------------- /nopassword/migrations/0002_auto_20190406_1322.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2 on 2019-04-06 13:22 2 | 3 | import uuid 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | dependencies = [ 10 | ('nopassword', '0001_initial'), 11 | ] 12 | 13 | operations = [ 14 | migrations.RemoveField( 15 | model_name='logincode', 16 | name='code', 17 | ), 18 | migrations.AlterField( 19 | model_name='logincode', 20 | name='id', 21 | field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, 22 | serialize=False), 23 | ), 24 | ] 25 | -------------------------------------------------------------------------------- /nopassword/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/relekang/django-nopassword/d1d0f99617b1394c860864852326be673f9b935f/nopassword/migrations/__init__.py -------------------------------------------------------------------------------- /nopassword/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import hashlib 3 | import uuid 4 | 5 | from django.conf import settings 6 | from django.db import models 7 | from django.utils import timezone 8 | from django.utils.translation import ugettext_lazy as _ 9 | 10 | 11 | class LoginCode(models.Model): 12 | id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 13 | user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='login_codes', 14 | editable=False, verbose_name=_('user'), on_delete=models.CASCADE) 15 | timestamp = models.DateTimeField(editable=False) 16 | next = models.TextField(editable=False, blank=True) 17 | 18 | def __str__(self): 19 | return "%s - %s" % (self.user, self.timestamp) 20 | 21 | @property 22 | def code(self): 23 | hash_algorithm = getattr(settings, 'NOPASSWORD_HASH_ALGORITHM', 'sha256') 24 | m = getattr(hashlib, hash_algorithm)() 25 | m.update(getattr(settings, 'SECRET_KEY', None).encode('utf-8')) 26 | m.update(str(self.id).encode()) 27 | if getattr(settings, 'NOPASSWORD_NUMERIC_CODES', False): 28 | hashed = str(int(m.hexdigest(), 16)) 29 | else: 30 | hashed = m.hexdigest() 31 | return hashed 32 | 33 | def save(self, *args, **kwargs): 34 | self.timestamp = timezone.now() 35 | 36 | if not self.next: 37 | self.next = '/' 38 | 39 | super(LoginCode, self).save(*args, **kwargs) 40 | 41 | @classmethod 42 | def create_code_for_user(cls, user, next=None): 43 | if not user.is_active: 44 | return None 45 | 46 | login_code = LoginCode(user=user) 47 | if next is not None: 48 | login_code.next = next 49 | login_code.save() 50 | return login_code 51 | -------------------------------------------------------------------------------- /nopassword/rest/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/relekang/django-nopassword/d1d0f99617b1394c860864852326be673f9b935f/nopassword/rest/__init__.py -------------------------------------------------------------------------------- /nopassword/rest/serializers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from rest_framework import serializers 3 | from rest_framework.authtoken.models import Token 4 | 5 | from nopassword import forms 6 | 7 | 8 | class LoginSerializer(serializers.Serializer): 9 | username = serializers.CharField() 10 | next = serializers.CharField(required=False, allow_null=True) 11 | 12 | form_class = forms.LoginForm 13 | 14 | def validate(self, data): 15 | self.form = self.form_class(data=self.initial_data) 16 | 17 | if not self.form.is_valid(): 18 | raise serializers.ValidationError(self.form.errors) 19 | 20 | return self.form.cleaned_data 21 | 22 | def save(self): 23 | request = self.context.get('request') 24 | return self.form.save(request=request) 25 | 26 | 27 | class LoginCodeSerializer(serializers.Serializer): 28 | code = serializers.CharField() 29 | 30 | form_class = forms.LoginCodeForm 31 | 32 | def validate(self, data): 33 | request = self.context.get('request') 34 | 35 | self.form = self.form_class(data=self.initial_data, request=request) 36 | 37 | if not self.form.is_valid(): 38 | raise serializers.ValidationError(self.form.errors) 39 | 40 | return self.form.cleaned_data 41 | 42 | def save(self): 43 | self.form.save() 44 | 45 | 46 | class TokenSerializer(serializers.ModelSerializer): 47 | 48 | class Meta: 49 | model = Token 50 | fields = ('key',) 51 | -------------------------------------------------------------------------------- /nopassword/rest/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf.urls import url 3 | 4 | from nopassword.rest import views 5 | 6 | urlpatterns = [ 7 | url(r'^login/$', views.LoginView.as_view(), name='rest_login'), 8 | url(r'^login/code/$', views.LoginCodeView.as_view(), name='rest_login_code'), 9 | url(r'^logout/$', views.LogoutView.as_view(), name='rest_logout'), 10 | ] 11 | -------------------------------------------------------------------------------- /nopassword/rest/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf import settings 3 | from django.contrib.auth import login as django_login 4 | from django.contrib.auth import logout as django_logout 5 | from django.core.exceptions import ObjectDoesNotExist 6 | from django.utils.decorators import method_decorator 7 | from django.utils.translation import ugettext_lazy as _ 8 | from django.views.decorators.debug import sensitive_post_parameters 9 | from rest_framework import status 10 | from rest_framework.authtoken.models import Token 11 | from rest_framework.generics import GenericAPIView 12 | from rest_framework.permissions import AllowAny 13 | from rest_framework.response import Response 14 | from rest_framework.views import APIView 15 | 16 | from nopassword.rest import serializers 17 | 18 | 19 | class LoginView(GenericAPIView): 20 | serializer_class = serializers.LoginSerializer 21 | permission_classes = (AllowAny,) 22 | 23 | def post(self, request, *args, **kwargs): 24 | serializer = self.get_serializer(data=request.data) 25 | serializer.is_valid(raise_exception=True) 26 | serializer.save() 27 | 28 | return Response( 29 | {"detail": _("Login code has been sent.")}, 30 | status=status.HTTP_200_OK 31 | ) 32 | 33 | 34 | @method_decorator(sensitive_post_parameters('code'), 'dispatch') 35 | class LoginCodeView(GenericAPIView): 36 | permission_classes = (AllowAny,) 37 | serializer_class = serializers.LoginCodeSerializer 38 | token_serializer_class = serializers.TokenSerializer 39 | token_model = Token 40 | 41 | def process_login(self): 42 | django_login(self.request, self.user) 43 | 44 | def login(self): 45 | self.user = self.serializer.validated_data['user'] 46 | self.token, created = self.token_model.objects.get_or_create(user=self.user) 47 | 48 | if getattr(settings, 'REST_SESSION_LOGIN', True): 49 | self.process_login() 50 | 51 | def get_response(self): 52 | token_serializer = self.token_serializer_class( 53 | instance=self.token, 54 | context=self.get_serializer_context(), 55 | ) 56 | data = token_serializer.data 57 | data['next'] = self.serializer.validated_data['user'].login_code.next 58 | return Response(data, status=status.HTTP_200_OK) 59 | 60 | def post(self, request, *args, **kwargs): 61 | self.serializer = self.get_serializer(data=request.data) 62 | self.serializer.is_valid(raise_exception=True) 63 | self.serializer.save() 64 | self.login() 65 | return self.get_response() 66 | 67 | 68 | class LogoutView(APIView): 69 | permission_classes = (AllowAny,) 70 | 71 | def post(self, request, *args, **kwargs): 72 | return self.logout(request) 73 | 74 | def logout(self, request): 75 | try: 76 | request.user.auth_token.delete() 77 | except (AttributeError, ObjectDoesNotExist): 78 | pass 79 | 80 | django_logout(request) 81 | 82 | return Response( 83 | {"detail": _("Successfully logged out.")}, 84 | status=status.HTTP_200_OK, 85 | ) 86 | -------------------------------------------------------------------------------- /nopassword/templates/registration/logged_out.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | 3 | 4 | 5 | 6 | {% trans "Thanks for spending some quality time with the Web site today." %} 7 | 8 | 9 | -------------------------------------------------------------------------------- /nopassword/templates/registration/login_code.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | 3 | 4 | 5 | 6 |
7 | {% csrf_token %} 8 | 9 |

10 | {% trans "Please enter the login code that was sent to you." %} 11 |

12 | 13 | {{ form }} 14 | 15 | 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /nopassword/templates/registration/login_email.txt: -------------------------------------------------------------------------------- 1 | {% load i18n %}{% autoescape off %} 2 | {% blocktrans %}You're receiving this email because you requested a login code for your user account at {{ site_name }}.{% endblocktrans %} 3 | 4 | {% trans "Please enter the following code for sign in:" %} 5 | {{ code }} 6 | 7 | {% trans "You can also follow this link to sign in automatically:" %} 8 | {{ url }} 9 | 10 | {% trans "Thanks for using our site!" %} 11 | 12 | {% blocktrans %}The {{ site_name }} team{% endblocktrans %} 13 | 14 | {% endautoescape %} 15 | -------------------------------------------------------------------------------- /nopassword/templates/registration/login_form.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | 3 | 4 | 5 | 6 |
7 | {% csrf_token %} 8 | {{ form }} 9 | 10 |
11 | 12 | 13 | -------------------------------------------------------------------------------- /nopassword/templates/registration/login_sms.txt: -------------------------------------------------------------------------------- 1 | {% load i18n %}{% trans "Login with this url " %}{{ url }} 2 | -------------------------------------------------------------------------------- /nopassword/templates/registration/login_subject.txt: -------------------------------------------------------------------------------- 1 | {% load i18n %}{% autoescape off %} 2 | {% blocktrans %}Login code request on {{ site_name }}{% endblocktrans %} 3 | {% endautoescape %} 4 | -------------------------------------------------------------------------------- /nopassword/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | from django.conf.urls import url 3 | 4 | from nopassword import views 5 | 6 | urlpatterns = [ 7 | url(r'^login/$', views.LoginView.as_view(), name='login'), 8 | url(r'^login/code/$', views.LoginCodeView.as_view(), name='login_code'), 9 | url(r'^logout/$', views.LogoutView.as_view(), name='logout'), 10 | ] 11 | -------------------------------------------------------------------------------- /nopassword/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf import settings 3 | from django.contrib.auth.views import LoginView as DjangoLoginView 4 | from django.contrib.auth.views import LogoutView as DjangoLogoutView 5 | from django.urls import reverse_lazy 6 | from django.utils.decorators import method_decorator 7 | from django.views.decorators.csrf import csrf_protect 8 | from django.views.generic.edit import FormView 9 | 10 | from nopassword import forms 11 | 12 | 13 | class LoginView(FormView): 14 | """ 15 | Sends a login code to the user. 16 | It doesn't authenticate a user but it is the entry point for the login process (login url). 17 | """ 18 | 19 | form_class = forms.LoginForm 20 | success_url = reverse_lazy('login_code') 21 | template_name = 'registration/login_form.html' 22 | 23 | @method_decorator(csrf_protect) 24 | def dispatch(self, request, *args, **kwargs): 25 | return super(LoginView, self).dispatch(request, *args, **kwargs) 26 | 27 | def get_form_kwargs(self): 28 | kwargs = super(LoginView, self).get_form_kwargs() 29 | kwargs['initial'] = {'next': self.request.GET.get('next')} 30 | return kwargs 31 | 32 | def form_valid(self, form): 33 | form.save(request=self.request) 34 | return super(LoginView, self).form_valid(form) 35 | 36 | 37 | class LoginCodeView(DjangoLoginView): 38 | """ 39 | Authenticates a user with a login code. 40 | """ 41 | 42 | form_class = forms.LoginCodeForm 43 | template_name = 'registration/login_code.html' 44 | 45 | def get(self, request, *args, **kwargs): 46 | if 'code' in self.request.GET and getattr(settings, 'NOPASSWORD_LOGIN_ON_GET', False): 47 | return super(LoginCodeView, self).post(request, *args, **kwargs) 48 | return super(LoginCodeView, self).get(request, *args, **kwargs) 49 | 50 | def form_valid(self, form): 51 | form.save() 52 | return super(LoginCodeView, self).form_valid(form) 53 | 54 | def get_form_kwargs(self): 55 | kwargs = super(LoginCodeView, self).get_form_kwargs() 56 | 57 | if self.request.method == 'GET' and 'code' in self.request.GET: 58 | kwargs['data'] = self.request.GET 59 | 60 | return kwargs 61 | 62 | def get_redirect_url(self): 63 | login_code = getattr(self.request.user, 'login_code', None) 64 | return login_code.next if login_code else '' 65 | 66 | 67 | class LogoutView(DjangoLogoutView): 68 | pass 69 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | twilio==5.4.0 2 | mock>=1.0 3 | djangorestframework>=3.1.3 4 | coverage 5 | -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' 6 | 7 | from django.test.utils import get_runner # noqa isort:skip 8 | from django.conf import settings # noqa isort:skip 9 | import django # noqa isort:skip 10 | 11 | if django.VERSION >= (1, 7): 12 | django.setup() 13 | 14 | 15 | def runtests(): 16 | TestRunner = get_runner(settings) 17 | test_runner = TestRunner(verbosity=1, interactive=True) 18 | failures = test_runner.run_tests(['tests']) 19 | sys.exit(bool(failures)) 20 | 21 | 22 | if __name__ == '__main__': 23 | runtests() 24 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [flake8] 5 | max-line-length=100 6 | exclude=docs/conf.py,.tox,tests/local.py 7 | 8 | [isort] 9 | line_length = 100 10 | skip = .tox,venv 11 | default_section = THIRDPARTY 12 | known_first_party = nopassword,tests 13 | 14 | [semantic_release] 15 | version_variable = nopassword/__init__.py:__version__ 16 | major_tag = [major] 17 | minor_tag = [minor] 18 | patch_tag = [patch] 19 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import sys 4 | 5 | from setuptools import setup, find_packages 6 | 7 | os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' 8 | 9 | 10 | def _read_long_description(): 11 | try: 12 | import pypandoc 13 | return pypandoc.convert('README.md', 'rst') 14 | except ImportError: 15 | return None 16 | 17 | 18 | with open('nopassword/__init__.py', 'r') as fd: 19 | version = re.search( 20 | r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', 21 | fd.read(), 22 | re.MULTILINE 23 | ).group(1) 24 | 25 | try: 26 | from semantic_release import setup_hook 27 | 28 | setup_hook(sys.argv) 29 | except ImportError: 30 | pass 31 | 32 | setup( 33 | name="django-nopassword", 34 | version=version, 35 | url='http://github.com/relekang/django-nopassword', 36 | author='Rolf Erik Lekang', 37 | author_email='me@rolflekang.com', 38 | description='Authentication backend for django that uses a one time code instead of passwords', 39 | long_description=_read_long_description(), 40 | packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), 41 | install_requires=[ 42 | 'django>=1.11', 43 | ], 44 | extras_require={ 45 | 'rest': ['djangorestframework>=3.1.3'], 46 | }, 47 | tests_require=[ 48 | 'django>=1.11', 49 | 'twilio==4.4.0', 50 | 'mock>=1.0' 51 | ], 52 | license='MIT', 53 | test_suite='runtests.runtests', 54 | include_package_data=True, 55 | classifiers=[ 56 | "Programming Language :: Python", 57 | 'Programming Language :: Python :: 2.7', 58 | 'Programming Language :: Python :: 3.5', 59 | "Topic :: Software Development :: Libraries :: Python Modules", 60 | "Framework :: Django", 61 | "Environment :: Web Environment", 62 | "Operating System :: OS Independent", 63 | "Natural Language :: English", 64 | ] 65 | ) 66 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | try: 4 | from django.contrib.auth.models import AbstractUser, UserManager 5 | except ImportError: 6 | from django.db.models import Model as AbstractUser 7 | 8 | 9 | class CustomUser(AbstractUser): 10 | extra_field = models.CharField(max_length=2) 11 | new_username_field = models.CharField('userid', unique=True, max_length=20) 12 | 13 | USERNAME_FIELD = 'new_username_field' 14 | 15 | def save(self, *args, **kwargs): 16 | self.new_username_field = self.username 17 | super(CustomUser, self).save(*args, **kwargs) 18 | 19 | 20 | class PhoneNumberUser(CustomUser): 21 | phone_number = models.CharField(max_length=11, default="+15555555") 22 | 23 | 24 | class NoUsernameUser(models.Model): 25 | """User model without a "username" field for authentication 26 | backend testing 27 | """ 28 | pass 29 | -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | import os 3 | 4 | import django 5 | 6 | DEBUG = True 7 | 8 | DATABASES = { 9 | 'default': { 10 | 'ENGINE': 'django.db.backends.sqlite3', 11 | 'NAME': os.environ.get('DB_NAME', ':memory:'), 12 | } 13 | } 14 | 15 | AUTH_USER_MODEL = 'tests.CustomUser' 16 | 17 | NOPASSWORD_LOGIN_CODE_TIMEOUT = 900 18 | 19 | INSTALLED_APPS = [ 20 | 'django.contrib.admin', 21 | 'django.contrib.auth', 22 | 'django.contrib.contenttypes', 23 | 'django.contrib.sessions', 24 | 'django.contrib.messages', 25 | 26 | 'rest_framework', 27 | 'rest_framework.authtoken', 28 | 29 | 'nopassword', 30 | 'tests', 31 | ] 32 | AUTHENTICATION_BACKENDS = ( 33 | 'nopassword.backends.EmailBackend', 34 | 'django.contrib.auth.backends.ModelBackend' 35 | ) 36 | 37 | TIME_ZONE = 'America/Chicago' 38 | LANGUAGE_CODE = 'en-us' 39 | STATICFILES_FINDERS = ( 40 | 'django.contrib.staticfiles.finders.FileSystemFinder', 41 | 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 42 | ) 43 | 44 | SECRET_KEY = 'supersecret' 45 | 46 | TEMPLATES = [ 47 | { 48 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 49 | 'DIRS': [], 50 | 'APP_DIRS': True, 51 | 'OPTIONS': { 52 | 'context_processors': [ 53 | 'django.contrib.auth.context_processors.auth', 54 | 'django.contrib.messages.context_processors.messages' 55 | ], 56 | }, 57 | }, 58 | ] 59 | 60 | MIDDLEWARE = ( 61 | 'django.middleware.common.CommonMiddleware', 62 | 'django.contrib.sessions.middleware.SessionMiddleware', 63 | 'django.middleware.csrf.CsrfViewMiddleware', 64 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 65 | 'django.contrib.messages.middleware.MessageMiddleware', 66 | ) 67 | 68 | if django.VERSION < (1, 10): 69 | MIDDLEWARE_CLASSES = MIDDLEWARE 70 | 71 | ROOT_URLCONF = 'tests.urls' 72 | 73 | EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 74 | 75 | REST_FRAMEWORK = { 76 | 'DEFAULT_AUTHENTICATION_CLASSES': ( 77 | 'rest_framework.authentication.SessionAuthentication', 78 | 'rest_framework.authentication.TokenAuthentication', 79 | ), 80 | } 81 | -------------------------------------------------------------------------------- /tests/templates/404.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/relekang/django-nopassword/d1d0f99617b1394c860864852326be673f9b935f/tests/templates/404.html -------------------------------------------------------------------------------- /tests/test_backends.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | from django.contrib.auth import authenticate, get_user_model 3 | from django.test import TestCase 4 | from django.test.utils import mail, override_settings 5 | from mock import MagicMock, patch 6 | 7 | from nopassword.backends.base import NoPasswordBackend 8 | from nopassword.backends.email import EmailBackend 9 | from nopassword.backends.sms import TwilioBackend 10 | from nopassword.models import LoginCode 11 | 12 | 13 | class AuthenticationBackendTests(TestCase): 14 | 15 | @override_settings(AUTH_USER_MODULE='tests.NoUsernameUser') 16 | def test_authenticate_with_custom_user_model(self): 17 | """When a custom user model is used that doesn't have a field 18 | called "username" return `None` 19 | """ 20 | result = authenticate(username='username') 21 | self.assertIsNone(result) 22 | 23 | 24 | @override_settings(AUTH_USER_MODEL='tests.PhoneNumberUser', NOPASSWORD_TWILIO_SID="aaaaaaaa", 25 | NOPASSWORD_TWILIO_AUTH_TOKEN="bbbbbbbb", DEFAULT_FROM_NUMBER="+15555555") 26 | class TwilioBackendTests(TestCase): 27 | 28 | def setUp(self): 29 | self.user = get_user_model().objects.create(username='twilio_user') 30 | self.code = LoginCode.create_code_for_user(self.user, next='/secrets/') 31 | self.assertEqual(len(self.code.code), 64) 32 | self.assertIsNotNone(authenticate(username=self.user.username, code=self.code.code)) 33 | 34 | @patch('nopassword.backends.sms.TwilioRestClient') 35 | def test_twilio_backend(self, mock_object): 36 | self.backend = TwilioBackend() 37 | self.backend.twilio_client.messages.create = MagicMock() 38 | self.backend.send_login_code(self.code, {'url': 'https://example.com'}) 39 | self.assertTrue(mock_object.called) 40 | self.assertTrue(self.backend.twilio_client.messages.create.called) 41 | _, kwargs = self.backend.twilio_client.messages.create.call_args 42 | self.assertIn('https://example.com', kwargs.get('body')) 43 | 44 | 45 | class EmailBackendTests(TestCase): 46 | 47 | def setUp(self): 48 | self.user = get_user_model().objects.create( 49 | username='email_user', 50 | email='nopassword@example.com', 51 | ) 52 | self.code = LoginCode.create_code_for_user(self.user, next='/secrets/') 53 | self.backend = EmailBackend() 54 | 55 | def test_email_backend(self): 56 | "Send email via EmailBackend with default options" 57 | self.backend.send_login_code(self.code, {'url': 'https://example.com'}) 58 | self.assertEqual(1, len(mail.outbox)) 59 | message = mail.outbox[0] 60 | self.assertIn('https://example.com', message.body) 61 | self.assertEqual([self.user.email], message.to) 62 | self.assertEqual(0, len(message.alternatives)) 63 | 64 | def test_html_template_name(self): 65 | # We don't have an existing html template, so we just use the txt template 66 | self.backend.html_template_name = 'registration/login_email.txt' 67 | self.backend.send_login_code(self.code, {'url': 'https://example.com'}) 68 | self.assertEqual(1, len(mail.outbox)) 69 | message = mail.outbox[0] 70 | self.assertIn('https://example.com', message.body) 71 | self.assertEqual(1, len(message.alternatives)) 72 | self.assertIn('https://example.com', message.alternatives[0][0]) 73 | 74 | 75 | class TestBackendUtils(TestCase): 76 | 77 | def test_send_login_code(self): 78 | backend = NoPasswordBackend() 79 | self.assertRaises(NotImplementedError, backend.send_login_code, code=None, context=None) 80 | -------------------------------------------------------------------------------- /tests/test_forms.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | from django.contrib.auth import get_user_model 3 | from django.core.exceptions import ImproperlyConfigured 4 | from django.test import RequestFactory, TestCase, override_settings 5 | from mock import MagicMock 6 | 7 | from nopassword import forms 8 | 9 | 10 | class TestLoginForm(TestCase): 11 | 12 | def setUp(self): 13 | self.factory = RequestFactory() 14 | self.user = get_user_model().objects.create(username='user') 15 | 16 | def test_domain_override(self): 17 | request = self.factory.post('/accounts/login/', { 18 | 'username': 'user', 19 | }) 20 | form = forms.LoginForm(data=request.POST) 21 | form.send_login_code = MagicMock() 22 | 23 | self.assertTrue(form.is_valid()) 24 | 25 | form.save(request, domain_override='foobar.com') 26 | 27 | self.assertTrue(form.send_login_code.called) 28 | (login_code, context), _ = form.send_login_code.call_args 29 | self.assertIn('http://foobar.com', context['url']) 30 | 31 | def test_extra_context(self): 32 | request = self.factory.post('/accounts/login/', { 33 | 'username': 'user', 34 | }) 35 | form = forms.LoginForm(data=request.POST) 36 | form.send_login_code = MagicMock() 37 | 38 | self.assertTrue(form.is_valid()) 39 | 40 | form.save(request, extra_context={'foo': 'bar'}) 41 | 42 | self.assertTrue(form.send_login_code.called) 43 | (login_code, context), _ = form.send_login_code.call_args 44 | self.assertTrue('url' in context) 45 | self.assertEqual('bar', context['foo']) 46 | 47 | @override_settings( 48 | AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.ModelBackend'], 49 | ) 50 | def test_missing_backend(self): 51 | form = forms.LoginForm() 52 | self.assertRaises(ImproperlyConfigured, form.send_login_code, None, None) 53 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | import time 3 | from datetime import datetime 4 | 5 | from django.contrib.auth import authenticate, get_user_model 6 | from django.test import TestCase 7 | from django.test.utils import override_settings 8 | 9 | from nopassword.models import LoginCode 10 | 11 | 12 | class TestLoginCodes(TestCase): 13 | 14 | def setUp(self): 15 | self.user = get_user_model().objects.create(username='test_user') 16 | self.inactive_user = get_user_model().objects.create(username='inactive', is_active=False) 17 | self.code = LoginCode.create_code_for_user(self.user) 18 | 19 | def tearDown(self): 20 | LoginCode.objects.all().delete() 21 | 22 | def test_login_backend(self): 23 | self.assertEqual(len(self.code.code), 64) 24 | self.assertIsNotNone(authenticate(username=self.user.username, code=self.code.code)) 25 | self.assertIsNone(LoginCode.create_code_for_user(self.inactive_user)) 26 | 27 | @override_settings(NOPASSWORD_NUMERIC_CODES=True) 28 | def test_numeric_code(self): 29 | code = LoginCode.create_code_for_user(self.user) 30 | self.assertGreater(len(code.code), 64) 31 | self.assertTrue(code.code.isdigit()) 32 | 33 | def test_next_value(self): 34 | code = LoginCode.create_code_for_user(self.user, next='/secrets/') 35 | self.assertEqual(code.next, '/secrets/') 36 | 37 | @override_settings(NOPASSWORD_LOGIN_CODE_TIMEOUT=1) 38 | def test_code_timeout(self): 39 | timeout_code = LoginCode.create_code_for_user(self.user) 40 | time.sleep(3) 41 | self.assertIsNone(authenticate(username=self.user.username, code=timeout_code.code)) 42 | 43 | def test_str(self): 44 | code = LoginCode(user=self.user, timestamp=datetime(2018, 7, 1)) 45 | self.assertEqual(str(code), 'test_user - 2018-07-01 00:00:00') 46 | -------------------------------------------------------------------------------- /tests/test_rest_views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | from django.contrib.auth import get_user_model 3 | from django.core import mail 4 | from django.test import TestCase 5 | from rest_framework.authtoken.models import Token 6 | 7 | from nopassword.models import LoginCode 8 | 9 | 10 | class TestRestViews(TestCase): 11 | 12 | def setUp(self): 13 | self.user = get_user_model().objects.create(username='user', email='foo@bar.com') 14 | 15 | def test_request_login_code(self): 16 | response = self.client.post('/accounts-rest/login/', { 17 | 'username': self.user.username, 18 | 'next': '/private/', 19 | }) 20 | 21 | self.assertEqual(response.status_code, 200) 22 | 23 | login_code = LoginCode.objects.filter(user=self.user).first() 24 | 25 | self.assertIsNotNone(login_code) 26 | self.assertEqual(login_code.next, '/private/') 27 | self.assertEqual(len(mail.outbox), 1) 28 | self.assertIn( 29 | 'http://testserver/accounts/login/code/?user={}&code={}'.format( 30 | login_code.user.pk, 31 | login_code.code 32 | ), 33 | mail.outbox[0].body, 34 | ) 35 | 36 | def test_request_login_code_missing_username(self): 37 | response = self.client.post('/accounts-rest/login/') 38 | 39 | self.assertEqual(response.status_code, 400) 40 | self.assertEqual(response.json(), { 41 | 'username': ['This field is required.'], 42 | }) 43 | 44 | def test_request_login_code_unknown_user(self): 45 | response = self.client.post('/accounts-rest/login/', { 46 | 'username': 'unknown', 47 | }) 48 | 49 | self.assertEqual(response.status_code, 400) 50 | self.assertEqual(response.json(), { 51 | 'username': ['Please enter a correct userid. Note that it is case-sensitive.'], 52 | }) 53 | 54 | def test_request_login_code_inactive_user(self): 55 | self.user.is_active = False 56 | self.user.save() 57 | 58 | response = self.client.post('/accounts-rest/login/', { 59 | 'username': self.user.username, 60 | }) 61 | 62 | self.assertEqual(response.status_code, 400) 63 | self.assertEqual(response.json(), { 64 | 'username': ['This account is inactive.'], 65 | }) 66 | 67 | def test_login(self): 68 | login_code = LoginCode.objects.create(user=self.user, next='/private/') 69 | 70 | response = self.client.post('/accounts-rest/login/code/', { 71 | 'user': login_code.user.pk, 72 | 'code': login_code.code, 73 | }) 74 | 75 | self.assertEqual(response.status_code, 200) 76 | self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists()) 77 | 78 | token = Token.objects.filter(user=self.user).first() 79 | 80 | self.assertIsNotNone(token) 81 | self.assertEqual(response.data, { 82 | 'key': token.key, 83 | 'next': '/private/', 84 | }) 85 | 86 | def test_login_missing_code(self): 87 | response = self.client.post('/accounts-rest/login/code/') 88 | 89 | self.assertEqual(response.status_code, 400) 90 | self.assertEqual(response.json(), { 91 | 'code': ['This field is required.'], 92 | }) 93 | 94 | def test_login_unknown_code(self): 95 | response = self.client.post('/accounts-rest/login/code/', { 96 | 'code': 'unknown', 97 | }) 98 | 99 | self.assertEqual(response.status_code, 400) 100 | self.assertEqual(response.json(), { 101 | '__all__': ['Unable to log in with provided login code.'], 102 | 'user': ['This field is required.'] 103 | }) 104 | 105 | def test_login_inactive_user(self): 106 | self.user.is_active = False 107 | self.user.save() 108 | 109 | login_code = LoginCode.objects.create(user=self.user) 110 | 111 | response = self.client.post('/accounts-rest/login/code/', { 112 | 'code': login_code.code, 113 | }) 114 | 115 | self.assertEqual(response.status_code, 400) 116 | self.assertEqual(response.json(), { 117 | '__all__': ['Unable to log in with provided login code.'], 118 | 'user': ['This field is required.'] 119 | }) 120 | 121 | def test_logout(self): 122 | token = Token.objects.create(user=self.user, key='foobar') 123 | 124 | response = self.client.post( 125 | '/accounts-rest/logout/', 126 | HTTP_AUTHORIZATION='Token {}'.format(token.key), 127 | ) 128 | 129 | self.assertEqual(response.status_code, 200) 130 | self.assertFalse(Token.objects.filter(user=self.user).exists()) 131 | 132 | def test_logout_unknown_token(self): 133 | login_code = LoginCode.objects.create(user=self.user) 134 | 135 | self.client.login(username=self.user.username, code=login_code.code) 136 | 137 | response = self.client.post( 138 | '/accounts-rest/logout/', 139 | HTTP_AUTHORIZATION='Token unknown', 140 | ) 141 | 142 | self.assertEqual(response.status_code, 200) 143 | -------------------------------------------------------------------------------- /tests/test_views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | from django.contrib.auth import get_user_model 3 | from django.core import mail 4 | from django.test import TestCase, override_settings 5 | 6 | from nopassword.models import LoginCode 7 | 8 | 9 | class TestViews(TestCase): 10 | 11 | def setUp(self): 12 | self.user = get_user_model().objects.create(username='user', email='foo@bar.com') 13 | 14 | def test_request_login_code(self): 15 | response = self.client.post('/accounts/login/', { 16 | 'username': self.user.username, 17 | 'next': '/private/', 18 | }) 19 | 20 | self.assertEqual(response.status_code, 302) 21 | self.assertEqual(response['Location'], '/accounts/login/code/') 22 | 23 | login_code = LoginCode.objects.filter(user=self.user).first() 24 | 25 | self.assertIsNotNone(login_code) 26 | self.assertEqual(login_code.next, '/private/') 27 | self.assertEqual(len(mail.outbox), 1) 28 | self.assertIn( 29 | 'http://testserver/accounts/login/code/?user={}&code={}'.format( 30 | login_code.user.pk, 31 | login_code.code 32 | ), 33 | mail.outbox[0].body, 34 | ) 35 | 36 | def test_request_login_code_missing_username(self): 37 | response = self.client.post('/accounts/login/') 38 | 39 | self.assertEqual(response.status_code, 200) 40 | self.assertEqual(response.context['form'].errors, { 41 | 'username': ['This field is required.'], 42 | }) 43 | 44 | def test_request_login_code_unknown_user(self): 45 | response = self.client.post('/accounts/login/', { 46 | 'username': 'unknown', 47 | }) 48 | 49 | self.assertEqual(response.status_code, 200) 50 | self.assertEqual(response.context['form'].errors, { 51 | 'username': ['Please enter a correct userid. Note that it is case-sensitive.'], 52 | }) 53 | 54 | def test_request_login_code_inactive_user(self): 55 | self.user.is_active = False 56 | self.user.save() 57 | 58 | response = self.client.post('/accounts/login/', { 59 | 'username': self.user.username, 60 | }) 61 | 62 | self.assertEqual(response.status_code, 200) 63 | self.assertEqual(response.context['form'].errors, { 64 | 'username': ['This account is inactive.'], 65 | }) 66 | 67 | def test_login_post(self): 68 | login_code = LoginCode.objects.create(user=self.user, next='/private/') 69 | 70 | response = self.client.post('/accounts/login/code/', { 71 | 'user': login_code.user.pk, 72 | 'code': login_code.code, 73 | }) 74 | 75 | self.assertEqual(response.status_code, 302) 76 | self.assertEqual(response['Location'], '/private/') 77 | self.assertEqual(response.wsgi_request.user, self.user) 78 | self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists()) 79 | 80 | def test_login_get(self): 81 | login_code = LoginCode.objects.create(user=self.user) 82 | 83 | response = self.client.get('/accounts/login/code/', { 84 | 'user': login_code.user.pk, 85 | 'code': login_code.code, 86 | }) 87 | 88 | self.assertEqual(response.status_code, 200) 89 | self.assertEqual(response.context['form'].cleaned_data['code'], login_code.code) 90 | self.assertTrue(response.wsgi_request.user.is_anonymous) 91 | self.assertTrue(LoginCode.objects.filter(pk=login_code.pk).exists()) 92 | 93 | @override_settings(NOPASSWORD_LOGIN_ON_GET=True) 94 | def test_login_get_non_idempotent(self): 95 | login_code = LoginCode.objects.create(user=self.user, next='/private/') 96 | 97 | response = self.client.get('/accounts/login/code/', { 98 | 'user': login_code.user.pk, 99 | 'code': login_code.code, 100 | }) 101 | 102 | self.assertEqual(response.status_code, 302) 103 | self.assertEqual(response['Location'], '/private/') 104 | self.assertEqual(response.wsgi_request.user, self.user) 105 | self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists()) 106 | 107 | def test_login_missing_code_post(self): 108 | response = self.client.post('/accounts/login/code/') 109 | 110 | self.assertEqual(response.status_code, 200) 111 | self.assertEqual(response.context['form'].errors, { 112 | 'user': ['This field is required.'], 113 | 'code': ['This field is required.'], 114 | '__all__': ['Unable to log in with provided login code.'] 115 | }) 116 | 117 | def test_login_missing_code_get(self): 118 | response = self.client.get('/accounts/login/code/') 119 | 120 | self.assertEqual(response.status_code, 200) 121 | self.assertFalse(response.context['form'].is_bound) 122 | 123 | def test_login_unknown_code(self): 124 | response = self.client.post('/accounts/login/code/', { 125 | 'user': 1, 126 | 'code': 'unknown', 127 | }) 128 | 129 | self.assertEqual(response.status_code, 200) 130 | self.assertEqual(response.context['form'].errors, { 131 | '__all__': ['Unable to log in with provided login code.'], 132 | }) 133 | 134 | def test_login_inactive_user(self): 135 | self.user.is_active = False 136 | self.user.save() 137 | 138 | login_code = LoginCode.objects.create(user=self.user) 139 | 140 | response = self.client.post('/accounts/login/code/', { 141 | 'user': login_code.user.pk, 142 | 'code': login_code.code, 143 | }) 144 | 145 | self.assertEqual(response.status_code, 200) 146 | self.assertEqual(response.context['form'].errors, { 147 | '__all__': ['Unable to log in with provided login code.'] 148 | }) 149 | 150 | def test_logout_post(self): 151 | login_code = LoginCode.objects.create(user=self.user) 152 | 153 | self.client.login(username=self.user.username, code=login_code.code) 154 | 155 | response = self.client.post('/accounts/logout/?next=/accounts/login/') 156 | 157 | self.assertEqual(response.status_code, 302) 158 | self.assertEqual(response['Location'], '/accounts/login/') 159 | self.assertTrue(response.wsgi_request.user.is_anonymous) 160 | 161 | def test_logout_get(self): 162 | login_code = LoginCode.objects.create(user=self.user) 163 | 164 | self.client.login(username=self.user.username, code=login_code.code) 165 | 166 | response = self.client.post('/accounts/logout/?next=/accounts/login/') 167 | 168 | self.assertEqual(response.status_code, 302) 169 | self.assertEqual(response['Location'], '/accounts/login/') 170 | self.assertTrue(response.wsgi_request.user.is_anonymous) 171 | -------------------------------------------------------------------------------- /tests/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import django 3 | 4 | if django.VERSION < (1, 6): 5 | from .test_backends import * # noqa 6 | from .test_models import * # noqa 7 | from .test_views import * # noqa 8 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | from django.conf.urls import include, url 3 | from django.contrib import admin 4 | 5 | urlpatterns = [ 6 | url(r'^admin/', admin.site.urls), 7 | url(r'^accounts/', include('nopassword.urls')), 8 | url(r'^accounts-rest/', include('nopassword.rest.urls')), 9 | ] 10 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | flake8, 4 | isort, 5 | py2-{django1_11}, 6 | py3-{django1_11,django2_1,django2_2}, 7 | coverage 8 | skipsdist = True 9 | 10 | [testenv] 11 | basepython = 12 | py3: python3 13 | py2: python2 14 | setenv = 15 | PYTHONPATH = {toxinidir}:{toxinidir} 16 | DB_NAME = :memory: 17 | commands = 18 | coverage run -p --source=nopassword runtests.py 19 | deps = 20 | -r{toxinidir}/requirements.txt 21 | django1_11: Django>=1.11,<1.12 22 | django2_1: Django>=2.1,<2.2 23 | django2_2: Django>=2.2,<2.3 24 | 25 | [testenv:flake8] 26 | basepython = python3 27 | deps = flake8 28 | commands = flake8 29 | 30 | [testenv:isort] 31 | basepython = python3 32 | deps = isort 33 | commands = isort -c -rc nopassword tests 34 | 35 | [testenv:coverage] 36 | basepython = python3 37 | deps = coverage 38 | commands = 39 | coverage combine 40 | coverage report 41 | coverage xml 42 | --------------------------------------------------------------------------------