CVE-2019-10682 (Python, published 2020-03-18T15:15Z)
Description: value: django-nopassword before 5.0.0 stores cleartext secrets in the database.
Severity: MEDIUM (CVSS v3 base score: 7.5)
Weakness: CWE-312 \u2014 Cleartext Storage of Sensitive Information
The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
Repository: https://github.com/relekang/django-nopassword
Files changed:
.circleci/config.yml
.coveragerc
.gitignore
LICENSE
MANIFEST.in
README.md
docs/Makefile
docs/changelog.rst
docs/conf.py
docs/index.rst
docs/rest.rst
docs/settings.rst
docs/usage.rst
manage.py
nopassword/__init__.py
nopassword/admin.py
nopassword/backends/__init__.py
nopassword/backends/base.py
nopassword/backends/email.py
nopassword/backends/sms.py
nopassword/forms.py
nopassword/locale/es/LC_MESSAGES/django.po
nopassword/migrations/0001_initial.py
nopassword/migrations/0002_auto_20190406_1322.py
nopassword/models.py
nopassword/rest/serializers.py
nopassword/rest/urls.py
nopassword/rest/views.py
nopassword/templates/registration/logged_out.html
nopassword/templates/registration/login_code.html
nopassword/templates/registration/login_email.txt
nopassword/templates/registration/login_form.html
nopassword/templates/registration/login_sms.txt
nopassword/templates/registration/login_subject.txt
nopassword/urls.py
nopassword/views.py
requirements.txt
runtests.py
setup.cfg
setup.py
tests/__init__.py
tests/models.py
tests/settings.py
tests/test_backends.py
tests/test_forms.py
tests/test_models.py
tests/test_rest_views.py
tests/test_views.py
tests/tests.py
tests/urls.py
tox.ini
Commit message: fix: Remove code from database


Vulnerable code:

Fixed code:
version: 2

jobs:
  flake8:
    docker:
      - image: circleci/python:3.6

    steps:
      - checkout
      - run: sudo pip install tox
      - restore_cache:
         keys:
           - v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }}
      - run: tox --notest
      - save_cache:
         key: v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }}
         paths:
           - .tox
      - run: tox -e flake8

  isort:
    docker:
      - image: circleci/python:3.6

    steps:
      - checkout
      - run: sudo pip install tox
      - restore_cache:
         keys:
           - v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }}
      - run: tox --notest
      - save_cache:
         key: v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }}
         paths:
           - .tox
      - run: tox -e isort

  tests:
    docker:
      - image: circleci/python:3.6

    steps:
      - checkout
      - run: sudo pip install tox
      - restore_cache:
         keys:
           - v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }}
      - run: tox --notest
      - save_cache:
         key: v1-tox-{{ checksum "tox.ini" }}-{{ checksum "requirements.txt" }}
         paths:
           - .tox
      - run: tox -e py2-django1_11
      - run: tox -e py3-django1_11
      - run: tox -e py3-django2_0
      - run: tox -e py3-django2_1
      - run: tox -e coverage

workflows:
  version: 2

  build:
    jobs:
      - flake8
      - isort
      - tests
[report]
show_missing = True
exclude_lines =
    pragma: no cover
    raise NotImplementedError
    if __name__ == .__main__.:
    if settings.DEBUG:
    if settings.DEBUG and*:
    if settings.DEBUG or*:

omit =
    nopassword/migrations/*
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover

# Translations
*.mo
*.pot

# Django stuff:
*.log

# Sphinx documentation
docs/_build/

# PyBuilder
target/



tests/local.py
docs/_build/
venv
.python-version
The MIT License (MIT)

Copyright (c) 2013 Rolf Erik Lekang

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
include setup.py README.md MANIFEST.in
recursive-include nopassword/templates *
recursive-include nopassword/static *
# django-nopassword
[![CircleCI](https://circleci.com/gh/relekang/django-nopassword.svg?style=svg)](https://circleci.com/gh/relekang/django-nopassword)

_Authentication backend for django that uses a one time code instead of passwords._

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)

## Installation
Run this command to install django-nopassword

    pip install django-nopassword

### Requirements
Django >= 1.11 (custom user is supported)

## Usage
Add the app to installed apps

```python
INSTALLED_APPS = (
    ...
    'nopassword',
    ...
)
```

Add the authentication backend *EmailBackend*

```python
AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `nopassword`
    'django.contrib.auth.backends.ModelBackend',

    # Send login codes via email
    'nopassword.backends.email.EmailBackend',
)
```

Add urls to your *urls.py*

```python
urlpatterns = patterns('',
    ...
    url(r'^accounts/', include('nopassword.urls')),
    ...
)
```

### REST API

To use the REST API, *djangorestframework* must be installed

    pip install djangorestframework

Add rest framework to installed apps

```python
INSTALLED_APPS = (
    ...
    'rest_framework',
    'rest_framework.authtoken',
    'nopassword',
    ...
)
```

Add *TokenAuthentication* to default authentication classes

```python
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}
```

Add urls to your *urls.py*

```python
urlpatterns = patterns('',
    ...
    url(r'^api/accounts/', include('nopassword.rest.urls')),
    ...
)
```

You will have the following endpoints available:

- `/api/accounts/login/` (POST)
  - username
  - next (optional, will be returned in `/api/accounts/login/code/` to be handled by the frontend)
  - Sends a login code to the user
- `/api/accounts/login/code/` (POST)
  - code
  - Returns `key` (authentication token) and `next` (provided by `/api/accounts/login/`)
- `/api/accounts/logout/` (POST)
  - Performs logout

### Settings
Information about the available settings can be found in the [docs](http://django-nopassword.readthedocs.org/en/latest/#settings)

## Tests
Run with `python setup.py test`.

--------
MIT © Rolf Erik Lekang
# Makefile for Sphinx documentation
#

# You can set these variables from the command line.
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
PAPER         =
BUILDDIR      = _build

# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif

# Internal variables.
PAPEROPT_a4     = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .

.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext

help:
	@echo "Please use \`make <target>' where <target> is one of"
	@echo "  html       to make standalone HTML files"
	@echo "  dirhtml    to make HTML files named index.html in directories"
	@echo "  singlehtml to make a single large HTML file"
	@echo "  pickle     to make pickle files"
	@echo "  json       to make JSON files"
	@echo "  htmlhelp   to make HTML files and a HTML help project"
	@echo "  qthelp     to make HTML files and a qthelp project"
	@echo "  devhelp    to make HTML files and a Devhelp project"
	@echo "  epub       to make an epub"
	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
	@echo "  latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
	@echo "  text       to make text files"
	@echo "  man        to make manual pages"
	@echo "  texinfo    to make Texinfo files"
	@echo "  info       to make Texinfo files and run them through makeinfo"
	@echo "  gettext    to make PO message catalogs"
	@echo "  changes    to make an overview of all changed/added/deprecated items"
	@echo "  xml        to make Docutils-native XML files"
	@echo "  pseudoxml  to make pseudoxml-XML files for display purposes"
	@echo "  linkcheck  to check all external links for integrity"
	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"

clean:
	rm -rf $(BUILDDIR)/*

html:
	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

dirhtml:
	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."

singlehtml:
	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
	@echo
	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."

pickle:
	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
	@echo
	@echo "Build finished; now you can process the pickle files."

json:
	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
	@echo
	@echo "Build finished; now you can process the JSON files."

htmlhelp:
	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
	@echo
	@echo "Build finished; now you can run HTML Help Workshop with the" \
	      ".hhp project file in $(BUILDDIR)/htmlhelp."

qthelp:
	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
	@echo
	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django_nopassword.qhcp"
	@echo "To view the help file:"
	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django_nopassword.qhc"

devhelp:
	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
	@echo
	@echo "Build finished."
	@echo "To view the help file:"
	@echo "# mkdir -p $$HOME/.local/share/devhelp/django_nopassword"
	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django_nopassword"
	@echo "# devhelp"

epub:
	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
	@echo
	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."

latex:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo
	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
	@echo "Run \`make' in that directory to run these through (pdf)latex" \
	      "(use \`make latexpdf' here to do that automatically)."

latexpdf:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo "Running LaTeX files through pdflatex..."
	$(MAKE) -C $(BUILDDIR)/latex all-pdf
	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

latexpdfja:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo "Running LaTeX files through platex and dvipdfmx..."
	$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

text:
	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
	@echo
	@echo "Build finished. The text files are in $(BUILDDIR)/text."

man:
	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
	@echo
	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."

texinfo:
	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo
	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
	@echo "Run \`make' in that directory to run these through makeinfo" \
	      "(use \`make info' here to do that automatically)."

info:
	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo "Running Texinfo files through makeinfo..."
	make -C $(BUILDDIR)/texinfo info
	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."

gettext:
	$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
	@echo
	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."

changes:
	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
	@echo
	@echo "The overview file is in $(BUILDDIR)/changes."

linkcheck:
	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
	@echo
	@echo "Link check complete; look for any errors in the above output " \
	      "or in $(BUILDDIR)/linkcheck/output.txt."

doctest:
	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
	@echo "Testing of doctests in the sources finished, look at the " \
	      "results in $(BUILDDIR)/doctest/output.txt."

xml:
	$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
	@echo
	@echo "Build finished. The XML files are in $(BUILDDIR)/xml."

pseudoxml:
	$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
	@echo
	@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
Changelog
=========

5.0.0
-----

Breaking changes:

- Removed custom length of login codes
- Do not store the code in the database. Hash and compare on login instead. This might have an performance impact.
- Add user id to the login code form and urls sent to the user.
- Changing the secret key will now invalidate all login codes.

4.0.1
-----

Set the default length of codes to 64. The setting ``NOPASSWORD_CODE_LENGTH`` is considered
deprecated.

4.0.0
-----

Added:

- Added ``LoginCodeAdmin``
- Added rest support

Breaking changes:

- Remove support for Django < 1.11
- Add support for Django 2
- ``NoPasswordBackend.authenticate`` doesn't have side effects anymore, it only checks if a login code is valid.
- ``NoPasswordBackend`` now uses the default django method ``user_can_authenticate`` instead of ``verify_user``.
- Changed signature of ``NoPasswordBackend.send_login_code`` to ``send_login_code(code, context, **kwargs)``, to support custom template context.
- ``EmailBackend`` doesn't attach a html message to the email by default. You can provide a template ``registration/login_email.html`` to do so.
- Removed setting ``NOPASSWORD_LOGIN_EMAIL_SUBJECT`` in favor of template ``registration/login_subject.txt``
- Renamed form ``AuthenticationForm`` to ``LoginForm``
- ``LoginForm`` (previously ``AuthenticationForm``) doesn't have side effects anymore while cleaning.
- ``LoginForm`` (previously ``AuthenticationForm``) doesn't check for cookie support anymore.
- Removed methods ``get_user`` and ``get_user_id`` from ``LoginForm`` (previously ``AuthenticationForm``).
- Removed method ``login_url`` and ``send_login_code`` from ``LoginCode`` (previously ``AuthenticationForm``).
- Renamed template ``registration/login.html`` to ``registration/login_form.html``.
- Changed content of default templates.
- Removed views ``login_with_code_and_username``.
- Refactored views to be class based views and to use forms instead of url parameters.
- Changed url paths
- Removed setting ``NOPASSWORD_POST_REDIRECT``, use ``NOPASSWORD_LOGIN_ON_GET`` instead.
- Removed setting ``NOPASSWORD_NAMESPACE``.
- Removed setting ``NOPASSWORD_HIDE_USERNAME``.
- Removed setting ``NOPASSWORD_LOGIN_EMAIL_SUBJECT``.
# -*- coding: utf-8 -*-
#
# django_nopassword documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 27 20:16:47 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# import sys
# import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.doctest',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'django_nopassword'
copyright = u'2014, Rolf Erik Lekang'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.6'
# The full version, including alpha/beta/rc tags.
release = '0.6.0'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False


# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

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

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

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

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

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

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

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

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

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

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

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

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

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

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

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

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

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

# Output file base name for HTML help builder.
htmlhelp_basename = 'django_nopassworddoc'


# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    # 'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    ('index', 'django_nopassword.tex', u'django\\_nopassword Documentation',
     u'Rolf Erik Lekang', 'manual'),
]

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

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

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


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'django_nopassword', u'django_nopassword Documentation',
     [u'Rolf Erik Lekang'], 1)
]

# If true, show URL addresses after external links.
# man_show_urls = False


# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    ('index', 'django_nopassword', u'django_nopassword Documentation',
     u'Rolf Erik Lekang', 'django_nopassword', 'One line description of project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

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

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
.. django_nopassword documentation master file, created by
   sphinx-quickstart on Thu Feb 27 20:16:47 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to django_nopassword's documentation!
=============================================

Authentication backend for django that uses a one time code instead of passwords.

Installation
------------
Run this command to install django-nopassword::

    pip install django-nopassword

Requirements:
Django >= 1.11 (custom user is supported)

.. include:: usage.rst
.. include:: rest.rst
.. include:: settings.rst
.. include:: changelog.rst
REST API
--------
To use the REST API, *djangorestframework* must be installed::

    pip install djangorestframework

Add rest framework to installed apps::

    INSTALLED_APPS = (
        ...
        'rest_framework',
        'rest_framework.authtoken',
        'nopassword',
        ...
    )

Add *TokenAuthentication* to default authentication classes::

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
        )
    }

Add urls to your *urls.py*::

    urlpatterns = patterns('',
        ...
        url(r'^api/accounts/', include('nopassword.rest.urls')),
        ...
    )

You will have the following endpoints available:

- `/api/accounts/login/` (POST)
   - username
   - next (optional, will be returned in ``/api/accounts/login/code/`` to be handled by the frontend)
   - Sends a login code to the user
- `/api/accounts/login/code/` (POST)
   - code
   - Returns ``key`` (authentication token) and ``next`` (provided by ``/api/accounts/login/``)
- `/api/accounts/logout/` (POST)
   - Performs logout
Settings
--------

django-nopassword settings

.. currentmodule:: django.conf.settings

.. attribute:: NOPASSWORD_LOGIN_CODE_TIMEOUT

    Default: ``900``

    Defines how long a login code is valid in seconds.

.. attribute:: NOPASSWORD_HASH_ALGORITHM

    Default: ``'sha256'``

    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'.

.. attribute:: NOPASSWORD_LOGIN_ON_GET

    Default: ``False``

    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``.

.. attribute:: NOPASSWORD_TWILIO_SID

    Account ID for Twilio.

.. attribute:: NOPASSWORD_TWILIO_AUTH_TOKEN

    Account secret for Twilio

.. attribute:: NOPASSWORD_NUMERIC_CODES

    Default: ``False``

    A boolean flag if set to True, codes will contain numeric characters only (0-9).

Django settings used in django-nopassword

.. attribute:: DEFAULT_FROM_EMAIL

    Default: ``'root@example.com'``
Usage
-----
Add the app to installed apps::

    INSTALLED_APPS = (
        'nopassword',
    )

Add the authentication backend *EmailBackend*::

    AUTHENTICATION_BACKENDS = (
        # Needed to login by username in Django admin, regardless of `nopassword`
        'django.contrib.auth.backends.ModelBackend',

        # Send login codes via email
        'nopassword.backends.email.EmailBackend',
    )

Add urls to your *urls.py*::

    urlpatterns = patterns('',
        url(r'^accounts/', include('nopassword.urls')),
    )

Backends
There are several predefined backends. Usage of those backends are listed below.

.. currentmodule:: nopassword.backends.email

.. class:: EmailBackend
Delivers the code by email. It uses the django send email functionality to send
the emails.

Override the following templates to customize emails:

- ``registration/login_email.txt`` - Plain text message
- ``registration/login_email.html`` - HTML message (note that no default html message is attached)
- ``registration/login_subject.txt`` - Subject

.. currentmodule:: nopassword.backends.sms

.. class:: TwilioBackend
Delivers the code by sms sent through the twilio service.

Override the following template to customize messages:

- ``registration/login_sms.txt`` - SMS message


Custom backends
~~~~~~~~~~~~~~~
In backends.py there is a *NoPasswordBackend*, from which it is possible
to build custom backends. The *EmailBackend* described above inherits from
this backend. Creating your own backend can be done by creating a subclass
of *NoPasswordBackend* and implementing *send_login_code*.::

    class CustomBackend(NoPasswordBackend):
    
        def send_login_code(self, code, context, **kwargs):
            """
            Use code.user to get contact information
            Use context to render a custom template
            Use kwargs in case you have a custom view that provides additional configuration
            """
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)
__version__ = '4.0.1'
# -*- coding: utf-8 -*-
from django.contrib import admin

from nopassword import models


@admin.register(models.LoginCode)
class LoginCodeAdmin(admin.ModelAdmin):
    list_display = ('code', 'user', 'timestamp')
    ordering = ('-timestamp',)
    readonly_fields = ('code', 'user', 'timestamp', 'next')
# -*- coding: utf-8 -*-
from .email import EmailBackend  # noqa

try:
    from .sms import TwilioBackend  # noqa
except ImportError:  # pragma: no cover
    pass
# -*- coding: utf-8 -*-
from datetime import timedelta

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.utils import timezone

from nopassword.models import LoginCode


class NoPasswordBackend(ModelBackend):

    def authenticate(self, request, username=None, code=None, **kwargs):
        if username is None:
            username = kwargs.get(get_user_model().USERNAME_FIELD)

        if not username or not code:
            return

        try:
            user = get_user_model()._default_manager.get_by_natural_key(username)

            if not self.user_can_authenticate(user):
                return

            timeout = getattr(settings, 'NOPASSWORD_LOGIN_CODE_TIMEOUT', 900)
            timestamp = timezone.now() - timedelta(seconds=timeout)

            # We don't delete the login code when authenticating,
            # as that is done during validation of the login form
            # and validation should not have any side effects.
            # It is the responsibility of the view/form to delete the token
            # as soon as the login was successful.

            for c in LoginCode.objects.filter(user=user, timestamp__gt=timestamp):
                if c.code == code:
                    user.login_code = c
                    return user
            return

        except (get_user_model().DoesNotExist, LoginCode.DoesNotExist):
            return

    def send_login_code(self, code, context, **kwargs):
        raise NotImplementedError
# -*- coding: utf-8 -*-
from django.core.mail import EmailMultiAlternatives
from django.template.exceptions import TemplateDoesNotExist
from django.template.loader import render_to_string

from nopassword.backends.base import NoPasswordBackend


class EmailBackend(NoPasswordBackend):
    template_name = 'registration/login_email.txt'
    html_template_name = 'registration/login_email.html'
    subject_template_name = 'registration/login_subject.txt'
    from_email = None

    def send_login_code(self, code, context, **kwargs):
        to_email = code.user.email
        subject = render_to_string(self.subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = render_to_string(self.template_name, context)

        email_message = EmailMultiAlternatives(subject, body, self.from_email, [to_email])

        try:
            html_email = render_to_string(self.html_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')
        except TemplateDoesNotExist:
            pass

        email_message.send()
# -*- coding: utf-8 -*-
from django.conf import settings
from django.template.loader import render_to_string
from twilio.rest import TwilioRestClient

from nopassword.backends.base import NoPasswordBackend


class TwilioBackend(NoPasswordBackend):
    template_name = 'registration/login_sms.txt'
    from_number = None

    def __init__(self):
        self.twilio_client = TwilioRestClient(
            settings.NOPASSWORD_TWILIO_SID,
            settings.NOPASSWORD_TWILIO_AUTH_TOKEN
        )
        super(TwilioBackend, self).__init__()

    def send_login_code(self, code, context, **kwargs):
        """
        Send a login code via SMS
        """
        from_number = self.from_number or getattr(settings, 'DEFAULT_FROM_NUMBER')
        sms_content = render_to_string(self.template_name, context)

        self.twilio_client.messages.create(
            to=code.user.phone_number,
            from_=from_number,
            body=sms_content
        )
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth import authenticate, get_backends, get_user_model
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import resolve_url
from django.utils.translation import ugettext_lazy as _

from nopassword import models


class LoginForm(forms.Form):
    error_messages = {
        'invalid_username': _(
            "Please enter a correct %(username)s. "
            "Note that it is case-sensitive."
        ),
        'inactive': _("This account is inactive."),
    }

    next = forms.CharField(max_length=200, required=False, widget=forms.HiddenInput)

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)

        self.username_field = get_user_model()._meta.get_field(get_user_model().USERNAME_FIELD)
        self.fields['username'] = self.username_field.formfield()

    def clean_username(self):
        username = self.cleaned_data['username']

        try:
            user = get_user_model()._default_manager.get_by_natural_key(username)
        except get_user_model().DoesNotExist:
            raise forms.ValidationError(
                self.error_messages['invalid_username'],
                code='invalid_username',
                params={'username': self.username_field.verbose_name},
            )

        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

        self.cleaned_data['user'] = user

        return username

    def save(self, request, login_code_url='login_code', domain_override=None, extra_context=None):
        login_code = models.LoginCode.create_code_for_user(
            user=self.cleaned_data['user'],
            next=self.cleaned_data['next'],
        )

        if not domain_override:
            current_site = get_current_site(request)
            site_name = current_site.name
            domain = current_site.domain
        else:
            site_name = domain = domain_override

        url = '{}://{}{}?user={}&code={}'.format(
            'https' if request.is_secure() else 'http',
            domain,
            resolve_url(login_code_url),
            login_code.user.pk,
            login_code.code,
        )

        context = {
            'domain': domain,
            'site_name': site_name,
            'code': login_code.code,
            'url': url,
        }

        if extra_context:
            context.update(extra_context)

        self.send_login_code(login_code, context)

        return login_code

    def send_login_code(self, login_code, context, **kwargs):
        for backend in get_backends():
            if hasattr(backend, 'send_login_code'):
                backend.send_login_code(login_code, context, **kwargs)
                break
        else:
            raise ImproperlyConfigured(
                'Please add a nopassword authentication backend to settings, '
                'e.g. `nopassword.backends.EmailBackend`'
            )


class LoginCodeForm(forms.Form):
    user = forms.CharField()
    code = forms.CharField(
        label=_('Login code'),
        error_messages={
            'invalid_choice': _('Login code is invalid. It might have expired.'),
        },
    )

    error_messages = {
        'invalid_code': _("Unable to log in with provided login code."),
    }

    def __init__(self, request=None, *args, **kwargs):
        super(LoginCodeForm, self).__init__(*args, **kwargs)

        self.request = request

    def clean(self):
        user_id = self.cleaned_data.get('user', None)
        if user_id is None:
            raise forms.ValidationError(
                self.error_messages['invalid_code'],
                code='invalid_code',
            )

        user = get_user_model().objects.get(pk=user_id)
        code = self.cleaned_data['code']
        user = authenticate(self.request, **{
            get_user_model().USERNAME_FIELD: user.username,
            'code': code,
        })

        if not user:
            raise forms.ValidationError(
                self.error_messages['invalid_code'],
                code='invalid_code',
            )

        self.cleaned_data['user'] = user

        return self.cleaned_data

    def get_user(self):
        return self.cleaned_data.get('user')

    def save(self):
        if self.get_user().login_code:
            self.get_user().login_code.delete()
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# Alejandro Varas <a.varas@tucarga.cl>, 2014.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2014-01-06 09:05-0300\n"
"PO-Revision-Date: 2014-01-06 09:07-0300\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: forms.py:15
msgid "Username"
msgstr "Nombre de usuario"

#: forms.py:18
msgid ""
"Please enter a correct username and password. Note that both fields are case-"
"sensitive."
msgstr ""
"Por favor, introduce un nombre de usuario y clave correctos. Observa que "
"ambos campos pueden ser sensibles a mayúsculas"

#: forms.py:20
msgid ""
"Your Web browser doesn't appear to have cookies enabled. Cookies are "
"required for logging in."
msgstr ""
"Su navegador no parece tener las cookies habilitadas. Las cookies se "
"necesitan para poder ingresar"

#: forms.py:22
msgid "This account is inactive."
msgstr "Esta cuenta está inactiva."

#: models.py:17
msgid "user"
msgstr "usuario"

#: models.py:18
msgid "code"
msgstr "código"

#: models.py:45
msgid "Login code"
msgstr "Código de inicio de sesión"

#: templates/registration/login.html:10
msgid "Login"
msgstr "Iniciar sesión"

#: templates/registration/login_email.html:1
#: templates/registration/login_email.txt:1
msgid "Login with this url "
msgstr "Iniciar sesión con esta url"

#: templates/registration/sent_mail.html:1
msgid "We sent you a mail with a login link"
msgstr "Le enviamos un correo electronico con un link para iniciar sesión"
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='LoginCode',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID',
                 auto_created=True)),
                ('code', models.CharField(editable=False, verbose_name='code', max_length=20)),
                ('timestamp', models.DateTimeField(editable=False)),
                ('next', models.TextField(blank=True, editable=False)),
                ('user', models.ForeignKey(related_name='login_codes', verbose_name='user',
                 to=settings.AUTH_USER_MODEL, editable=False, on_delete=models.CASCADE)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]
# Generated by Django 2.2 on 2019-04-06 13:22

import uuid

from django.db import migrations, models


class Migration(migrations.Migration):
    dependencies = [
        ('nopassword', '0001_initial'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='logincode',
            name='code',
        ),
        migrations.AlterField(
            model_name='logincode',
            name='id',
            field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True,
                                   serialize=False),
        ),
    ]
# -*- coding: utf-8 -*-
import hashlib
import uuid

from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _


class LoginCode(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='login_codes',
                             editable=False, verbose_name=_('user'), on_delete=models.CASCADE)
    timestamp = models.DateTimeField(editable=False)
    next = models.TextField(editable=False, blank=True)

    def __str__(self):
        return "%s - %s" % (self.user, self.timestamp)

    @property
    def code(self):
        hash_algorithm = getattr(settings, 'NOPASSWORD_HASH_ALGORITHM', 'sha256')
        m = getattr(hashlib, hash_algorithm)()
        m.update(getattr(settings, 'SECRET_KEY', None).encode('utf-8'))
        m.update(str(self.id).encode())
        if getattr(settings, 'NOPASSWORD_NUMERIC_CODES', False):
            hashed = str(int(m.hexdigest(), 16))
        else:
            hashed = m.hexdigest()
        return hashed

    def save(self, *args, **kwargs):
        self.timestamp = timezone.now()

        if not self.next:
            self.next = '/'

        super(LoginCode, self).save(*args, **kwargs)

    @classmethod
    def create_code_for_user(cls, user, next=None):
        if not user.is_active:
            return None

        login_code = LoginCode(user=user)
        if next is not None:
            login_code.next = next
        login_code.save()
        return login_code
# -*- coding: utf-8 -*-
from rest_framework import serializers
from rest_framework.authtoken.models import Token

from nopassword import forms


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    next = serializers.CharField(required=False, allow_null=True)

    form_class = forms.LoginForm

    def validate(self, data):
        self.form = self.form_class(data=self.initial_data)

        if not self.form.is_valid():
            raise serializers.ValidationError(self.form.errors)

        return self.form.cleaned_data

    def save(self):
        request = self.context.get('request')
        return self.form.save(request=request)


class LoginCodeSerializer(serializers.Serializer):
    code = serializers.CharField()

    form_class = forms.LoginCodeForm

    def validate(self, data):
        request = self.context.get('request')

        self.form = self.form_class(data=self.initial_data, request=request)

        if not self.form.is_valid():
            raise serializers.ValidationError(self.form.errors)

        return self.form.cleaned_data

    def save(self):
        self.form.save()


class TokenSerializer(serializers.ModelSerializer):

    class Meta:
        model = Token
        fields = ('key',)
# -*- coding: utf-8 -*-
from django.conf.urls import url

from nopassword.rest import views

urlpatterns = [
    url(r'^login/$', views.LoginView.as_view(), name='rest_login'),
    url(r'^login/code/$', views.LoginCodeView.as_view(), name='rest_login_code'),
    url(r'^logout/$', views.LogoutView.as_view(), name='rest_logout'),
]
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth import login as django_login
from django.contrib.auth import logout as django_logout
from django.core.exceptions import ObjectDoesNotExist
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from nopassword.rest import serializers


class LoginView(GenericAPIView):
    serializer_class = serializers.LoginSerializer
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(
            {"detail": _("Login code has been sent.")},
            status=status.HTTP_200_OK
        )


@method_decorator(sensitive_post_parameters('code'), 'dispatch')
class LoginCodeView(GenericAPIView):
    permission_classes = (AllowAny,)
    serializer_class = serializers.LoginCodeSerializer
    token_serializer_class = serializers.TokenSerializer
    token_model = Token

    def process_login(self):
        django_login(self.request, self.user)

    def login(self):
        self.user = self.serializer.validated_data['user']
        self.token, created = self.token_model.objects.get_or_create(user=self.user)

        if getattr(settings, 'REST_SESSION_LOGIN', True):
            self.process_login()

    def get_response(self):
        token_serializer = self.token_serializer_class(
            instance=self.token,
            context=self.get_serializer_context(),
        )
        data = token_serializer.data
        data['next'] = self.serializer.validated_data['user'].login_code.next
        return Response(data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        self.serializer = self.get_serializer(data=request.data)
        self.serializer.is_valid(raise_exception=True)
        self.serializer.save()
        self.login()
        return self.get_response()


class LogoutView(APIView):
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        return self.logout(request)

    def logout(self, request):
        try:
            request.user.auth_token.delete()
        except (AttributeError, ObjectDoesNotExist):
            pass

        django_logout(request)

        return Response(
            {"detail": _("Successfully logged out.")},
            status=status.HTTP_200_OK,
        )
{% load i18n %}

<!doctype html>
<html>
    <body>
        {% trans "Thanks for spending some quality time with the Web site today." %}
    </body>
</html>
{% load i18n %}

<!doctype html>
<html>
    <body>
        <form method="post">
            {% csrf_token %}

	    <p>
                {% trans "Please enter the login code that was sent to you." %}
	    </p>

            {{ form }}

            <button>{% trans "Login" %}</button>
        </form>
    </body>
</html>
{% load i18n %}{% autoescape off %}
{% blocktrans %}You're receiving this email because you requested a login code for your user account at {{ site_name }}.{% endblocktrans %}

{% trans "Please enter the following code for sign in:" %}
{{ code }}

{% trans "You can also follow this link to sign in automatically:" %}
{{ url }}

{% trans "Thanks for using our site!" %}

{% blocktrans %}The {{ site_name }} team{% endblocktrans %}

{% endautoescape %}
{% load i18n %}

<!doctype html>
<html>
    <body>
        <form method="post">
            {% csrf_token %}
            {{ form }}
	    <button>{% trans "Submit" %}</button>
        </form>
    </body>
</html>
{% load i18n %}{% trans "Login with this url " %}{{ url }}
{% load i18n %}{% autoescape off %}
{% blocktrans %}Login code request on {{ site_name }}{% endblocktrans %}
{% endautoescape %}
# -*- coding: utf8 -*-
from django.conf.urls import url

from nopassword import views

urlpatterns = [
    url(r'^login/$', views.LoginView.as_view(), name='login'),
    url(r'^login/code/$', views.LoginCodeView.as_view(), name='login_code'),
    url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
]
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.views import LoginView as DjangoLoginView
from django.contrib.auth.views import LogoutView as DjangoLogoutView
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.views.generic.edit import FormView

from nopassword import forms


class LoginView(FormView):
    """
    Sends a login code to the user.
    It doesn't authenticate a user but it is the entry point for the login process (login url).
    """

    form_class = forms.LoginForm
    success_url = reverse_lazy('login_code')
    template_name = 'registration/login_form.html'

    @method_decorator(csrf_protect)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginView, self).dispatch(request, *args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super(LoginView, self).get_form_kwargs()
        kwargs['initial'] = {'next': self.request.GET.get('next')}
        return kwargs

    def form_valid(self, form):
        form.save(request=self.request)
        return super(LoginView, self).form_valid(form)


class LoginCodeView(DjangoLoginView):
    """
    Authenticates a user with a login code.
    """

    form_class = forms.LoginCodeForm
    template_name = 'registration/login_code.html'

    def get(self, request, *args, **kwargs):
        if 'code' in self.request.GET and getattr(settings, 'NOPASSWORD_LOGIN_ON_GET', False):
            return super(LoginCodeView, self).post(request, *args, **kwargs)
        return super(LoginCodeView, self).get(request, *args, **kwargs)

    def form_valid(self, form):
        form.save()
        return super(LoginCodeView, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(LoginCodeView, self).get_form_kwargs()

        if self.request.method == 'GET' and 'code' in self.request.GET:
            kwargs['data'] = self.request.GET

        return kwargs

    def get_redirect_url(self):
        login_code = getattr(self.request.user, 'login_code', None)
        return login_code.next if login_code else ''


class LogoutView(DjangoLogoutView):
    pass
twilio==5.4.0
mock>=1.0
djangorestframework>=3.1.3
coverage
#!/usr/bin/env python
import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'

from django.test.utils import get_runner  # noqa isort:skip
from django.conf import settings  # noqa isort:skip
import django  # noqa isort:skip

if django.VERSION >= (1, 7):
    django.setup()


def runtests():
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(['tests'])
    sys.exit(bool(failures))


if __name__ == '__main__':
    runtests()
[wheel]
universal = 1

[flake8]
max-line-length=100
exclude=docs/conf.py,.tox,tests/local.py

[isort]
line_length = 100
skip = .tox,venv
default_section = THIRDPARTY
known_first_party = nopassword,tests

[semantic_release]
version_variable = nopassword/__init__.py:__version__
major_tag = [major]
minor_tag = [minor]
patch_tag = [patch]
import os
import re
import sys

from setuptools import setup, find_packages

os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'


def _read_long_description():
    try:
        import pypandoc
        return pypandoc.convert('README.md', 'rst')
    except ImportError:
        return None


with open('nopassword/__init__.py', 'r') as fd:
    version = re.search(
        r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
        fd.read(),
        re.MULTILINE
    ).group(1)

try:
    from semantic_release import setup_hook

    setup_hook(sys.argv)
except ImportError:
    pass

setup(
    name="django-nopassword",
    version=version,
    url='http://github.com/relekang/django-nopassword',
    author='Rolf Erik Lekang',
    author_email='me@rolflekang.com',
    description='Authentication backend for django that uses a one time code instead of passwords',
    long_description=_read_long_description(),
    packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    install_requires=[
        'django>=1.11',
    ],
    extras_require={
        'rest': ['djangorestframework>=3.1.3'],
    },
    tests_require=[
        'django>=1.11',
        'twilio==4.4.0',
        'mock>=1.0'
    ],
    license='MIT',
    test_suite='runtests.runtests',
    include_package_data=True,
    classifiers=[
        "Programming Language :: Python",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Framework :: Django",
        "Environment :: Web Environment",
        "Operating System :: OS Independent",
        "Natural Language :: English",
    ]
)
# -*- coding: utf8 -*-
from django.db import models

try:
    from django.contrib.auth.models import AbstractUser, UserManager
except ImportError:
    from django.db.models import Model as AbstractUser


class CustomUser(AbstractUser):
    extra_field = models.CharField(max_length=2)
    new_username_field = models.CharField('userid', unique=True, max_length=20)

    USERNAME_FIELD = 'new_username_field'

    def save(self, *args, **kwargs):
        self.new_username_field = self.username
        super(CustomUser, self).save(*args, **kwargs)


class PhoneNumberUser(CustomUser):
    phone_number = models.CharField(max_length=11, default="+15555555")


class NoUsernameUser(models.Model):
    """User model without a "username" field for authentication
    backend testing
    """
    pass
# -*- coding: utf8 -*-
import os

import django

DEBUG = True

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.environ.get('DB_NAME', ':memory:'),
    }
}

AUTH_USER_MODEL = 'tests.CustomUser'

NOPASSWORD_LOGIN_CODE_TIMEOUT = 900

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',

    'rest_framework',
    'rest_framework.authtoken',

    'nopassword',
    'tests',
]
AUTHENTICATION_BACKENDS = (
    'nopassword.backends.EmailBackend',
    'django.contrib.auth.backends.ModelBackend'
)

TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

SECRET_KEY = 'supersecret'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages'
            ],
        },
    },
]

MIDDLEWARE = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

if django.VERSION < (1, 10):
    MIDDLEWARE_CLASSES = MIDDLEWARE

ROOT_URLCONF = 'tests.urls'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
}
# -*- coding: utf8 -*-
from django.contrib.auth import authenticate, get_user_model
from django.test import TestCase
from django.test.utils import mail, override_settings
from mock import MagicMock, patch

from nopassword.backends.base import NoPasswordBackend
from nopassword.backends.email import EmailBackend
from nopassword.backends.sms import TwilioBackend
from nopassword.models import LoginCode


class AuthenticationBackendTests(TestCase):

    @override_settings(AUTH_USER_MODULE='tests.NoUsernameUser')
    def test_authenticate_with_custom_user_model(self):
        """When a custom user model is used that doesn't have a field
        called "username" return `None`
        """
        result = authenticate(username='username')
        self.assertIsNone(result)


@override_settings(AUTH_USER_MODEL='tests.PhoneNumberUser', NOPASSWORD_TWILIO_SID="aaaaaaaa",
                   NOPASSWORD_TWILIO_AUTH_TOKEN="bbbbbbbb", DEFAULT_FROM_NUMBER="+15555555")
class TwilioBackendTests(TestCase):

    def setUp(self):
        self.user = get_user_model().objects.create(username='twilio_user')
        self.code = LoginCode.create_code_for_user(self.user, next='/secrets/')
        self.assertEqual(len(self.code.code), 64)
        self.assertIsNotNone(authenticate(username=self.user.username, code=self.code.code))

    @patch('nopassword.backends.sms.TwilioRestClient')
    def test_twilio_backend(self, mock_object):
        self.backend = TwilioBackend()
        self.backend.twilio_client.messages.create = MagicMock()
        self.backend.send_login_code(self.code, {'url': 'https://example.com'})
        self.assertTrue(mock_object.called)
        self.assertTrue(self.backend.twilio_client.messages.create.called)
        _, kwargs = self.backend.twilio_client.messages.create.call_args
        self.assertIn('https://example.com', kwargs.get('body'))


class EmailBackendTests(TestCase):

    def setUp(self):
        self.user = get_user_model().objects.create(
            username='email_user',
            email='nopassword@example.com',
        )
        self.code = LoginCode.create_code_for_user(self.user, next='/secrets/')
        self.backend = EmailBackend()

    def test_email_backend(self):
        "Send email via EmailBackend with default options"
        self.backend.send_login_code(self.code, {'url': 'https://example.com'})
        self.assertEqual(1, len(mail.outbox))
        message = mail.outbox[0]
        self.assertIn('https://example.com', message.body)
        self.assertEqual([self.user.email], message.to)
        self.assertEqual(0, len(message.alternatives))

    def test_html_template_name(self):
        # We don't have an existing html template, so we just use the txt template
        self.backend.html_template_name = 'registration/login_email.txt'
        self.backend.send_login_code(self.code, {'url': 'https://example.com'})
        self.assertEqual(1, len(mail.outbox))
        message = mail.outbox[0]
        self.assertIn('https://example.com', message.body)
        self.assertEqual(1, len(message.alternatives))
        self.assertIn('https://example.com', message.alternatives[0][0])


class TestBackendUtils(TestCase):

    def test_send_login_code(self):
        backend = NoPasswordBackend()
        self.assertRaises(NotImplementedError, backend.send_login_code, code=None, context=None)
# -*- coding: utf8 -*-
from django.contrib.auth import get_user_model
from django.core.exceptions import ImproperlyConfigured
from django.test import RequestFactory, TestCase, override_settings
from mock import MagicMock

from nopassword import forms


class TestLoginForm(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.user = get_user_model().objects.create(username='user')

    def test_domain_override(self):
        request = self.factory.post('/accounts/login/', {
            'username': 'user',
        })
        form = forms.LoginForm(data=request.POST)
        form.send_login_code = MagicMock()

        self.assertTrue(form.is_valid())

        form.save(request, domain_override='foobar.com')

        self.assertTrue(form.send_login_code.called)
        (login_code, context), _ = form.send_login_code.call_args
        self.assertIn('http://foobar.com', context['url'])

    def test_extra_context(self):
        request = self.factory.post('/accounts/login/', {
            'username': 'user',
        })
        form = forms.LoginForm(data=request.POST)
        form.send_login_code = MagicMock()

        self.assertTrue(form.is_valid())

        form.save(request, extra_context={'foo': 'bar'})

        self.assertTrue(form.send_login_code.called)
        (login_code, context), _ = form.send_login_code.call_args
        self.assertTrue('url' in context)
        self.assertEqual('bar', context['foo'])

    @override_settings(
        AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.ModelBackend'],
    )
    def test_missing_backend(self):
        form = forms.LoginForm()
        self.assertRaises(ImproperlyConfigured, form.send_login_code, None, None)
# -*- coding: utf8 -*-
import time
from datetime import datetime

from django.contrib.auth import authenticate, get_user_model
from django.test import TestCase
from django.test.utils import override_settings

from nopassword.models import LoginCode


class TestLoginCodes(TestCase):

    def setUp(self):
        self.user = get_user_model().objects.create(username='test_user')
        self.inactive_user = get_user_model().objects.create(username='inactive', is_active=False)
        self.code = LoginCode.create_code_for_user(self.user)

    def tearDown(self):
        LoginCode.objects.all().delete()

    def test_login_backend(self):
        self.assertEqual(len(self.code.code), 64)
        self.assertIsNotNone(authenticate(username=self.user.username, code=self.code.code))
        self.assertIsNone(LoginCode.create_code_for_user(self.inactive_user))

    @override_settings(NOPASSWORD_NUMERIC_CODES=True)
    def test_numeric_code(self):
        code = LoginCode.create_code_for_user(self.user)
        self.assertGreater(len(code.code), 64)
        self.assertTrue(code.code.isdigit())

    def test_next_value(self):
        code = LoginCode.create_code_for_user(self.user, next='/secrets/')
        self.assertEqual(code.next, '/secrets/')

    @override_settings(NOPASSWORD_LOGIN_CODE_TIMEOUT=1)
    def test_code_timeout(self):
        timeout_code = LoginCode.create_code_for_user(self.user)
        time.sleep(3)
        self.assertIsNone(authenticate(username=self.user.username, code=timeout_code.code))

    def test_str(self):
        code = LoginCode(user=self.user, timestamp=datetime(2018, 7, 1))
        self.assertEqual(str(code), 'test_user - 2018-07-01 00:00:00')
# -*- coding: utf8 -*-
from django.contrib.auth import get_user_model
from django.core import mail
from django.test import TestCase
from rest_framework.authtoken.models import Token

from nopassword.models import LoginCode


class TestRestViews(TestCase):

    def setUp(self):
        self.user = get_user_model().objects.create(username='user', email='foo@bar.com')

    def test_request_login_code(self):
        response = self.client.post('/accounts-rest/login/', {
            'username': self.user.username,
            'next': '/private/',
        })

        self.assertEqual(response.status_code, 200)

        login_code = LoginCode.objects.filter(user=self.user).first()

        self.assertIsNotNone(login_code)
        self.assertEqual(login_code.next, '/private/')
        self.assertEqual(len(mail.outbox), 1)
        self.assertIn(
            'http://testserver/accounts/login/code/?user={}&code={}'.format(
                login_code.user.pk,
                login_code.code
            ),
            mail.outbox[0].body,
        )

    def test_request_login_code_missing_username(self):
        response = self.client.post('/accounts-rest/login/')

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(), {
            'username': ['This field is required.'],
        })

    def test_request_login_code_unknown_user(self):
        response = self.client.post('/accounts-rest/login/', {
            'username': 'unknown',
        })

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(), {
            'username': ['Please enter a correct userid. Note that it is case-sensitive.'],
        })

    def test_request_login_code_inactive_user(self):
        self.user.is_active = False
        self.user.save()

        response = self.client.post('/accounts-rest/login/', {
            'username': self.user.username,
        })

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(), {
            'username': ['This account is inactive.'],
        })

    def test_login(self):
        login_code = LoginCode.objects.create(user=self.user, next='/private/')

        response = self.client.post('/accounts-rest/login/code/', {
            'user': login_code.user.pk,
            'code': login_code.code,
        })

        self.assertEqual(response.status_code, 200)
        self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists())

        token = Token.objects.filter(user=self.user).first()

        self.assertIsNotNone(token)
        self.assertEqual(response.data, {
            'key': token.key,
            'next': '/private/',
        })

    def test_login_missing_code(self):
        response = self.client.post('/accounts-rest/login/code/')

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(), {
            'code': ['This field is required.'],
        })

    def test_login_unknown_code(self):
        response = self.client.post('/accounts-rest/login/code/', {
            'code': 'unknown',
        })

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(), {
            '__all__': ['Unable to log in with provided login code.'],
            'user': ['This field is required.']
        })

    def test_login_inactive_user(self):
        self.user.is_active = False
        self.user.save()

        login_code = LoginCode.objects.create(user=self.user)

        response = self.client.post('/accounts-rest/login/code/', {
            'code': login_code.code,
        })

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(), {
            '__all__': ['Unable to log in with provided login code.'],
            'user': ['This field is required.']
        })

    def test_logout(self):
        token = Token.objects.create(user=self.user, key='foobar')

        response = self.client.post(
            '/accounts-rest/logout/',
            HTTP_AUTHORIZATION='Token {}'.format(token.key),
        )

        self.assertEqual(response.status_code, 200)
        self.assertFalse(Token.objects.filter(user=self.user).exists())

    def test_logout_unknown_token(self):
        login_code = LoginCode.objects.create(user=self.user)

        self.client.login(username=self.user.username, code=login_code.code)

        response = self.client.post(
            '/accounts-rest/logout/',
            HTTP_AUTHORIZATION='Token unknown',
        )

        self.assertEqual(response.status_code, 200)
# -*- coding: utf8 -*-
from django.contrib.auth import get_user_model
from django.core import mail
from django.test import TestCase, override_settings

from nopassword.models import LoginCode


class TestViews(TestCase):

    def setUp(self):
        self.user = get_user_model().objects.create(username='user', email='foo@bar.com')

    def test_request_login_code(self):
        response = self.client.post('/accounts/login/', {
            'username': self.user.username,
            'next': '/private/',
        })

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '/accounts/login/code/')

        login_code = LoginCode.objects.filter(user=self.user).first()

        self.assertIsNotNone(login_code)
        self.assertEqual(login_code.next, '/private/')
        self.assertEqual(len(mail.outbox), 1)
        self.assertIn(
            'http://testserver/accounts/login/code/?user={}&code={}'.format(
                login_code.user.pk,
                login_code.code
            ),
            mail.outbox[0].body,
        )

    def test_request_login_code_missing_username(self):
        response = self.client.post('/accounts/login/')

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['form'].errors, {
            'username': ['This field is required.'],
        })

    def test_request_login_code_unknown_user(self):
        response = self.client.post('/accounts/login/', {
            'username': 'unknown',
        })

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['form'].errors, {
            'username': ['Please enter a correct userid. Note that it is case-sensitive.'],
        })

    def test_request_login_code_inactive_user(self):
        self.user.is_active = False
        self.user.save()

        response = self.client.post('/accounts/login/', {
            'username': self.user.username,
        })

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['form'].errors, {
            'username': ['This account is inactive.'],
        })

    def test_login_post(self):
        login_code = LoginCode.objects.create(user=self.user, next='/private/')

        response = self.client.post('/accounts/login/code/', {
            'user': login_code.user.pk,
            'code': login_code.code,
        })

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '/private/')
        self.assertEqual(response.wsgi_request.user, self.user)
        self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists())

    def test_login_get(self):
        login_code = LoginCode.objects.create(user=self.user)

        response = self.client.get('/accounts/login/code/', {
            'user': login_code.user.pk,
            'code': login_code.code,
        })

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['form'].cleaned_data['code'], login_code.code)
        self.assertTrue(response.wsgi_request.user.is_anonymous)
        self.assertTrue(LoginCode.objects.filter(pk=login_code.pk).exists())

    @override_settings(NOPASSWORD_LOGIN_ON_GET=True)
    def test_login_get_non_idempotent(self):
        login_code = LoginCode.objects.create(user=self.user, next='/private/')

        response = self.client.get('/accounts/login/code/', {
            'user': login_code.user.pk,
            'code': login_code.code,
        })

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '/private/')
        self.assertEqual(response.wsgi_request.user, self.user)
        self.assertFalse(LoginCode.objects.filter(pk=login_code.pk).exists())

    def test_login_missing_code_post(self):
        response = self.client.post('/accounts/login/code/')

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['form'].errors, {
            'user': ['This field is required.'],
            'code': ['This field is required.'],
            '__all__': ['Unable to log in with provided login code.']
        })

    def test_login_missing_code_get(self):
        response = self.client.get('/accounts/login/code/')

        self.assertEqual(response.status_code, 200)
        self.assertFalse(response.context['form'].is_bound)

    def test_login_unknown_code(self):
        response = self.client.post('/accounts/login/code/', {
            'user': 1,
            'code': 'unknown',
        })

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['form'].errors, {
            '__all__': ['Unable to log in with provided login code.'],
        })

    def test_login_inactive_user(self):
        self.user.is_active = False
        self.user.save()

        login_code = LoginCode.objects.create(user=self.user)

        response = self.client.post('/accounts/login/code/', {
            'user': login_code.user.pk,
            'code': login_code.code,
        })

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['form'].errors, {
            '__all__': ['Unable to log in with provided login code.']
        })

    def test_logout_post(self):
        login_code = LoginCode.objects.create(user=self.user)

        self.client.login(username=self.user.username, code=login_code.code)

        response = self.client.post('/accounts/logout/?next=/accounts/login/')

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '/accounts/login/')
        self.assertTrue(response.wsgi_request.user.is_anonymous)

    def test_logout_get(self):
        login_code = LoginCode.objects.create(user=self.user)

        self.client.login(username=self.user.username, code=login_code.code)

        response = self.client.post('/accounts/logout/?next=/accounts/login/')

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '/accounts/login/')
        self.assertTrue(response.wsgi_request.user.is_anonymous)
# -*- coding: utf-8 -*-
import django

if django.VERSION < (1, 6):
    from .test_backends import *  # noqa
    from .test_models import *  # noqa
    from .test_views import *  # noqa
# -*- coding: utf8 -*-
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('nopassword.urls')),
    url(r'^accounts-rest/', include('nopassword.rest.urls')),
]
[tox]
envlist =
    flake8,
    isort,
    py2-{django1_11},
    py3-{django1_11,django2_1,django2_2},
    coverage
skipsdist = True

[testenv]
basepython =
    py3: python3
    py2: python2
setenv =
    PYTHONPATH = {toxinidir}:{toxinidir}
    DB_NAME = :memory:
commands =
    coverage run -p --source=nopassword runtests.py
deps =
    -r{toxinidir}/requirements.txt
    django1_11: Django>=1.11,<1.12
    django2_1: Django>=2.1,<2.2
    django2_2: Django>=2.2,<2.3

[testenv:flake8]
basepython = python3
deps = flake8
commands = flake8

[testenv:isort]
basepython = python3
deps = isort
commands = isort -c -rc nopassword tests

[testenv:coverage]
basepython = python3
deps = coverage
commands = 
    coverage combine
    coverage report 
    coverage xml