pax_global_header 0000666 0000000 0000000 00000000064 14070037163 0014513 g ustar 00root root 0000000 0000000 52 comment=9cf10efc7dedaec9c9b78ab832dbf98fc0d89e72
django-cas-server-1.3.1/ 0000775 0000000 0000000 00000000000 14070037163 0015027 5 ustar 00root root 0000000 0000000 django-cas-server-1.3.1/.coveragerc 0000664 0000000 0000000 00000000476 14070037163 0017157 0 ustar 00root root 0000000 0000000 [run]
branch = True
source = cas_server
omit =
cas_server/migrations*
cas_server/management/*
cas_server/tests/*
cas_server/cas.py
[report]
exclude_lines =
pragma: no cover
def __repr__
def __unicode__
def __str__
raise AssertionError
raise NotImplementedError
if six.PY3:
django-cas-server-1.3.1/.gitignore 0000664 0000000 0000000 00000000250 14070037163 0017014 0 ustar 00root root 0000000 0000000 *.pyc
*.egg-info
*~
*.swp
build/
cas/
dist/
db.sqlite3
manage.py
coverage.xml
docs/_build/
docs/django.inv
.tox
test_venv
.coverage
htmlcov/
tox_logs/
.cache/
.eggs/
django-cas-server-1.3.1/.gitlab-ci.yml 0000664 0000000 0000000 00000003441 14070037163 0017465 0 ustar 00root root 0000000 0000000 before_script:
- pip install tox setuptools
flake8:
image: "python:3.9"
cache:
key: flake8
paths:
- .tox/flake8
script:
- tox -e flake8
check_rst:
image: "python:3.9"
cache:
key: check_rst
paths:
- .tox/check_rst
script:
- tox -e check_rst
py27-django111:
image: "python:2.7"
cache:
key: py27-django111
paths:
- .tox/py27-django111
script:
- tox -e py27-django111
py35-django111:
image: "python:3.5"
cache:
key: py35-django111
paths:
- .tox/py35-django111
script:
- tox -e py35-django111
py36-django111:
image: "python:3.6"
cache:
key: py36-django111
paths:
- .tox/py36-django111
script:
- tox -e py36-django111
py37-django22:
image: "python:3.7"
cache:
key: py37-django22
paths:
- .tox/py37-django22
script:
- tox -e py37-django22
py38-django22:
image: "python:3.8"
cache:
key: py38-django22
paths:
- .tox/py38-django22
script:
- tox -e py38-django22
py38-django30:
image: "python:3.8"
cache:
key: py38-django30
paths:
- .tox/py38-django30
script:
- tox -e py38-django30
py38-django31:
image: "python:3.8"
cache:
key: py38-django31
paths:
- .tox/py38-django31
script:
- tox -e py38-django31
py39-django22:
image: "python:3.9"
cache:
key: py39-django22
paths:
- .tox/py39-django22
script:
- tox -e py39-django22
py39-django30:
image: "python:3.9"
cache:
key: py39-django30
paths:
- .tox/py39-django30
script:
- tox -e py39-django30
py39-django31:
image: "python:3.9"
cache:
key: py39-django31
paths:
- .tox/py39-django31
script:
- tox -e py39-django31
coverage:
image: "python:3.9"
cache:
key: coverage
paths:
- .tox/coverage
script:
- tox -e coverage
django-cas-server-1.3.1/.travis.yml 0000664 0000000 0000000 00000002732 14070037163 0017144 0 ustar 00root root 0000000 0000000 language: python
matrix:
include:
# generic checks
- python: "3.9"
env: TOX_ENV=flake8
- python: "3.9"
env: TOX_ENV=check_rst
- python: "3.9"
env: TOX_ENV=coverage
# Debian strech support
- python: "3.5"
env: TOX_ENV=py35-django111
- python: "3.5"
env: TOX_ENV=py35-django111
arch: ppc64le
# Ubuntu bionic and EPEL 7 support
- python: "3.6"
env: TOX_ENV=py36-django111
- python: "3.6"
env: TOX_ENV=py36-django111
arch: ppc64le
# RHEL 8 support
- python: "3.6"
env: TOX_ENV=py36-django22
- python: "3.6"
env: TOX_ENV=py36-django22
arch: ppc64le
# Debian buster support
- python: "3.7"
env: TOX_ENV=py37-django111
- python: "3.7"
env: TOX_ENV=py37-django111
arch: ppc64le
# Ubuntu focal and Ubuntu groovy support
- python: "3.8"
env: TOX_ENV=py38-django22
- python: "3.8"
env: TOX_ENV=py38-django22
arch: ppc64le
# Debian bullseye and Ubuntu hirsute support
- python: "3.9"
env: TOX_ENV=py39-django22
- python: "3.9"
env: TOX_ENV=py39-django22
arch: ppc64le
# Django additional supported version
- python: "3.9"
env: TOX_ENV=py39-django31
- python: "3.9"
env: TOX_ENV=py39-django32
cache:
directories:
- $HOME/.cache/pip/http/
- $HOME/build/nitmir/django-cas-server/.tox/$TOX_ENV/
install:
- travis_retry pip install setuptools --upgrade
- pip install tox $PKGS
- pip freeze
script:
- tox -e $TOX_ENV
after_script:
- cat tox_log/*.log
django-cas-server-1.3.1/.update_coverage 0000775 0000000 0000000 00000002464 14070037163 0020176 0 ustar 00root root 0000000 0000000 #!/bin/bash
set -x
set -e
BASEDIR="$(realpath "$1")"
PROJECT_NAME="$2"
TITLE="Coverage report of $PROJECT_NAME"
# build by gitlab CI
if [ -n "$CI_BUILD_REF_NAME" ]; then
BRANCH="$CI_BUILD_REF_NAME"
TITLE="$TITLE, $BRANCH branch"
# build by travis
elif [ -n "$TRAVIS_BRANCH" ]; then
# if this a pull request ?
if [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then
BRANCH="pull-request-$TRAVIS_PULL_REQUEST"
TITLE="$TITLE, pull request n°$BRANCH"
else
BRANCH="$TRAVIS_BRANCH"
TITLE="$TITLE, $BRANCH branch"
fi
else
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
TITLE="$TITLE, $BRANCH branch"
fi
if [[ "$BRANCH" = "HEAD" ]] || [ -z "$BRANCH" ]; then
echo "bad branch name '$BRANCH', ignoring it"
exit 0
fi
VENV="$(mktemp -d)"
HTMLREPORT="$(mktemp -d)"
virtualenv -p python3 "$VENV"
"$VENV/bin/pip" install coverage
"$VENV/bin/coverage" html --title "$TITLE" --directory "$HTMLREPORT"
rm -rf "$VENV"
cd "$HTMLREPORT"; tar czf "$BASEDIR/coverage.tar.gz" ./
cd "$BASEDIR"
rm -rf "$HTMLREPORT"
set +x
echo "curl https://badges.genua.fr/coverage/ ..."
curl https://badges.genua.fr/coverage/ \
-F "secret=$COVERAGE_TOKEN" \
-F "tar=@$BASEDIR/coverage.tar.gz" \
-F "project=$PROJECT_NAME" \
-F "branch=$BRANCH"
set -x
rm "$BASEDIR/coverage.tar.gz"
django-cas-server-1.3.1/CHANGELOG.rst 0000664 0000000 0000000 00000042277 14070037163 0017064 0 ustar 00root root 0000000 0000000 Change Log
##########
All notable changes to this project will be documented in this file.
.. contents:: Table of Contents
:depth: 2
v1.3.1 - 2021-07-03
===================
Fixes
-----
* Documentation generation to works with latest Django and sphinx version
* Update classifier and dependencies versions in setup.py
v1.3.0 - 2021-06-19
===================
Added
-----
* Support for Dango 3.1 and 3.2
* Implement CAS_LDAP_ATTRS_VIEW set to 0: then using ldap bind mode, user
attributes can be retreive either using CAS_LDAP_USER or using the
binded user credentials.
* Added ppc64le architecture support on travis-ci (django-cas-server is
included in the ppc64le versions of RHEL and Ubuntu)
* Python 3.9 support
Fixes
-----
* Allow to use user attributes if auth by ldap bind
* Fix spelling mistakes in french translation
* Fix bug model datefield Form (Federated User Admin)
* django.conf.urls is deprecated and will be removed in Django 4.0.
Use django.urls.re_path instead
Removed
-------
* Drop support for Django 3.0 as it reached end of life.
v1.2.0 - 2020-07-05
===================
Added
-----
* Bootstrap 4 templates
* Support for Django 2.2 and 3.0
Fixes
-----
* Replace calls to add_description_unit. As of Sphinx 2.4, the deprecated
add_description_unit function has been removed.
* Fix CRYPT-DES hash method for LDAP
* Fix various spelling miskate in README.rst
* Service URL: keep blank GET arguments
Changed
-------
* Use python3 for flake8, check_rst and coverage
* Update README.rst quickstart for using python3 by default
Removed
-------
* Drop support for Django 2.0 and 2.1 as it reached end of life.
We still keep Django 1.11 as it is the last supported release
by python2 AND the currently packaged version of Django in
Debian Buster (current stable).
v1.1.0 - 2019-03-02
===================
Added
-----
* Support for Django 2.1
Fixes
-----
* Checkbox position on the login page
* Set ldap3 client_strategy from sync to sync-restartable
* Deprecation warning for {% load staticfiles %} and django.contrib.staticfiles
v1.0.0 - 2019-01-12
===================
Added
-----
* Support for python 3.6 and Django 1.11
* Support for Django 2.0
* Keep query string then redirecting from / to /login
Fixes
-----
* Add missing attributes authenticationDate, longTermAuthenticationRequestTokenUsed and
isFromNewLogin from service validation response
* Catch error from calling django.contrib.staticfiles.templatetags.staticfiles.static
in non-debug mode before collectstatic in cas_server.default_settings.py
* Invalid escape sequence in regular expression
Deprecated
----------
* Support for Django <1.11 is dropped, it should still works for this version.
Next versions will most probably be not compatible with Django <1.11
* Support for python 3.4 is dropped, it should still works for this version.
Next versions may or may not works with python 3.4.
Other
-----
* Migrations have been squashed for Django 2.0 support. Be sur to apply all migration before
updating to this version
* Update PyPi url from https://pypi.python.org to https://pypi.org
v0.9.0 - 2017-11-17
===================
Added
-----
* Dutch translation
* Protuguese translation (brazilian variant)
* Support for ldap3 version 2 or more (changes in the API)
All exception are now in ldap3.core.exceptions, methodes for fetching attritutes and
dn are renamed.
* Possibility to disable service message boxes on the login pages
Fixed
-----
* Then using the LDAP auth backend with ``bind`` method for password check, do not try to bind
if the user dn was not found. This was causing the exception
``'NoneType' object has no attribute 'getitem'`` describe in #21
* Increase the max size of usernames (30 chars to 250)
* Fix XSS js injection
v0.8.0 - 2017-03-08
===================
Added
-----
* Add a test for login with missing parameter (username or password or both)
* Add ldap auth using bind method (use the user credentials to bind the the ldap server and let the
server check the credentials)
* Add CAS_TGT_VALIDITY parameter: Max time after with the user MUST reauthenticate.
Fixed
-----
* Allow both unicode and bytes dotted string in utils.import_attr
* Fix some spelling and grammar on log messages. (thanks to Allie Micka)
* Fix froms css class error on success/error due to a scpaless block
* Disable pip cache then installing with make install
Changed
-------
* Update french translation
v0.7.4 - 2016-09-07
===================
Fixed
-----
* Add templatetags to Pypi package
v0.7.3 - 2016-09-07
===================
Added
-----
* Add autofocus to the username input on the login page
Fixed
-----
* Really pick the last version on Pypi for new version checking.
We were only sorting version string lexicographically and it would have break when
we reach version 0.10.N or 0.N.10
* Only check for valid username/password if username and password POST fields are posted.
This fix a bug where posting without it raise a exception are None where passed for
username/password verification.
v0.7.2 - 2016-08-31
===================
Added
-----
* Add Django 1.10 support
* Add support of gitlab continuous integration
Fixed
-----
* Fix BootsrapForm: placeholder on Input and Textarea only, use class form-control on
Input, Select and Textarea.
* Fix lang attribute in django 1.7. On html pages, the lang attribute of the was not
present in django 1.7. We use now a methode to display it that is also available in django 1.7
v0.7.1 - 2016-08-24
===================
Added
-----
* Add a forgotten migration (only change help_text and validators)
v0.7.0 - 2016-08-24
===================
Added
-----
* Add a CHANGELOG.rst file.
* Add a validator to models CharField that should be regular expressions checking that user input
are valids regular expressions.
* Add a CAS_INFO_MESSAGES and CAS_INFO_MESSAGES_ORDER settings allowing to display messages in
info-boxes on the html pages of the default templates.
Changed
-------
* Allow the user defined CAS_COMPONENT_URLS to omit not changed values.
* replace code-block without language indication by literal blocks.
* Update french translation
Fixed
-----
* Some README.rst typos.
* some english typos
v0.6.4 - 2016-08-14
===================
commit: 282e3a831b3c0b0818881c2f16d056850d572b89
Added
-----
* Add a forgotten migration (only change help_text)
v0.6.3 - 2016-08-14
===================
commit: 07a537b403c5c5e39a4ddd084f90e3a4de88a54e
Added
-----
* Add powered by footer
* Add a github version badge
* documents templatetags
Changed
-------
* Usage of the documented API for models _meta in auth.DjangoAuthUser
* set warn cookie using javascript if possible
* Unfold many to many attributes in auth.DjangoAuthUser attributes
Fixed
-----
* typos in README.rst
* w3c validation
Cleaned
-------
* Code factorisation (models.py, views.py)
v0.6.2 - 2016-08-02
===================
commit: 773707e6c3c3fa20f697c946e31cafc591e8fee8
Added
-----
* Support authentication renewal in federate mode
* Add new version email and info box then new version is available
* Add SqlAuthUser and LdapAuthUser auth classes.
Deprecate the usage of MysqlAuthUser in favor of SqlAuthUser.
* Add pytest-warning to tests
* Add a checkbox to forget the identity provider if we checked "remember the identity provider"
* Add dependancies correspondance between python pypi, debian and centos packages in README
Changed
-------
* Move coverage computation last in travis
* Enable logging to stderr then running tests
* Remember "warn me before…" using a cookie
* Put favicon (shortcut icon) URL in settings
Deprecated
----------
* The auth class MysqlAuthUser is deprecated in favor of the SqlAuthUser class.
Fixed
-----
* Use custom templatetags instead settings custom attributes to Boundfields
(As it do not work with django 1.7)
* Display an error message on bad response from identity provider in federate mode
instead of crashing. (e.g. Bad XML document)
* Catch base64 decode error on b64decode to raise our custom exception BadHash
* Add secret as sensitive variables/post parameter for /auth
* Only set "remember my provider" in federated mode upon successful authentication
* Since we drop django-boostrap3 dependancies, Django default minimal version is 1.7.1
* [cas.py] Append renew=true when validating tickets
Cleaned
-------
* code factorization (cas.py, forms.py)
v0.6.1 - 2016-07-27
===================
commit: b168e0a6423c53de31aae6c444fa1d1c5083afa6
Added
-----
* Add sphinx docs + autodoc
* Add the possibility to run tests with "setup.py test"
* Include docs, Makefile, coverage config and tests config to source package
* Add serviceValidate ProxyTicket tests
* Add python 3.5 tox/travis tests
Changed
-------
* Use https://badges.genua.fr for badges
Fixed
-----
* Keep LoginTicket list upon fail authentication
(It prevent the next login attemps to fail because of bad LT)
Cleaned
-------
* Compact federated mode migration
* Reformat default_settings.py for documentation using sphinx autodoc
* Factorize some code (from views.py to Ticket models class methods)
* Update urlpattern for django 1.10
* Drop dependancies django-picklefield and django-bootstrap3
v0.6.0 - 2016-07-06
===================
commit: 4ad4d13baa4236c5cd72cc5216d7ff08dd361476
Added
-----
* Add a section describing service patterns options to README.rst
* Add a federation mode:
When the settings CAS_FEDERATE is True, django-cas-server will offer to the user to choose its
CAS backend to authenticate. Hence the login page do not display anymore a username/password form
but a select form with configured CASs backend.
This allow to give access to CAS supported applications to users from multiple organization
seamlessly.
It was originally developped to mach the need of https://ares.fr (Federated CAS at
https://cas.ares.fr, example of an application using it as https://chat.myares.fr)
Fixed
-----
* Then a ticket was marked as obtained with the user entering its credentials (aka not by SSO), and
the service did not require it, ticket validation was failing. Now, if the service do not require
authentication to be renewed, both ticket with renewed authentication and non renewed
authentication validate successfully.
v0.5.0 - 2016-07-01
===================
commit: e3ab64271b718a17e4cbbbabda0a2453107a83df
Added
-----
* Add more password scheme support to the mysql authentication backend: ldap user
attribute scheme encoding and simple password hash in hexa for md5, sha1, sha224,
sha256, sha384, sha512.
* Add a main heading to template "Central Authentication Service" with a logo controled
by CAS_LOGO_URL
* Add logos to the project (svg, png)
* Add coverage computation
* link project to codacy
* Update doc: add debian requirement, correct typos, correct links
Changed
-------
* Use settings to set tests username password and attributes
* Tweak the css and html for small screens
* Update travis cache for faster build
* clean Makefile, use pip to install, add target for tests
Fixed
-----
* Fix "warn me": we generate the ticket after the user agree to be connected to the service.
we were generating first and the connect button was a link to the service url with the ?ticket=
this could lead to situation where the ticket validity expire if the user is slow to click the
connect button.
* Fix authentication renewal: the renew parameter were not transmited when POST the login request
and self.renew (aks for auth renewal) was use instead of self.renewed (auth was renewd)
when generating a ticket.
* Fix attribute value replacement when generating a ticket: we were using the 'name' attribute
instead of the 'attribut' attribut on ReplaceAttributValue
* Fix attribute value replacement when generating a ticket then the value is a list: iterate over
each element of the list.
* Fix a NameError in utils.import_attr
* Fix serviceValidate and samlValidate when user_field is an attribute that is a list: we use
the first element of the list as username. we were serializing the list before that.
* Correct typos
Cleaned
-------
* Clean some useless conditional branches found with coverage
* Clean cas.js: use compact object declararion
* Use six for python{2|3} compatibility
* Move all unit tests to cas_server.tests and use django primitive. We also have a 100% tests
coverage now. Using the django classes for tests, we do not need to use our own dirty mock.
* Move mysql backend password check to a function in utils
v0.4.4 - 2016-04-30
===================
commit: 77d1607b0beefe8b171adcd8e2dcd974e3cdc72a
Added
-----
* Add sensitive_post_parameters and sensitive_variables for passwords, so passwords are anonymised
before django send an error report.
Fixed
-----
* Before commit 77fc5b5 the User model had a foreign key to the Session model. After the commit,
Only the session_key is store, allowing to use different backend than the Session SQL backend.
So the first migration (which is 21 migrations combined) was creating the User model with the
foreign key, then delete it and add the field session_key. Somehow, MySQL did not like it.
Now the first migration directly create the User model with the session_key and without the
foreign key to the Session SQL backend.
* Evaluate attributes variables in the template samlValidate.xml. the {{ }} was missing causing
the variable name to be displyed instead of the variable content.
* Return username in CAS 1.0 on the second ligne of the CAS response as specified.
Changed
-------
* Update tests
v0.4.3 - 2016-03-18
===================
commit: f6d436acb49f8d32b5457c316c18c4892accfd3b
Fixed
-----
* Currently, one of our dependancy, django-boostrap3, do not support django 1.7 in its last version.
So there is some detection of the current django installed version in setup.py to pin
django-boostrap3 to a version supported by django 1.7 if django 1.7 is installed, or to require
at least django 1.8.
The detection did not handle the case where django was not installed.
* [PEP8] Put line breaks after binary operator and not before.
v0.4.2 - 2016-03-18
===================
commit: d1cd17d6103281b03a8c57013671057eab80d21c
Added
-----
* On logout, display the number of sessions we are logged out from.
Fixed
-----
* One of our dependancy, django-boostrap3, do not support django 1.7 in its last version.
Some django version detection is added to setup.py to handle that.
* Some typos
* Make errors returned by utils.import_attr clearer (as they are likely to be displayed to the
django admin)
v0.4.1 - 2015-12-23
===================
commit: 5e63f39f9b7c678a300ad2f8132166be34d1d35b
Added
-----
* Add a run_test_server target to make file. Running make run_test_server will build a virtualenv,
create a django projet with django-cas-server and lauch ./management.py runserver. It is quite
handy to test developement version.
* Add verbose name for cas_server app and models
* Add Makefile clean targets for tox tests and test virtualenv.
* Add link on license badge to the GPLv3
Changed
-------
* Make Makefile clean targets modular
* Use img.shields.io for PyPi badges
* Get django-cas-server version in Makefile directly from setup.py (so now, the version is only
written in one place)
Fixed
-----
* Fix MysqlAuthUser when number of results != 1: In that case, call super anyway this the provided
username.
v0.4.0 - 2015-12-15
===================
commit: 7b4fac575449e50c2caff07f5798dba7f4e4857c
Added
-----
* Add a help_text to pattern of ServicePattern
* Add a timeout to SLO requests
* Add logging capabilities (see README.rst for instruction)
* Add management commands that should be called on a regular basis to README.rst
v0.3.5 - 2015-12-12
===================
commit: 51fa0861f550723171e52d58025fa789dccb8cde
Added
-----
* Add badges to README.rst
* Document settings parameter in README.rst
* Add a "Features" section in README.rst
Changed
-------
* Add a AuthUser auth class and use it as auth classes base class instead of DummyAuthUser
Fixed
-----
* Fix minor errors and typos in README.rst
v0.3.4 - 2015-12-12
===================
commit: 9fbfe19c550b147e8d0377108cdac8231cf0fb27
Added
-----
* Add static files, templates and locales to the PyPi release by adding them to MANIFEST.in
* Add a Makefile with the build/install/clean/dist targets
v0.3.3 - 2015-12-12
===================
commit: 16b700d0127abe33a1eabf5d5fe890aeb5167e5a
Added
-----
* Add management commands and migrations to the package by adding there packages to setup.py
packages list.
v0.3.2 - 2015-12-12 [YANKED]
============================
commit: eef9490885bf665a53349573ddb9cbe844319b3e
Added
-----
* Add migrations to setup.py package_data
v0.3.1 - 2015-12-12
===================
commit: d0f6ed9ea3a4b3e2bf715fd218c460892c32e39f
Added
-----
* Add a forgotten migration (remove auto_now_add=True from the User model)
v0.3.0 - 2015-12-12
===================
commit: b69769d71a99806a69e300eca0d7c6744a2b327e
Added
-----
* Django 1.9 compatibility (add tox and travis tests and fix some decrecated)
v0.2.1 - 2015-12-12
===================
commit: 90e077dedb991d651822e9bb283470de8bddd7dd
First github and PyPi release
Fixed
-----
* Prune .tox in MANIFEST.in
* add dist/ to .gitignore
* typo in setup.cfg
v0.2.0 - 2015-12-12 [YANKED]
============================
commit: a071ad46d7cd76fc97eb86f2f538d330457c6767
v0.1.0 - 2015-05-22 [YANKED]
============================
commit: 6981433bdf8a406992ba0c5e844a47d06ccc08fb
django-cas-server-1.3.1/LICENSE 0000664 0000000 0000000 00000104514 14070037163 0016041 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
django-cas-server-1.3.1/MANIFEST.in 0000664 0000000 0000000 00000001061 14070037163 0016563 0 ustar 00root root 0000000 0000000 include tox.ini
include LICENSE
include README.rst
include CHANGELOG.rst
include .coveragerc
include Makefile
include pytest.ini
include requirements-dev.txt
include requirements.txt
prune .tox
recursive-include cas_server/static *
recursive-include cas_server/templates *
recursive-include cas_server/locale *
include docs/conf.py
include docs/index.rst
include docs/Makefile
include docs/README.rst
include docs/CHANGELOG.rst
recursive-include docs/_ext *
recursive-include docs/package *
recursive-include docs/_static *
recursive-include docs/_templates *
django-cas-server-1.3.1/Makefile 0000664 0000000 0000000 00000005170 14070037163 0016472 0 ustar 00root root 0000000 0000000 .PHONY: build dist docs
VERSION=`python3 setup.py -V`
build:
python3 setup.py build
install: dist
pip3 -V
pip3 install --no-cache-dir --no-deps --upgrade --force-reinstall --find-links ./dist/django-cas-server-${VERSION}.tar.gz django-cas-server
uninstall:
pip3 uninstall django-cas-server || true
clean_pyc:
find ./ -name '*.pyc' -delete
find ./ -name __pycache__ -delete
clean_build:
rm -rf build django_cas_server.egg-info dist
clean_tox:
rm -rf .tox tox_logs
clean_test_venv:
rm -rf test_venv
clean_coverage:
rm -rf coverage.xml .coverage htmlcov
clean_tild_backup:
find ./ -name '*~' -delete
clean_docs:
rm -rf docs/_build/ docs/django.inv
clean_eggs:
rm -rf .eggs/
clean: clean_pyc clean_build clean_coverage clean_tild_backup
clean_all: clean clean_tox clean_test_venv clean_docs clean_eggs
dist:
python3 setup.py sdist
test_venv/bin/python:
python3 -m venv test_venv
test_venv/bin/pip install -U --requirement requirements-dev.txt 'Django>=3.2,<3.3'
test_venv/cas/manage.py: test_venv
mkdir -p test_venv/cas
test_venv/bin/django-admin startproject cas test_venv/cas
ln -s ../../cas_server test_venv/cas/cas_server
sed -i "s/'django.contrib.staticfiles',/'django.contrib.staticfiles',\n 'cas_server',/" test_venv/cas/cas/settings.py
sed -i "s/'django.middleware.clickjacking.XFrameOptionsMiddleware',/'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.locale.LocaleMiddleware',/" test_venv/cas/cas/settings.py
sed -i 's/from django.conf.urls import url/from django.conf.urls import url, include/' test_venv/cas/cas/urls.py
sed -i "s@url(r'^admin/', admin.site.urls),@url(r'^admin/', admin.site.urls),\n url(r'^', include('cas_server.urls', namespace='cas_server')),@" test_venv/cas/cas/urls.py
test_venv/bin/python test_venv/cas/manage.py migrate
test_venv/bin/python test_venv/cas/manage.py createsuperuser
test_venv: test_venv/bin/python
test_project: test_venv/cas/manage.py
@echo "##############################################################"
@echo "A test django project was created in $(realpath test_venv/cas)"
run_server: test_project
test_venv/bin/python test_venv/cas/manage.py runserver
run_tests: test_venv
python3 setup.py check --restructuredtext --stric
test_venv/bin/py.test -rw -x --cov=cas_server --cov-report html --cov-report term
rm htmlcov/coverage_html.js # I am really pissed off by those keybord shortcuts
test_venv/bin/sphinx-build: test_venv
test_venv/bin/pip install Sphinx sphinx_rtd_theme
docs: test_venv/bin/sphinx-build
bash -c "source test_venv/bin/activate; cd docs; make html"
publish_pypi_release:
python3 setup.py sdist bdist_wheel upload --sign
django-cas-server-1.3.1/README.rst 0000664 0000000 0000000 00000077073 14070037163 0016534 0 ustar 00root root 0000000 0000000 CAS Server
##########
|travis| |coverage| |licence| |github_version| |pypi_version| |codacy| |doc|
CAS Server is a Django application implementing the `CAS Protocol 3.0 Specification
`_.
By default, the authentication process uses django internal users but you can easily
use any source (see the `Authentication backend`_ section and auth classes in the auth.py file)
.. contents:: Table of Contents
Features
========
* Support CAS version 1.0, 2.0, 3.0
* Support Single Sign Out
* Configuration of services via the Django Admin application
* Fine control on which user's attributes are passed to which service
* Possibility to rename/rewrite attributes per service
* Possibility to require some attribute values per service
* Federated mode between multiple CAS
* Supports Django 1.11, 2.2, 3.1 and 3.2
* Supports Python 3.5+
Dependencies
============
``django-cas-server`` depends on the following python packages:
* Django >= 1.11 < 3.3
* requests >= 2.4
* requests_futures >= 0.9.5
* lxml >= 3.4
* six >= 1.8
Minimal version of package dependencies are just indicative and means that ``django-cas-server`` has
been tested with it. Previous versions of dependencies may or may not work.
Additionally, depending on the `Authentication backend`_ you plan to use, you may need the following
python packages:
* ldap3
* psycopg2
* mysql-python
Here is a table with the name of python packages and the corresponding packages providing
them on debian like systems and centos like systems.
You should try as much as possible to use system packages as they are automatically updated when
you update your system. You can then install Not Available (N/A)
packages on your system using pip3 inside a virtualenv as described in the `Installation`_ section.
For use with python2, just replace python3(6) in the table by python.
+------------------+--------------------------+---------------------+
| python package | debian like systems | centos like systems |
+==================+==========================+=====================+
| Django | python3-django | python36-django |
+------------------+--------------------------+---------------------+
| requests | python3-requests | python36-requests |
+------------------+--------------------------+---------------------+
| requests_futures | python3-requests-futures | N/A |
+------------------+--------------------------+---------------------+
| lxml | python3-lxml | python36-lxml |
+------------------+--------------------------+---------------------+
| six | python3-six | python36-six |
+------------------+--------------------------+---------------------+
| ldap3 | python3-ldap3 | python36-ldap3 |
+------------------+--------------------------+---------------------+
| psycopg2 | python3-psycopg2 | python36-psycopg2 |
+------------------+--------------------------+---------------------+
| mysql-python | python3-mysqldb | python36-mysql |
+------------------+--------------------------+---------------------+
Installation
============
The recommended installation mode is to use a virtualenv with ``--system-site-packages``
1. Make sure that python virtualenv is installed
2. Install python packages available via the system package manager:
On debian like systems::
$ sudo apt-get install python3-django python3-requests python3-six python3-lxml python3-requests-futures
On debian jessie, you can use the version of python-django available in the
`backports `_.
On centos like systems with epel enabled::
$ sudo yum install python36-django python36-requests python36-six python36-lxml
3. Create a virtualenv::
$ virtualenv -p python3 --system-site-packages cas_venv
4. And `activate it `__::
$ cd cas_venv/; . bin/activate
5. Create a django project::
$ django-admin startproject cas_project
$ cd cas_project
6. Install `django-cas-server`. To use the last published release, run::
$ pip install django-cas-server
Alternatively if you want to use the version of the git repository, you can clone it::
$ git clone https://github.com/nitmir/django-cas-server
$ cd django-cas-server
$ pip install -r requirements.txt
Then, either run ``make install`` to create a python package using the sources of the repository
and install it with pip, or place the ``cas_server`` directory into your
`PYTHONPATH `_
(for instance by symlinking ``cas_server`` to the root of your django project).
7. Open ``cas_project/settings.py`` in your favourite editor and follow the quick start section.
Quick start
===========
1. Add "cas_server" to your INSTALLED_APPS setting like this::
INSTALLED_APPS = (
'django.contrib.admin',
...
'cas_server',
)
For internationalization support, add "django.middleware.locale.LocaleMiddleware"
to your MIDDLEWARE setting like this::
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware',
...
]
2. Include the cas_server URLconf in your project urls.py like this::
from django.conf.urls import url, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
...
url(r'^cas/', include('cas_server.urls', namespace="cas_server")),
]
3. Run ``python manage.py migrate`` to create the cas_server models.
4. You should add some management commands to a crontab: ``clearsessions``,
``cas_clean_tickets`` and ``cas_clean_sessions``.
* ``clearsessions``: please see `Clearing the session store `_.
* ``cas_clean_tickets``: old tickets and timed-out tickets do not get purged from
the database automatically. They are just marked as invalid. ``cas_clean_tickets``
is a clean-up management command for this purpose. It sends SingleLogOut requests
to services with timed out tickets and deletes them.
* ``cas_clean_sessions``: Logout and purge users (sending SLO requests) that are
inactive more than ``SESSION_COOKIE_AGE``. The default value is ``1209600``
seconds (2 weeks). You probably should reduce it to something like ``86400`` seconds (1 day).
You could, for example, do as below::
0 0 * * * cas-user /path/to/project/manage.py clearsessions
*/5 * * * * cas-user /path/to/project/manage.py cas_clean_tickets
5 0 * * * cas-user /path/to/project/manage.py cas_clean_sessions
5. Run ``python manage.py createsuperuser`` to create an administrator user.
6. Start the development server and visit http://127.0.0.1:8000/admin/
to add a first service allowed to authenticate user against the CAS
(you'll need the Admin app enabled). See the `Service Patterns`_ section below.
7. Visit http://127.0.0.1:8000/cas/ to login with your django users.
Settings
========
All settings are optional. Add them to ``settings.py`` to customize ``django-cas-server``:
Template settings
-----------------
* ``CAS_LOGO_URL``: URL to the logo shown in the upper left corner on the default
template. Set it to ``False`` to disable it.
* ``CAS_FAVICON_URL``: URL to the favicon (shortcut icon) used by the default templates.
Default is a key icon. Set it to ``False`` to disable it.
* ``CAS_SHOW_POWERED``: Set it to ``False`` to hide the powered by footer. The default is ``True``.
* ``CAS_COMPONENT_URLS``: URLs to css and javascript external components. It is a dictionary
having the five following keys: ``"bootstrap3_css"``, ``"bootstrap3_js"``,
``bootstrap4_css``, ``bootstrap4_js``, ``"html5shiv"``, ``"respond"``, ``"jquery"``.
The default is::
{
"bootstrap3_css": "//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
"bootstrap3_js": "//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js",
"html5shiv": "//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js",
"respond": "//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js",
"bootstrap4_css": "//stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css",
"bootstrap4_js": "//stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js",
"jquery": "//code.jquery.com/jquery.min.js",
}
if you omit some keys of the dictionary, the default value for these keys is used.
* ``CAS_SHOW_SERVICE_MESSAGES``: Messages displayed about the state of the service on the login page.
The default is ``True``.
* ``CAS_INFO_MESSAGES``: Messages displayed in info-boxes on the html pages of the default templates.
It is a dictionary mapping message name to a message dict. A message dict has 3 keys:
* ``message``: A unicode message to display, potentially wrapped around ugettex_lazy
* ``discardable``: A boolean, specify if the users can close the message info-box
* ``type``: One of info, success, warning, danger. The type of the info-box.
``CAS_INFO_MESSAGES`` contains by default one message, ``cas_explained``, which explains
roughly the purpose of a CAS. The default is::
{
"cas_explained": {
"message":_(
u"The Central Authentication Service grants you access to most of our websites by "
u"authenticating only once, so you don't need to type your credentials again unless "
u"your session expires or you logout."
),
"discardable": True,
"type": "info", # one of info, success, warning, danger
},
}
* ``CAS_INFO_MESSAGES_ORDER``: A list of message names. Order in which info-box messages are
displayed. Use an empty list to disable messages display. The default is ``[]``.
* ``CAS_LOGIN_TEMPLATE``: Path to the template shown on ``/login`` when the user
is not autenticated. The default is ``"cas_server/bs4/login.html"``.
* ``CAS_WARN_TEMPLATE``: Path to the template shown on ``/login?service=...`` when
the user is authenticated and has asked to be warned before being connected
to a service. The default is ``"cas_server/bs4/warn.html"``.
* ``CAS_LOGGED_TEMPLATE``: Path to the template shown on ``/login`` when the user is
authenticated. The default is ``"cas_server/bs4/logged.html"``.
* ``CAS_LOGOUT_TEMPLATE``: Path to the template shown on ``/logout`` when the user
is being disconnected. The default is ``"cas_server/bs4/logout.html"``
* ``CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT``: Should we redirect users to ``/login`` after they
logged out instead of displaying ``CAS_LOGOUT_TEMPLATE``. The default is ``False``.
Note that the old bootstrap3 template is available in ``cas_server/bs3/``
Authentication settings
-----------------------
* ``CAS_AUTH_CLASS``: A dotted path to a class or a class implementing
``cas_server.auth.AuthUser``. The default is ``"cas_server.auth.DjangoAuthUser"``
Available classes bundled with ``django-cas-server`` are listed below in the
`Authentication backend`_ section.
* ``SESSION_COOKIE_AGE``: This is a django setting. Here, it controls the delay in seconds after
which inactive users are logged out. The default is ``1209600`` (2 weeks). You probably should
reduce it to something like ``86400`` seconds (1 day).
* ``CAS_TGT_VALIDITY``: Max time after which the user MUST reauthenticate. Set it to `None` for no
max time. This can be used to force refreshing cached information only available upon user
authentication like the user attributes in federation mode or with the ldap auth in bind mode.
The default is ``None``.
* ``CAS_PROXY_CA_CERTIFICATE_PATH``: Path to certificate authorities file. Usually on linux
the local CAs are in ``/etc/ssl/certs/ca-certificates.crt``. The default is ``True`` which
tells requests to use its internal certificate authorities. Setting it to ``False`` should
disable all x509 certificate validation and MUST not be done in production.
x509 certificate validation is performed upon PGT issuance.
* ``CAS_SLO_MAX_PARALLEL_REQUESTS``: Maximum number of parallel single log out requests sent.
If more requests need to be sent, they are queued. The default is ``10``.
* ``CAS_SLO_TIMEOUT``: Timeout for a single SLO request in seconds. The default is ``5``.
Federation settings
-------------------
* ``CAS_FEDERATE``: A boolean for activating the federated mode (see the `Federation mode`_
section below). The default is ``False``.
* ``CAS_FEDERATE_REMEMBER_TIMEOUT``: Time after which the cookie used for "remember my identity
provider" expire. The default is ``604800``, one week. The cookie is called
``_remember_provider``.
New version warnings settings
-----------------------------
* ``CAS_NEW_VERSION_HTML_WARNING``: A boolean for diplaying a warning on html pages that a new
version of the application is avaible. Once closed by a user, it is not displayed to this user
until the next new version. The default is ``True``.
* ``CAS_NEW_VERSION_EMAIL_WARNING``: A boolean for sending a email to ``settings.ADMINS`` when a new
version is available. The default is ``True``.
Tickets validity settings
-------------------------
* ``CAS_TICKET_VALIDITY``: Number of seconds the service tickets and proxy tickets are valid.
This is the maximal time between ticket issuance by the CAS and ticket validation by an
application. The default is ``60``.
* ``CAS_PGT_VALIDITY``: Number of seconds the proxy granting tickets are valid.
The default is ``3600`` (1 hour).
* ``CAS_TICKET_TIMEOUT``: Number of seconds a ticket is kept in the database before sending
Single Log Out request and being cleared. The default is ``86400`` (24 hours).
Tickets miscellaneous settings
------------------------------
* ``CAS_TICKET_LEN``: Default ticket length. All CAS implementations MUST support ST and PT
up to 32 chars, PGT and PGTIOU up to 64 chars and it is RECOMMENDED that all tickets up
to 256 chars are supported. Here the default is ``64``.
* ``CAS_LT_LEN``: Length of the login tickets. Login tickets are only processed by ``django-cas-server``
thus there are no length restrictions on it. The default is ``CAS_TICKET_LEN``.
* ``CAS_ST_LEN``: Length of the service tickets. The default is ``CAS_TICKET_LEN``.
You may need to lower it to ``32`` if you use some old clients.
* ``CAS_PT_LEN``: Length of the proxy tickets. The default is ``CAS_TICKET_LEN``.
This length should be the same as ``CAS_ST_LEN``. You may need to lower it to ``32``
if you use some old clients.
* ``CAS_PGT_LEN``: Length of the proxy granting tickets. The default is ``CAS_TICKET_LEN``.
* ``CAS_PGTIOU_LEN``: Length of the proxy granting tickets IOU. The default is ``CAS_TICKET_LEN``.
* ``CAS_LOGIN_TICKET_PREFIX``: Prefix of login tickets. The default is ``"LT"``.
* ``CAS_SERVICE_TICKET_PREFIX``: Prefix of service tickets. The default is ``"ST"``.
The CAS specification mandates that service tickets MUST begin with the characters ST
so you should not change this.
* ``CAS_PROXY_TICKET_PREFIX``: Prefix of proxy ticket. The default is ``"PT"``.
* ``CAS_PROXY_GRANTING_TICKET_PREFIX``: Prefix of proxy granting ticket. The default is ``"PGT"``.
* ``CAS_PROXY_GRANTING_TICKET_IOU_PREFIX``: Prefix of proxy granting ticket IOU. The default is ``"PGTIOU"``.
Mysql backend settings
----------------------
Deprecated, see the `Sql backend settings`_.
Only useful if you are using the mysql authentication backend:
* ``CAS_SQL_HOST``: Host for the SQL server. The default is ``"localhost"``.
* ``CAS_SQL_USERNAME``: Username for connecting to the SQL server.
* ``CAS_SQL_PASSWORD``: Password for connecting to the SQL server.
* ``CAS_SQL_DBNAME``: Database name.
* ``CAS_SQL_DBCHARSET``: Database charset. The default is ``"utf8"``
* ``CAS_SQL_USER_QUERY``: The query performed upon user authentication.
The username must be in field ``username``, the password in ``password``,
additional fields are used as the user attributes.
The default is ``"SELECT user AS username, pass AS password, users.* FROM users WHERE user = %s"``
* ``CAS_SQL_PASSWORD_CHECK``: The method used to check the user password. Must be one of the following:
* ``"crypt"`` (see ), the password in the database
should begin with $
* ``"ldap"`` (see https://tools.ietf.org/id/draft-stroeder-hashed-userpassword-values-01.html)
the password in the database must begin with one of {MD5}, {SMD5}, {SHA}, {SSHA}, {SHA256},
{SSHA256}, {SHA384}, {SSHA384}, {SHA512}, {SSHA512}, {CRYPT}.
* ``"hex_HASH_NAME"`` with ``HASH_NAME`` in md5, sha1, sha224, sha256, sha384, sha512.
The hashed password in the database is compared to the hexadecimal digest of the clear
password hashed with the corresponding algorithm.
* ``"plain"``, the password in the database must be in clear.
The default is ``"crypt"``.
Sql backend settings
--------------------
Only useful if you are using the sql authentication backend. You must add a ``"cas_server"``
database to `settings.DATABASES `__
as defined in the django documentation. It is then the database
used by the sql backend.
* ``CAS_SQL_USER_QUERY``: The query performed upon user authentication.
The username must be in field ``username``, the password in ``password``,
additional fields are used as the user attributes.
The default is ``"SELECT user AS username, pass AS password, users.* FROM users WHERE user = %s"``
* ``CAS_SQL_PASSWORD_CHECK``: The method used to check the user password. Must be one of the following:
* ``"crypt"`` (see ), the password in the database
should begin with $
* ``"ldap"`` (see https://tools.ietf.org/id/draft-stroeder-hashed-userpassword-values-01.html)
the password in the database must begin with one of {MD5}, {SMD5}, {SHA}, {SSHA}, {SHA256},
{SSHA256}, {SHA384}, {SSHA384}, {SHA512}, {SSHA512}, {CRYPT}.
* ``"hex_HASH_NAME"`` with ``HASH_NAME`` in md5, sha1, sha224, sha256, sha384, sha512.
The hashed password in the database is compared to the hexadecimal digest of the clear
password hashed with the corresponding algorithm.
* ``"plain"``, the password in the database must be in clear.
The default is ``"crypt"``.
* ``CAS_SQL_PASSWORD_CHARSET``: Charset the SQL users passwords was hash with. This is needed to
encode the user submitted password before hashing it for comparison. The default is ``"utf-8"``.
Ldap backend settings
---------------------
Only useful if you are using the ldap authentication backend:
* ``CAS_LDAP_SERVER``: Address of the LDAP server. The default is ``"localhost"``.
* ``CAS_LDAP_USER``: User bind address, for example ``"cn=admin,dc=crans,dc=org"`` for
connecting to the LDAP server.
* ``CAS_LDAP_PASSWORD``: Password for connecting to the LDAP server.
* ``CAS_LDAP_BASE_DN``: LDAP search base DN, for example ``"ou=data,dc=crans,dc=org"``.
* ``CAS_LDAP_USER_QUERY``: Search filter for searching user by username. User entered usernames are
escaped using ``ldap3.utils.conv.escape_bytes``. The default is ``"(uid=%s)"``
* ``CAS_LDAP_USERNAME_ATTR``: Attribute used for user's usernames. The default is ``"uid"``
* ``CAS_LDAP_PASSWORD_ATTR``: Attribute used for user's passwords. The default is ``"userPassword"``
* ``CAS_LDAP_PASSWORD_CHECK``: The method used to check the user password. Must be one of the following:
* ``"crypt"`` (see ), the password in the database
should begin with $
* ``"ldap"`` (see https://tools.ietf.org/id/draft-stroeder-hashed-userpassword-values-01.html)
the password in the database must begin with one of {MD5}, {SMD5}, {SHA}, {SSHA}, {SHA256},
{SSHA256}, {SHA384}, {SSHA384}, {SHA512}, {SSHA512}, {CRYPT}.
* ``"hex_HASH_NAME"`` with ``HASH_NAME`` in md5, sha1, sha224, sha256, sha384, sha512.
The hashed password in the database is compared to the hexadecimal digest of the clear
password hashed with the corresponding algorithm.
* ``"plain"``, the password in the database must be in clear.
* ``"bind"``, the user credentials are used to bind to the ldap database and retreive the user
attribute. In this mode, the settings ``CAS_LDAP_PASSWORD_ATTR`` and ``CAS_LDAP_PASSWORD_CHARSET``
are ignored, and it is the ldap server that performs the password check.
The default is ``"ldap"``.
* ``CAS_LDAP_ATTRS_VIEW``: This parameter is only used then ``CAS_LDAP_PASSWORD_CHECK`` is set to
``"bind"``. If ``0`` the user attributes are retrieved by connecting to the ldap as ``CAS_LDAP_USER``.
If ``1`` the user attributes are retrieve then the user authenticate using the user credentials and
are cached for later use. It means there can be some differences between the attributes in database
and the cached ones. See the parameter ``CAS_TGT_VALIDITY`` to force user to reauthenticate
periodically.
The default is ``0``.
* ``CAS_LDAP_PASSWORD_CHARSET``: Charset the LDAP users passwords was hashed with. This is needed to
encode the user submitted password before hashing it for comparison. The default is ``"utf-8"``.
Test backend settings
---------------------
Only useful if you are using the test authentication backend:
* ``CAS_TEST_USER``: Username of the test user. The default is ``"test"``.
* ``CAS_TEST_PASSWORD``: Password of the test user. The default is ``"test"``.
* ``CAS_TEST_ATTRIBUTES``: Attributes of the test user. The default is
``{'nom': 'Nymous', 'prenom': 'Ano', 'email': 'anonymous@example.net',
'alias': ['demo1', 'demo2']}``.
Authentication backend
======================
``django-cas-server`` comes with some authentication backends:
* dummy backend ``cas_server.auth.DummyAuthUser``: all authentication attempts fail.
* test backend ``cas_server.auth.TestAuthUser``: username, password and returned attributes
for the user are defined by the ``CAS_TEST_*`` settings.
* django backend ``cas_server.auth.DjangoAuthUser``: Users are authenticated against django users system.
This is the default backend. The returned attributes are the fields available on the user model.
* mysql backend ``cas_server.auth.MysqlAuthUser``: Deprecated, use the sql backend instead.
see the `Mysql backend settings`_ section. The returned attributes are those returned by sql query
``CAS_SQL_USER_QUERY``.
* sql backend ``cas_server.auth.SqlAuthUser``: see the `Sql backend settings`_ section.
The returned attributes are those returned by sql query ``CAS_SQL_USER_QUERY``.
* ldap backend ``cas_server.auth.LdapAuthUser``: see the `Ldap backend settings`_ section.
The returned attributes are those of the ldap node returned by the query filter ``CAS_LDAP_USER_QUERY``.
* federated backend ``cas_server.auth.CASFederateAuth``: It is automatically used when ``CAS_FEDERATE`` is ``True``.
You should not set it manually without setting ``CAS_FEDERATE`` to ``True``.
Logs
====
``django-cas-server`` logs most of its actions. To enable login, you must set the ``LOGGING``
(https://docs.djangoproject.com/en/stable/topics/logging) variable in ``settings.py``.
Users successful actions (login, logout) are logged with the level ``INFO``, failures are logged
with the level ``WARNING`` and user attributes transmitted to a service are logged with the level ``DEBUG``.
For example to log to syslog you can use :
.. code-block:: python
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'cas_syslog': {
'format': 'cas: %(levelname)s %(message)s'
},
},
'handlers': {
'cas_syslog': {
'level': 'INFO',
'class': 'logging.handlers.SysLogHandler',
'address': '/dev/log',
'formatter': 'cas_syslog',
},
},
'loggers': {
'cas_server': {
'handlers': ['cas_syslog'],
'level': 'INFO',
'propagate': True,
},
},
}
Or to log to a file:
.. code-block:: python
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'cas_file': {
'format': '%(asctime)s %(levelname)s %(message)s'
},
},
'handlers': {
'cas_file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': '/tmp/cas_server.log',
'formatter': 'cas_file',
},
},
'loggers': {
'cas_server': {
'handlers': ['cas_file'],
'level': 'INFO',
'propagate': True,
},
},
}
Service Patterns
================
In a CAS context, ``Service`` refers to the application the client is trying to access.
By extension we use ``service`` for the URL of such an application.
By default, ``django-cas-server`` does not allow any service to use the CAS to authenticate users.
In order to allow services, you need to connect to the django admin interface using a django
superuser, and add a first service pattern.
A service pattern comes with 9 fields:
* ``Position``: an integer used to change the order in which services are matched against
service patterns.
* ``Name``: the name of the service pattern. It will be displayed to the users asking for a ticket
for a service matching this service pattern on the login page.
* ``Pattern``: a regular expression used to match services.
* ``User field``: the user attribute to use as username for services matching this service pattern.
Leave it empty to use the login name.
* ``Restrict username``: if checked, only login names defined below are allowed to get tickets
for services matching this service pattern.
* ``Proxy``: if checked, allow the creation of Proxy Ticket for services matching this
service pattern. Otherwise, only Service Ticket will be created.
* ``Proxy callback``: if checked, services matching this service pattern are allowed to retrieve Proxy
Granting Ticket. A service with a Proxy Granting Ticket can get Proxy Ticket for other services.
Hence you must only check this for trusted services that need it. (For instance, a webmail needs
Proxy Ticket to authenticate himself as the user to the imap server).
* ``Single log out``: Check it to send Single Log Out requests to authenticated services matching
this service pattern. SLO requests are sent to all services the user is authenticated to when
the user disconnects.
* ``Single log out callback``: The http(s) URL to POST the SLO requests. If empty, the service URL
is used. This field is useful to allow non http services (imap, smtp, ftp) to handle SLO requests.
A service pattern has 4 associated models:
* ``Usernames``: a list of username associated with the ``Restrict username`` field
* ``Replace attribute names``: a list of user attributes to send to the service. Choose the name
used for sending the attribute by setting ``Replacement`` or leave it empty to leave it unchanged.
* ``Replace attribute values``: a list of sent user attributes for which value needs to be tweaked.
Replace the attribute value by the string obtained by replacing the leftmost non-overlapping
occurrences of ``pattern`` in string by ``replace``. In ``replace`` backslash escapes are processed.
Matched groups are captured by \1, \2, etc.
* ``Filter attribute values``: a list of user attributes for which value needs to match a regular
expression. For instance, service A may need an email address, and you only want user with
an email address to connect to it. To do so, put ``email`` in ``Attribute`` and ``.*`` in ``pattern``.
When a user asks for a ticket for a service, the service URL is compared against each service pattern
sorted by ``position``. The first service pattern that matches the service URL is chosen.
Hence, you should give low ``position`` to very specific patterns like
``^https://www\.example\.com(/.*)?$`` and higher ``position`` to generic patterns like ``^https://.*``.
So the service URL ``https://www.examle.com`` will use the service pattern for
``^https://www\.example\.com(/.*)?$`` and not the one for ``^https://.*``.
Federation mode
===============
``django-cas-server`` comes with a federation mode. When ``CAS_FEDERATE`` is ``True``,
users are invited to choose an identity provider on the login page, then, they are redirected
to the provider CAS to authenticate. This provider transmits to ``django-cas-server`` the user
username and attributes. The user is now logged in on ``django-cas-server`` and can use
services using ``django-cas-server`` as CAS.
In federation mode, the user attributes are cached upon user authentication. See the settings
``CAS_TGT_VALIDITY`` to force users to reauthenticate periodically and allow ``django-cas-server``
to refresh cached attributes.
The list of allowed identity providers is defined using the django admin application.
With the development server started, visit http://127.0.0.1:8000/admin/ to add identity providers.
An identity provider comes with 5 fields:
* ``Position``: an integer used to tweak the order in which identity providers are displayed on
the login page. Identity providers are sorted using position first, then, on equal position,
using ``verbose name`` and then, on equal ``verbose name``, using ``suffix``.
* ``Suffix``: the suffix that will be append to the username returned by the identity provider.
It must be unique.
* ``Server url``: the URL to the identity provider CAS. For instance, if you are using
``https://cas.example.org/login`` to authenticate on the CAS, the ``server url`` is
``https://cas.example.org``
* ``CAS protocol version``: the version of the CAS protocol to use to contact the identity provider.
The default is version 3.
* ``Verbose name``: the name used on the login page to display the identity provider.
* ``Display``: a boolean controlling the display of the identity provider on the login page.
Beware that this do not disable the identity provider, it just hide it on the login page.
User will always be able to log in using this provider by fetching ``/federate/provider_suffix``.
In federation mode, ``django-cas-server`` build user's username as follow:
``provider_returned_username@provider_suffix``.
Choose the provider returned username for ``django-cas-server`` and the provider suffix
in order to make sense, as this built username is likely to be displayed to end users in
applications.
Then using federate mode, you should add one command to a daily crontab: ``cas_clean_federate``.
This command clean the local cache of federated user from old unused users.
You could for example do as below::
10 0 * * * cas-user /path/to/project/manage.py cas_clean_federate
.. |travis| image:: https://badges.genua.fr/travis/com/nitmir/django-cas-server/master.svg
:target: https://travis-ci.com/nitmir/django-cas-server
.. |pypi_version| image:: https://badges.genua.fr/pypi/v/django-cas-server.svg
:target: https://pypi.org/project/django-cas-server/
.. |github_version| image:: https://badges.genua.fr/github/tag/nitmir/django-cas-server.svg?label=github
:target: https://github.com/nitmir/django-cas-server/releases/latest
.. |licence| image:: https://badges.genua.fr/pypi/l/django-cas-server.svg
:target: https://www.gnu.org/licenses/gpl-3.0.html
.. |codacy| image:: https://badges.genua.fr/codacy/grade/255c21623d6946ef8802fa7995b61366/master.svg
:target: https://www.codacy.com/app/valentin-samir/django-cas-server
.. |coverage| image:: https://intranet.genua.fr/coverage/badge/django-cas-server/master.svg
:target: https://badges.genua.fr/coverage/django-cas-server/master
.. |doc| image:: https://badges.genua.fr/local/readthedocs/?version=latest
:target: http://django-cas-server.readthedocs.io
django-cas-server-1.3.1/cas_server/ 0000775 0000000 0000000 00000000000 14070037163 0017163 5 ustar 00root root 0000000 0000000 django-cas-server-1.3.1/cas_server/__init__.py 0000664 0000000 0000000 00000001266 14070037163 0021301 0 ustar 00root root 0000000 0000000 # This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# (c) 2015-2016 Valentin Samir
"""A django CAS server application"""
#: version of the application
VERSION = '1.3.1'
#: path the the application configuration class
default_app_config = 'cas_server.apps.CasAppConfig'
django-cas-server-1.3.1/cas_server/admin.py 0000664 0000000 0000000 00000015235 14070037163 0020633 0 ustar 00root root 0000000 0000000 # This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# (c) 2015-2016 Valentin Samir
"""module for the admin interface of the app"""
from .default_settings import settings
from django.contrib import admin
from .models import ServiceTicket, ProxyTicket, ProxyGrantingTicket, User, ServicePattern
from .models import Username, ReplaceAttributName, ReplaceAttributValue, FilterAttributValue
from .models import FederatedIendityProvider, FederatedUser, UserAttributes
from .forms import TicketForm
class BaseInlines(admin.TabularInline):
"""
Bases: :class:`django.contrib.admin.TabularInline`
Base class for inlines in the admin interface.
"""
#: This controls the number of extra forms the formset will display in addition to
#: the initial forms.
extra = 0
class UserAdminInlines(BaseInlines):
"""
Bases: :class:`BaseInlines`
Base class for inlines in :class:`UserAdmin` interface
"""
#: The form :class:`TicketForm` used to display tickets.
form = TicketForm
#: Fields to display on a object that are read only (not editable).
readonly_fields = (
'validate', 'service', 'service_pattern',
'creation', 'renew', 'single_log_out', 'value'
)
#: Fields to display on a object.
fields = (
'validate', 'service', 'service_pattern',
'creation', 'renew', 'single_log_out'
)
class ServiceTicketInline(UserAdminInlines):
"""
Bases: :class:`UserAdminInlines`
:class:`ServiceTicket` in admin interface
"""
#: The model which the inline is using.
model = ServiceTicket
class ProxyTicketInline(UserAdminInlines):
"""
Bases: :class:`UserAdminInlines`
:class:`ProxyTicket` in admin interface
"""
#: The model which the inline is using.
model = ProxyTicket
class ProxyGrantingInline(UserAdminInlines):
"""
Bases: :class:`UserAdminInlines`
:class:`ProxyGrantingTicket` in admin interface
"""
#: The model which the inline is using.
model = ProxyGrantingTicket
class UserAdmin(admin.ModelAdmin):
"""
Bases: :class:`django.contrib.admin.ModelAdmin`
:class:`User` in admin interface
"""
#: See :class:`ServiceTicketInline`, :class:`ProxyTicketInline`, :class:`ProxyGrantingInline`
#: objects below the :class:`UserAdmin` fields.
inlines = (ServiceTicketInline, ProxyTicketInline, ProxyGrantingInline)
#: Fields to display on a object that are read only (not editable).
readonly_fields = ('username', 'date', "session_key")
#: Fields to display on a object.
fields = ('username', 'date', "session_key")
#: Fields to display on the list of class:`UserAdmin` objects.
list_display = ('username', 'date', "session_key")
class UsernamesInline(BaseInlines):
"""
Bases: :class:`BaseInlines`
:class:`Username` in admin interface
"""
#: The model which the inline is using.
model = Username
class ReplaceAttributNameInline(BaseInlines):
"""
Bases: :class:`BaseInlines`
:class:`ReplaceAttributName` in admin interface
"""
#: The model which the inline is using.
model = ReplaceAttributName
class ReplaceAttributValueInline(BaseInlines):
"""
Bases: :class:`BaseInlines`
:class:`ReplaceAttributValue` in admin interface
"""
#: The model which the inline is using.
model = ReplaceAttributValue
class FilterAttributValueInline(BaseInlines):
"""
Bases: :class:`BaseInlines`
:class:`FilterAttributValue` in admin interface
"""
#: The model which the inline is using.
model = FilterAttributValue
class ServicePatternAdmin(admin.ModelAdmin):
"""
Bases: :class:`django.contrib.admin.ModelAdmin`
:class:`ServicePattern` in admin interface
"""
#: See :class:`UsernamesInline`, :class:`ReplaceAttributNameInline`,
#: :class:`ReplaceAttributValueInline`, :class:`FilterAttributValueInline` objects below
#: the :class:`ServicePatternAdmin` fields.
inlines = (
UsernamesInline,
ReplaceAttributNameInline,
ReplaceAttributValueInline,
FilterAttributValueInline
)
#: Fields to display on the list of class:`ServicePatternAdmin` objects.
list_display = ('pos', 'name', 'pattern', 'proxy',
'single_log_out', 'proxy_callback', 'restrict_users')
class FederatedIendityProviderAdmin(admin.ModelAdmin):
"""
Bases: :class:`django.contrib.admin.ModelAdmin`
:class:`FederatedIendityProvider` in admin
interface
"""
#: Fields to display on a object.
fields = ('pos', 'suffix', 'server_url', 'cas_protocol_version', 'verbose_name', 'display')
#: Fields to display on the list of class:`FederatedIendityProviderAdmin` objects.
list_display = ('verbose_name', 'suffix', 'display')
class FederatedUserAdmin(admin.ModelAdmin):
"""
Bases: :class:`django.contrib.admin.ModelAdmin`
:class:`FederatedUser` in admin
interface
"""
#: Fields to display on a object.
fields = ('username', 'provider', 'last_update')
#: Fields to display on the list of class:`FederatedUserAdmin` objects.
list_display = ('username', 'provider', 'last_update')
class UserAttributesAdmin(admin.ModelAdmin):
"""
Bases: :class:`django.contrib.admin.ModelAdmin`
:class:`UserAttributes` in admin
interface
"""
#: Fields to display on a object.
fields = ('username', '_attributs')
admin.site.register(ServicePattern, ServicePatternAdmin)
admin.site.register(FederatedIendityProvider, FederatedIendityProviderAdmin)
if settings.DEBUG: # pragma: no branch (we always test with DEBUG True)
admin.site.register(User, UserAdmin)
admin.site.register(FederatedUser, FederatedUserAdmin)
admin.site.register(UserAttributes, UserAttributesAdmin)
django-cas-server-1.3.1/cas_server/apps.py 0000664 0000000 0000000 00000002077 14070037163 0020506 0 ustar 00root root 0000000 0000000 # This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# (c) 2015-2016 Valentin Samir
"""django config module"""
from django.apps import AppConfig
import sys
if sys.version_info < (3, ):
from django.utils.translation import ugettext_lazy as _
else:
from django.utils.translation import gettext_lazy as _
class CasAppConfig(AppConfig):
"""
Bases: :class:`django.apps.AppConfig`
django CAS application config class
"""
#: Full Python path to the application. It must be unique across a Django project.
name = 'cas_server'
#: Human-readable name for the application.
verbose_name = _('Central Authentication Service')
django-cas-server-1.3.1/cas_server/auth.py 0000664 0000000 0000000 00000047761 14070037163 0020515 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# (c) 2015-2016 Valentin Samir
"""Some authentication classes for the CAS"""
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.db import connections, DatabaseError
import warnings
from datetime import timedelta
from six.moves import range
try: # pragma: no cover
import MySQLdb
import MySQLdb.cursors
except ImportError:
MySQLdb = None
try: # pragma: no cover
import ldap3
import ldap3.core.exceptions
except ImportError:
ldap3 = None
from .models import FederatedUser, UserAttributes
from .utils import check_password, dictfetchall
class AuthUser(object):
"""
Authentication base class
:param unicode username: A username, stored in the :attr:`username` class attribute.
"""
#: username used to instanciate the current object
username = None
def __init__(self, username):
self.username = username
def test_password(self, password):
"""
Tests ``password`` against the user-supplied password.
:raises NotImplementedError: always. The method need to be implemented by subclasses
"""
raise NotImplementedError()
def attributs(self):
"""
The user attributes.
raises NotImplementedError: always. The method need to be implemented by subclasses
"""
raise NotImplementedError()
class DummyAuthUser(AuthUser): # pragma: no cover
"""
A Dummy authentication class. Authentication always fails
:param unicode username: A username, stored in the :attr:`username`
class attribute. There is no valid value for this attribute here.
"""
def test_password(self, password):
"""
Tests ``password`` against the user-supplied password.
:param unicode password: a clear text password as submited by the user.
:return: always ``False``
:rtype: bool
"""
return False
def attributs(self):
"""
The user attributes.
:return: en empty :class:`dict`.
:rtype: dict
"""
return {}
class TestAuthUser(AuthUser):
"""
A test authentication class only working for one unique user.
:param unicode username: A username, stored in the :attr:`username`
class attribute. The uniq valid value is ``settings.CAS_TEST_USER``.
"""
def test_password(self, password):
"""
Tests ``password`` against the user-supplied password.
:param unicode password: a clear text password as submited by the user.
:return: ``True`` if :attr:`username` is valid and
``password`` is equal to ``settings.CAS_TEST_PASSWORD``, ``False`` otherwise.
:rtype: bool
"""
return self.username == settings.CAS_TEST_USER and password == settings.CAS_TEST_PASSWORD
def attributs(self):
"""
The user attributes.
:return: the ``settings.CAS_TEST_ATTRIBUTES`` :class:`dict` if
:attr:`username` is valid, an empty :class:`dict` otherwise.
:rtype: dict
"""
if self.username == settings.CAS_TEST_USER:
return settings.CAS_TEST_ATTRIBUTES
else: # pragma: no cover (should not happen)
return {}
class DBAuthUser(AuthUser): # pragma: no cover
"""base class for databate based auth classes"""
#: DB user attributes as a :class:`dict` if the username is found in the database.
user = None
def attributs(self):
"""
The user attributes.
:return: a :class:`dict` with the user attributes. Attributes may be :func:`unicode`
or :class:`list` of :func:`unicode`. If the user do not exists, the returned
:class:`dict` is empty.
:rtype: dict
"""
if self.user:
return self.user
else:
return {}
class MysqlAuthUser(DBAuthUser): # pragma: no cover
"""
DEPRECATED, use :class:`SqlAuthUser` instead.
A mysql authentication class: authenticate user against a mysql database
:param unicode username: A username, stored in the :attr:`username`
class attribute. Valid value are fetched from the MySQL database set with
``settings.CAS_SQL_*`` settings parameters using the query
``settings.CAS_SQL_USER_QUERY``.
"""
def __init__(self, username):
warnings.warn(
(
"MysqlAuthUser authentication class is deprecated: "
"use cas_server.auth.SqlAuthUser instead"
),
UserWarning
)
# see the connect function at
# http://mysql-python.sourceforge.net/MySQLdb.html#functions-and-attributes
# for possible mysql config parameters.
mysql_config = {
"user": settings.CAS_SQL_USERNAME,
"passwd": settings.CAS_SQL_PASSWORD,
"db": settings.CAS_SQL_DBNAME,
"host": settings.CAS_SQL_HOST,
"charset": settings.CAS_SQL_DBCHARSET,
"cursorclass": MySQLdb.cursors.DictCursor
}
if not MySQLdb:
raise RuntimeError("Please install MySQLdb before using the MysqlAuthUser backend")
conn = MySQLdb.connect(**mysql_config)
curs = conn.cursor()
if curs.execute(settings.CAS_SQL_USER_QUERY, (username,)) == 1:
self.user = curs.fetchone()
super(MysqlAuthUser, self).__init__(self.user['username'])
else:
super(MysqlAuthUser, self).__init__(username)
def test_password(self, password):
"""
Tests ``password`` against the user-supplied password.
:param unicode password: a clear text password as submited by the user.
:return: ``True`` if :attr:`username` is valid and ``password`` is
correct, ``False`` otherwise.
:rtype: bool
"""
if self.user:
return check_password(
settings.CAS_SQL_PASSWORD_CHECK,
password,
self.user["password"],
settings.CAS_SQL_DBCHARSET
)
else:
return False
class SqlAuthUser(DBAuthUser): # pragma: no cover
"""
A SQL authentication class: authenticate user against a SQL database. The SQL database
must be configures in settings.py as ``settings.DATABASES['cas_server']``.
:param unicode username: A username, stored in the :attr:`username`
class attribute. Valid value are fetched from the MySQL database set with
``settings.CAS_SQL_*`` settings parameters using the query
``settings.CAS_SQL_USER_QUERY``.
"""
def __init__(self, username):
if "cas_server" not in connections:
raise RuntimeError("Please configure the 'cas_server' database in settings.DATABASES")
for retry_nb in range(3):
try:
with connections["cas_server"].cursor() as curs:
curs.execute(settings.CAS_SQL_USER_QUERY, (username,))
results = dictfetchall(curs)
if len(results) == 1:
self.user = results[0]
super(SqlAuthUser, self).__init__(self.user['username'])
else:
super(SqlAuthUser, self).__init__(username)
break
except DatabaseError:
connections["cas_server"].close()
if retry_nb == 2:
raise
def test_password(self, password):
"""
Tests ``password`` against the user-supplied password.
:param unicode password: a clear text password as submited by the user.
:return: ``True`` if :attr:`username` is valid and ``password`` is
correct, ``False`` otherwise.
:rtype: bool
"""
if self.user:
return check_password(
settings.CAS_SQL_PASSWORD_CHECK,
password,
self.user["password"],
settings.CAS_SQL_PASSWORD_CHARSET
)
else:
return False
class LdapAuthUser(DBAuthUser): # pragma: no cover
"""
A ldap authentication class: authenticate user against a ldap database
:param unicode username: A username, stored in the :attr:`username`
class attribute. Valid value are fetched from the ldap database set with
``settings.CAS_LDAP_*`` settings parameters.
"""
_conn = None
@classmethod
def get_conn(cls):
"""Return a connection object to the ldap database"""
conn = cls._conn
if conn is None or conn.closed:
conn = ldap3.Connection(
settings.CAS_LDAP_SERVER,
settings.CAS_LDAP_USER,
settings.CAS_LDAP_PASSWORD,
client_strategy="RESTARTABLE",
auto_bind=True
)
cls._conn = conn
return conn
def __init__(self, username):
if not ldap3:
raise RuntimeError("Please install ldap3 before using the LdapAuthUser backend")
if not settings.CAS_LDAP_BASE_DN:
raise ValueError(
"You must define CAS_LDAP_BASE_DN for using the ldap authentication backend"
)
# in case we got deconnected from the database, retry to connect 2 times
for retry_nb in range(3):
try:
conn = self.get_conn()
if conn.search(
settings.CAS_LDAP_BASE_DN,
settings.CAS_LDAP_USER_QUERY % ldap3.utils.conv.escape_bytes(username),
attributes=ldap3.ALL_ATTRIBUTES
) and len(conn.entries) == 1:
# try the new ldap3>=2 API
try:
user = conn.entries[0].entry_attributes_as_dict
# store the user dn
user["dn"] = conn.entries[0].entry_dn
# fallback to ldap3<2 API
except (
ldap3.core.exceptions.LDAPKeyError, # ldap3<1 exception
ldap3.core.exceptions.LDAPAttributeError # ldap3<2 exception
):
user = conn.entries[0].entry_get_attributes_dict()
# store the user dn
user["dn"] = conn.entries[0].entry_get_dn()
if user.get(settings.CAS_LDAP_USERNAME_ATTR):
self.user = user
super(LdapAuthUser, self).__init__(user[settings.CAS_LDAP_USERNAME_ATTR][0])
else:
super(LdapAuthUser, self).__init__(username)
else:
super(LdapAuthUser, self).__init__(username)
break
except ldap3.core.exceptions.LDAPCommunicationError:
if retry_nb == 2:
raise
def test_password(self, password):
"""
Tests ``password`` against the user-supplied password.
:param unicode password: a clear text password as submited by the user.
:return: ``True`` if :attr:`username` is valid and ``password`` is
correct, ``False`` otherwise.
:rtype: bool
"""
if self.user and settings.CAS_LDAP_PASSWORD_CHECK == "bind":
try:
conn = ldap3.Connection(
settings.CAS_LDAP_SERVER,
self.user["dn"],
password,
auto_bind=True
)
try:
# fetch the user attribute
if conn.search(
settings.CAS_LDAP_BASE_DN,
settings.CAS_LDAP_USER_QUERY % ldap3.utils.conv.escape_bytes(self.username),
attributes=ldap3.ALL_ATTRIBUTES
) and len(conn.entries) == 1:
# try the ldap3>=2 API
try:
attributes = conn.entries[0].entry_attributes_as_dict
# store the user dn
attributes["dn"] = conn.entries[0].entry_dn
# fallback to ldap<2 API
except (
ldap3.core.exceptions.LDAPKeyError, # ldap3<1 exception
ldap3.core.exceptions.LDAPAttributeError # ldap3<2 exception
):
attributes = conn.entries[0].entry_get_attributes_dict()
attributes["dn"] = conn.entries[0].entry_get_dn()
# cache the attributes locally as we wont have access to the user password
# later.
user = UserAttributes.objects.get_or_create(username=self.username)[0]
user.attributs = attributes
user.save()
finally:
conn.unbind()
return True
except (
ldap3.core.exceptions.LDAPBindError,
ldap3.core.exceptions.LDAPCommunicationError
):
return False
elif self.user and self.user.get(settings.CAS_LDAP_PASSWORD_ATTR):
return check_password(
settings.CAS_LDAP_PASSWORD_CHECK,
password,
self.user[settings.CAS_LDAP_PASSWORD_ATTR][0],
settings.CAS_LDAP_PASSWORD_CHARSET
)
else:
return False
def attributs(self):
"""
The user attributes.
:return: a :class:`dict` with the user attributes. Attributes may be :func:`unicode`
or :class:`list` of :func:`unicode`. If the user do not exists, the returned
:class:`dict` is empty.
:rtype: dict
"""
if settings.CAS_LDAP_PASSWORD_CHECK == "bind":
if settings.CAS_LDAP_ATTRS_VIEW == 1:
user = UserAttributes.objects.get(username=self.username)
return user.attributs
else:
return self.user
else:
return super(LdapAuthUser, self).attributs()
class DjangoAuthUser(AuthUser): # pragma: no cover
"""
A django auth class: authenticate user against django internal users
:param unicode username: A username, stored in the :attr:`username`
class attribute. Valid value are usernames of django internal users.
"""
#: a django user object if the username is found. The user model is retreived
#: using :func:`django.contrib.auth.get_user_model`.
user = None
def __init__(self, username):
User = get_user_model()
try:
self.user = User.objects.get(username=username)
except User.DoesNotExist:
pass
super(DjangoAuthUser, self).__init__(username)
def test_password(self, password):
"""
Tests ``password`` against the user-supplied password.
:param unicode password: a clear text password as submited by the user.
:return: ``True`` if :attr:`user` is valid and ``password`` is
correct, ``False`` otherwise.
:rtype: bool
"""
if self.user:
return self.user.check_password(password)
else:
return False
def attributs(self):
"""
The user attributes, defined as the fields on the :attr:`user` object.
:return: a :class:`dict` with the :attr:`user` object fields. Attributes may be
If the user do not exists, the returned :class:`dict` is empty.
:rtype: dict
"""
if self.user:
attr = {}
# _meta.get_fields() is from the new documented _meta interface in django 1.8
try:
field_names = [
field.attname for field in self.user._meta.get_fields()
if hasattr(field, "attname")
]
# backward compatibility with django 1.7
except AttributeError: # pragma: no cover (only used by django 1.7)
field_names = self.user._meta.get_all_field_names()
for name in field_names:
attr[name] = getattr(self.user, name)
# unfold user_permissions many to many relation
if 'user_permissions' in attr:
attr['user_permissions'] = [
(
u"%s.%s" % (
perm.content_type.model_class().__module__,
perm.content_type.model_class().__name__
),
perm.codename
) for perm in attr['user_permissions'].filter()
]
# unfold group many to many relation
if 'groups' in attr:
attr['groups'] = [group.name for group in attr['groups'].filter()]
return attr
else:
return {}
class CASFederateAuth(AuthUser):
"""
Authentication class used then CAS_FEDERATE is True
:param unicode username: A username, stored in the :attr:`username`
class attribute. Valid value are usernames of
:class:`FederatedUser` object.
:class:`FederatedUser` object are created on CAS
backends successful ticket validation.
"""
#: a :class`FederatedUser` object if ``username`` is found.
user = None
def __init__(self, username):
try:
self.user = FederatedUser.get_from_federated_username(username)
super(CASFederateAuth, self).__init__(
self.user.federated_username
)
except FederatedUser.DoesNotExist:
super(CASFederateAuth, self).__init__(username)
def test_password(self, ticket):
"""
Tests ``password`` against the user-supplied password.
:param unicode password: The CAS tickets just used to validate the user authentication
against its CAS backend.
:return: ``True`` if :attr:`user` is valid and ``password`` is
a ticket validated less than ``settings.CAS_TICKET_VALIDITY`` secondes and has not
being previously used for authenticated this
:class:`FederatedUser`. ``False`` otherwise.
:rtype: bool
"""
if not self.user or not self.user.ticket:
return False
else:
return (
ticket == self.user.ticket and
self.user.last_update >
(timezone.now() - timedelta(seconds=settings.CAS_TICKET_VALIDITY))
)
def attributs(self):
"""
The user attributes, as returned by the CAS backend.
:return: :obj:`FederatedUser.attributs`.
If the user do not exists, the returned :class:`dict` is empty.
:rtype: dict
"""
if not self.user: # pragma: no cover (should not happen)
return {}
else:
return self.user.attributs
django-cas-server-1.3.1/cas_server/cas.py 0000664 0000000 0000000 00000034602 14070037163 0020310 0 ustar 00root root 0000000 0000000 # Copyright (C) 2014, Ming Chen
#
# 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.
# This file is originated from https://github.com/python-cas/python-cas
# at commit ec1f2d4779625229398547b9234d0e9e874a2c9a
# some modifications have been made to be unicode coherent between python2 and python2
import six
from six.moves.urllib import parse as urllib_parse
from six.moves.urllib import request as urllib_request
from six.moves.urllib.request import Request
from uuid import uuid4
import datetime
class CASError(ValueError):
pass
class ReturnUnicode(object):
@staticmethod
def u(string, charset):
if not isinstance(string, six.text_type):
return string.decode(charset)
else:
return string
class SingleLogoutMixin(object):
@classmethod
def get_saml_slos(cls, logout_request):
"""returns saml logout ticket info"""
from lxml import etree
try:
root = etree.fromstring(logout_request)
return root.xpath(
"//samlp:SessionIndex",
namespaces={'samlp': "urn:oasis:names:tc:SAML:2.0:protocol"})
except etree.XMLSyntaxError:
pass
class CASClient(object):
def __new__(self, *args, **kwargs):
version = kwargs.pop('version')
if version in (1, '1'):
return CASClientV1(*args, **kwargs)
elif version in (2, '2'):
return CASClientV2(*args, **kwargs)
elif version in (3, '3'):
return CASClientV3(*args, **kwargs)
elif version == 'CAS_2_SAML_1_0':
return CASClientWithSAMLV1(*args, **kwargs)
raise ValueError('Unsupported CAS_VERSION %r' % version)
class CASClientBase(object):
logout_redirect_param_name = 'service'
def __init__(self, service_url=None, server_url=None,
extra_login_params=None, renew=False,
username_attribute=None):
self.service_url = service_url
self.server_url = server_url
self.extra_login_params = extra_login_params or {}
self.renew = renew
self.username_attribute = username_attribute
pass
def verify_ticket(self, ticket):
"""must return a triple"""
raise NotImplementedError()
def get_login_url(self):
"""Generates CAS login URL"""
params = {'service': self.service_url}
if self.renew:
params.update({'renew': 'true'})
params.update(self.extra_login_params)
url = urllib_parse.urljoin(self.server_url, 'login')
query = urllib_parse.urlencode(params)
return url + '?' + query
def get_logout_url(self, redirect_url=None):
"""Generates CAS logout URL"""
url = urllib_parse.urljoin(self.server_url, 'logout')
if redirect_url:
params = {self.logout_redirect_param_name: redirect_url}
url += '?' + urllib_parse.urlencode(params)
return url
def get_proxy_url(self, pgt):
"""Returns proxy url, given the proxy granting ticket"""
params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url})
return "%s/proxy?%s" % (self.server_url, params)
def get_proxy_ticket(self, pgt):
"""Returns proxy ticket given the proxy granting ticket"""
response = urllib_request.urlopen(self.get_proxy_url(pgt))
if response.code == 200:
from lxml import etree
root = etree.fromstring(response.read())
tickets = root.xpath(
"//cas:proxyTicket",
namespaces={"cas": "http://www.yale.edu/tp/cas"}
)
if len(tickets) == 1:
return tickets[0].text
errors = root.xpath(
"//cas:authenticationFailure",
namespaces={"cas": "http://www.yale.edu/tp/cas"}
)
if len(errors) == 1:
raise CASError(errors[0].attrib['code'], errors[0].text)
raise CASError("Bad http code %s" % response.code)
@staticmethod
def get_page_charset(page, default="utf-8"):
content_type = page.info().get('Content-type')
if content_type and "charset=" in content_type:
return content_type.split("charset=")[-1]
else:
return default
class CASClientV1(CASClientBase, ReturnUnicode):
"""CAS Client Version 1"""
logout_redirect_param_name = 'url'
def verify_ticket(self, ticket):
"""Verifies CAS 1.0 authentication ticket.
Returns username on success and None on failure.
"""
params = [('ticket', ticket), ('service', self.service_url)]
if self.renew:
params.append(('renew', 'true'))
url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' +
urllib_parse.urlencode(params))
page = urllib_request.urlopen(url)
try:
verified = page.readline().strip()
if verified == b'yes':
charset = self.get_page_charset(page, default="ascii")
user = self.u(page.readline().strip(), charset)
return user, None, None
else:
return None, None, None
finally:
page.close()
class CASClientV2(CASClientBase, ReturnUnicode):
"""CAS Client Version 2"""
url_suffix = 'serviceValidate'
logout_redirect_param_name = 'url'
def __init__(self, proxy_callback=None, *args, **kwargs):
"""proxy_callback is for V2 and V3 so V3 is subclass of V2"""
self.proxy_callback = proxy_callback
super(CASClientV2, self).__init__(*args, **kwargs)
def verify_ticket(self, ticket):
"""Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes"""
(response, charset) = self.get_verification_response(ticket)
return self.verify_response(response, charset)
def get_verification_response(self, ticket):
params = [('ticket', ticket), ('service', self.service_url)]
if self.renew:
params.append(('renew', 'true'))
if self.proxy_callback:
params.append(('pgtUrl', self.proxy_callback))
base_url = urllib_parse.urljoin(self.server_url, self.url_suffix)
url = base_url + '?' + urllib_parse.urlencode(params)
page = urllib_request.urlopen(url)
try:
charset = self.get_page_charset(page)
return (page.read(), charset)
finally:
page.close()
@classmethod
def parse_attributes_xml_element(cls, element, charset):
attributes = dict()
for attribute in element:
tag = cls.u(attribute.tag, charset).split(u"}").pop()
if tag in attributes:
if isinstance(attributes[tag], list):
attributes[tag].append(cls.u(attribute.text, charset))
else:
attributes[tag] = [attributes[tag]]
attributes[tag].append(cls.u(attribute.text, charset))
else:
if tag == u'attraStyle':
pass
else:
attributes[tag] = cls.u(attribute.text, charset)
return attributes
@classmethod
def verify_response(cls, response, charset):
user, attributes, pgtiou = cls.parse_response_xml(response, charset)
if len(attributes) == 0:
attributes = None
return user, attributes, pgtiou
@classmethod
def parse_response_xml(cls, response, charset):
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
user = None
attributes = {}
pgtiou = None
tree = ElementTree.fromstring(response)
if tree[0].tag.endswith('authenticationSuccess'):
for element in tree[0]:
if element.tag.endswith('user'):
user = cls.u(element.text, charset)
elif element.tag.endswith('proxyGrantingTicket'):
pgtiou = cls.u(element.text, charset)
elif element.tag.endswith('attributes'):
attributes = cls.parse_attributes_xml_element(element, charset)
return user, attributes, pgtiou
class CASClientV3(CASClientV2, SingleLogoutMixin):
"""CAS Client Version 3"""
url_suffix = 'serviceValidate'
logout_redirect_param_name = 'service'
@classmethod
def parse_attributes_xml_element(cls, element, charset):
attributes = dict()
for attribute in element:
tag = cls.u(attribute.tag, charset).split(u"}").pop()
if tag in attributes:
if isinstance(attributes[tag], list):
attributes[tag].append(cls.u(attribute.text, charset))
else:
attributes[tag] = [attributes[tag]]
attributes[tag].append(cls.u(attribute.text, charset))
else:
attributes[tag] = cls.u(attribute.text, charset)
return attributes
@classmethod
def verify_response(cls, response, charset):
return cls.parse_response_xml(response, charset)
SAML_1_0_NS = 'urn:oasis:names:tc:SAML:1.0:'
SAML_1_0_PROTOCOL_NS = '{' + SAML_1_0_NS + 'protocol' + '}'
SAML_1_0_ASSERTION_NS = '{' + SAML_1_0_NS + 'assertion' + '}'
SAML_ASSERTION_TEMPLATE = """
{ticket}
"""
class CASClientWithSAMLV1(CASClientV2, SingleLogoutMixin):
"""CASClient 3.0+ with SAML"""
def verify_ticket(self, ticket, **kwargs):
"""Verifies CAS 3.0+ XML-based authentication ticket and returns extended attributes.
@date: 2011-11-30
@author: Carlos Gonzalez Vila
Returns username and attributes on success and None,None on failure.
"""
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
page = self.fetch_saml_validation(ticket)
charset = self.get_page_charset(page)
try:
user = None
attributes = {}
response = page.read()
tree = ElementTree.fromstring(response)
# Find the authentication status
success = tree.find('.//' + SAML_1_0_PROTOCOL_NS + 'StatusCode')
if success is not None and success.attrib['Value'].endswith(':Success'):
# User is validated
name_identifier = tree.find('.//' + SAML_1_0_ASSERTION_NS + 'NameIdentifier')
if name_identifier is not None:
user = self.u(name_identifier.text, charset)
attrs = tree.findall('.//' + SAML_1_0_ASSERTION_NS + 'Attribute')
for at in attrs:
if self.username_attribute in list(at.attrib.values()):
user = self.u(
at.find(SAML_1_0_ASSERTION_NS + 'AttributeValue').text,
charset
)
attributes[u'uid'] = user
values = at.findall(SAML_1_0_ASSERTION_NS + 'AttributeValue')
key = self.u(at.attrib['AttributeName'], charset)
if len(values) > 1:
values_array = []
for v in values:
values_array.append(self.u(v.text, charset))
attributes[key] = values_array
else:
attributes[key] = self.u(values[0].text, charset)
return user, attributes, None
finally:
page.close()
def fetch_saml_validation(self, ticket):
# We do the SAML validation
headers = {
'soapaction': 'http://www.oasis-open.org/committees/security',
'cache-control': 'no-cache',
'pragma': 'no-cache',
'accept': 'text/xml',
'connection': 'keep-alive',
'content-type': 'text/xml; charset=utf-8',
}
params = [('TARGET', self.service_url)]
saml_validate_url = urllib_parse.urljoin(
self.server_url, 'samlValidate',
)
request = Request(
saml_validate_url + '?' + urllib_parse.urlencode(params),
self.get_saml_assertion(ticket),
headers,
)
return urllib_request.urlopen(request)
@classmethod
def get_saml_assertion(cls, ticket):
"""
http://www.jasig.org/cas/protocol#samlvalidate-cas-3.0
SAML request values:
RequestID [REQUIRED]:
unique identifier for the request
IssueInstant [REQUIRED]:
timestamp of the request
samlp:AssertionArtifact [REQUIRED]:
the valid CAS Service Ticket obtained as a response parameter at login.
"""
# RequestID [REQUIRED] - unique identifier for the request
request_id = uuid4()
# e.g. 2014-06-02T09:21:03.071189
timestamp = datetime.datetime.now().isoformat()
return SAML_ASSERTION_TEMPLATE.format(
request_id=request_id,
timestamp=timestamp,
ticket=ticket,
).encode('utf8')
django-cas-server-1.3.1/cas_server/default_settings.py 0000664 0000000 0000000 00000026652 14070037163 0023114 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# (c) 2015-2016 Valentin Samir
"""Default values for the app's settings"""
from django.conf import settings
from django.templatetags.static import static
from importlib import import_module
import sys
if sys.version_info < (3, ):
from django.utils.translation import ugettext_lazy as _
else:
from django.utils.translation import gettext_lazy as _
try:
#: URL to the logo showed in the up left corner on the default templates.
CAS_LOGO_URL = static("cas_server/logo.png")
#: URL to the favicon (shortcut icon) used by the default templates. Default is a key icon.
CAS_FAVICON_URL = static("cas_server/favicon.ico")
# is settings.DEBUG is False and collectstatics has not been run yet, the static function will
# raise a ValueError because the file is not found.
except ValueError:
#: URL to the logo showed in the up left corner on the default templates.
CAS_LOGO_URL = None
#: URL to the favicon (shortcut icon) used by the default templates. Default is a key icon.
CAS_FAVICON_URL = None
#: Show the powered by footer if set to ``True``
CAS_SHOW_POWERED = True
#: URLs to css and javascript external components.
CAS_COMPONENT_URLS = {
"bootstrap3_css": "//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
"bootstrap3_js": "//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js",
"html5shiv": "//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js",
"respond": "//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js",
"bootstrap4_css": "//stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css",
"bootstrap4_js": "//stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js",
"jquery": "//code.jquery.com/jquery.min.js",
}
#: Path to the template showed on /login then the user is not autenticated.
CAS_LOGIN_TEMPLATE = 'cas_server/bs4/login.html'
#: Path to the template showed on /login?service=... then the user is authenticated and has asked
#: to be warned before being connected to a service.
CAS_WARN_TEMPLATE = 'cas_server/bs4/warn.html'
#: Path to the template showed on /login then to user is authenticated.
CAS_LOGGED_TEMPLATE = 'cas_server/bs4/logged.html'
#: Path to the template showed on /logout then to user is being disconnected.
CAS_LOGOUT_TEMPLATE = 'cas_server/bs4/logout.html'
#: Should we redirect users to /login after they logged out instead of displaying
#: :obj:`CAS_LOGOUT_TEMPLATE`.
CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT = False
#: A dotted path to a class or a class implementing cas_server.auth.AuthUser.
CAS_AUTH_CLASS = 'cas_server.auth.DjangoAuthUser'
#: Path to certificate authorities file. Usually on linux the local CAs are in
#: /etc/ssl/certs/ca-certificates.crt. ``True`` tell requests to use its internal certificat
#: authorities.
CAS_PROXY_CA_CERTIFICATE_PATH = True
#: Maximum number of parallel single log out requests send
#: if more requests need to be send, there are queued
CAS_SLO_MAX_PARALLEL_REQUESTS = 10
#: Timeout for a single SLO request in seconds.
CAS_SLO_TIMEOUT = 5
#: Shared to transmit then using the view :class:`cas_server.views.Auth`
CAS_AUTH_SHARED_SECRET = ''
#: Max time after with the user MUST reauthenticate. Let it to `None` for no max time.
#: This can be used to force refreshing cached informations only available upon user authentication
#: like the user attributes in federation mode or with the ldap auth in bind mode.
CAS_TGT_VALIDITY = None
#: Number of seconds the service tickets and proxy tickets are valid. This is the maximal time
#: between ticket issuance by the CAS and ticket validation by an application.
CAS_TICKET_VALIDITY = 60
#: Number of seconds the proxy granting tickets are valid.
CAS_PGT_VALIDITY = 3600
#: Number of seconds a ticket is kept in the database before sending Single Log Out request and
#: being cleared.
CAS_TICKET_TIMEOUT = 24*3600
#: All CAS implementation MUST support ST and PT up to 32 chars,
#: PGT and PGTIOU up to 64 chars and it is RECOMMENDED that all
#: tickets up to 256 chars are supports so we use 64 for the default
#: len.
CAS_TICKET_LEN = 64
#: alias of :obj:`settings.CAS_TICKET_LEN`
CAS_LT_LEN = getattr(settings, 'CAS_TICKET_LEN', CAS_TICKET_LEN)
#: alias of :obj:`settings.CAS_TICKET_LEN`
#: Services MUST be able to accept service tickets of up to 32 characters in length.
CAS_ST_LEN = getattr(settings, 'CAS_TICKET_LEN', CAS_TICKET_LEN)
#: alias of :obj:`settings.CAS_TICKET_LEN`
#: Back-end services MUST be able to accept proxy tickets of up to 32 characters.
CAS_PT_LEN = getattr(settings, 'CAS_TICKET_LEN', CAS_TICKET_LEN)
#: alias of :obj:`settings.CAS_TICKET_LEN`
#: Services MUST be able to handle proxy-granting tickets of up to 64
CAS_PGT_LEN = getattr(settings, 'CAS_TICKET_LEN', CAS_TICKET_LEN)
#: alias of :obj:`settings.CAS_TICKET_LEN`
#: Services MUST be able to handle PGTIOUs of up to 64 characters in length.
CAS_PGTIOU_LEN = getattr(settings, 'CAS_TICKET_LEN', CAS_TICKET_LEN)
#: Prefix of login tickets.
CAS_LOGIN_TICKET_PREFIX = u'LT'
#: Prefix of service tickets. Service tickets MUST begin with the characters ST so you should not
#: change this.
CAS_SERVICE_TICKET_PREFIX = u'ST'
#: Prefix of proxy ticket. Proxy tickets SHOULD begin with the characters, PT.
CAS_PROXY_TICKET_PREFIX = u'PT'
#: Prefix of proxy granting ticket. Proxy-granting tickets SHOULD begin with the characters PGT.
CAS_PROXY_GRANTING_TICKET_PREFIX = u'PGT'
#: Prefix of proxy granting ticket IOU. Proxy-granting ticket IOUs SHOULD begin with the characters
#: PGTIOU.
CAS_PROXY_GRANTING_TICKET_IOU_PREFIX = u'PGTIOU'
#: Host for the SQL server.
CAS_SQL_HOST = 'localhost'
#: Username for connecting to the SQL server.
CAS_SQL_USERNAME = ''
#: Password for connecting to the SQL server.
CAS_SQL_PASSWORD = ''
#: Database name.
CAS_SQL_DBNAME = ''
#: Database charset.
CAS_SQL_DBCHARSET = 'utf8'
#: The query performed upon user authentication.
CAS_SQL_USER_QUERY = 'SELECT user AS username, pass AS password, users.* FROM users WHERE user = %s'
#: The method used to check the user password. Must be one of ``"crypt"``, ``"ldap"``,
#: ``"hex_md5"``, ``"hex_sha1"``, ``"hex_sha224"``, ``"hex_sha256"``, ``"hex_sha384"``,
#: ``"hex_sha512"``, ``"plain"``.
CAS_SQL_PASSWORD_CHECK = 'crypt'
#: charset the SQL users passwords was hash with
CAS_SQL_PASSWORD_CHARSET = "utf-8"
#: Address of the LDAP server
CAS_LDAP_SERVER = 'localhost'
#: LDAP user bind address, for example ``"cn=admin,dc=crans,dc=org"`` for connecting to the LDAP
#: server.
CAS_LDAP_USER = None
#: LDAP connection password
CAS_LDAP_PASSWORD = None
#: LDAP seach base DN, for example ``"ou=data,dc=crans,dc=org"``.
CAS_LDAP_BASE_DN = None
#: LDAP search filter for searching user by username. User inputed usernames are escaped using
#: :func:`ldap3.utils.conv.escape_bytes`.
CAS_LDAP_USER_QUERY = "(uid=%s)"
#: LDAP attribute used for users usernames
CAS_LDAP_USERNAME_ATTR = "uid"
#: LDAP attribute used for users passwords
CAS_LDAP_PASSWORD_ATTR = "userPassword"
#: The method used to check the user password. Must be one of ``"crypt"``, ``"ldap"``,
#: ``"hex_md5"``, ``"hex_sha1"``, ``"hex_sha224"``, ``"hex_sha256"``, ``"hex_sha384"``,
#: ``"hex_sha512"``, ``"plain"``, ``"bind"``.
CAS_LDAP_PASSWORD_CHECK = "ldap"
#: charset the LDAP users passwords was hash with
CAS_LDAP_PASSWORD_CHARSET = "utf-8"
#: This parameter is only used then ``CAS_LDAP_PASSWORD_CHECK`` is set to ``"bind"``.
#:
#: * if ``0`` the user attributes are retrieved by connecting to the ldap as ``CAS_LDAP_USER``.
#: * if ``1`` the user attributes are retrieve then the user authenticate using
#: the user credentials. These attributes are then cached for the session.
#:
#: The default is ``0``.
CAS_LDAP_ATTRS_VIEW = 0
#: Username of the test user.
CAS_TEST_USER = 'test'
#: Password of the test user.
CAS_TEST_PASSWORD = 'test'
#: Attributes of the test user.
CAS_TEST_ATTRIBUTES = {
'nom': 'Nymous',
'prenom': 'Ano',
'email': 'anonymous@example.net',
'alias': ['demo1', 'demo2']
}
#: A :class:`bool` for activatinc the hability to fetch tickets using javascript.
CAS_ENABLE_AJAX_AUTH = False
#: A :class:`bool` for activating the federated mode
CAS_FEDERATE = False
#: Time after witch the cookie use for “remember my identity provider” expire (one week).
CAS_FEDERATE_REMEMBER_TIMEOUT = 604800
#: A :class:`bool` for diplaying a warning on html pages then a new version of the application
#: is avaible. Once closed by a user, it is not displayed to this user until the next new version.
CAS_NEW_VERSION_HTML_WARNING = True
#: A :class:`bool` for sending emails to ``settings.ADMINS`` when a new version is available.
CAS_NEW_VERSION_EMAIL_WARNING = True
#: URL to the pypi json of the application. Used to retreive the version number of the last version.
#: You should not change it.
CAS_NEW_VERSION_JSON_URL = "https://pypi.org/pypi/django-cas-server/json"
#: If the service message should be displayed on the login page
CAS_SHOW_SERVICE_MESSAGES = True
#: Messages displayed in a info-box on the html pages of the default templates.
#: ``CAS_INFO_MESSAGES`` is a :class:`dict` mapping message name to a message :class:`dict`.
#: A message :class:`dict` has 3 keys:
#:
#: * ``message``: A :class:`unicode`, the message to display, potentially wrapped around
#: ugettex_lazy
#: * ``discardable``: A :class:`bool`, specify if the users can close the message info-box
#: * ``type``: One of info, success, info, warning, danger. The type of the info-box.
#:
#: ``CAS_INFO_MESSAGES`` contains by default one message, ``cas_explained``, which explain
#: roughly the purpose of a CAS.
CAS_INFO_MESSAGES = {
"cas_explained": {
"message": _(
u"The Central Authentication Service grants you access to most of our websites by "
u"authenticating only once, so you don't need to type your credentials again unless "
u"your session expires or you logout."
),
"discardable": True,
"type": "info", # one of info, success, info, warning, danger
},
}
#: :class:`list` of message names. Order in which info-box messages are displayed.
#: Let the list empty to disable messages display.
CAS_INFO_MESSAGES_ORDER = []
GLOBALS = globals().copy()
for name, default_value in GLOBALS.items():
# only care about parameter begining by CAS_
if name.startswith("CAS_"):
# get the current setting value, falling back to default_value
value = getattr(settings, name, default_value)
# set the setting value to its value if defined, ellse to the default_value.
setattr(settings, name, value)
# Allow the user defined CAS_COMPONENT_URLS to omit not changed values
MERGED_CAS_COMPONENT_URLS = CAS_COMPONENT_URLS.copy()
MERGED_CAS_COMPONENT_URLS.update(settings.CAS_COMPONENT_URLS)
settings.CAS_COMPONENT_URLS = MERGED_CAS_COMPONENT_URLS
# if the federated mode is enabled, we must use the :class`cas_server.auth.CASFederateAuth` auth
# backend.
if settings.CAS_FEDERATE:
settings.CAS_AUTH_CLASS = "cas_server.auth.CASFederateAuth"
#: SessionStore class depending of :django:setting:`SESSION_ENGINE`
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
django-cas-server-1.3.1/cas_server/federate.py 0000664 0000000 0000000 00000013335 14070037163 0021321 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# (c) 2016 Valentin Samir
"""federated mode helper classes"""
from .default_settings import SessionStore
from django.db import IntegrityError
from .cas import CASClient
from .models import FederatedUser, FederateSLO, User
import logging
from six.moves import urllib
#: logger facility
logger = logging.getLogger(__name__)
class CASFederateValidateUser(object):
"""
Class CAS client used to authenticate the user again a CAS provider
:param cas_server.models.FederatedIendityProvider provider: The provider to use for
authenticate the user.
:param unicode service_url: The service url to transmit to the ``provider``.
"""
#: the provider returned username
username = None
#: the provider returned attributes
attributs = {}
#: the CAS client instance
client = None
#: the provider returned username this the provider suffix appended
federated_username = None
#: the identity provider
provider = None
def __init__(self, provider, service_url, renew=False):
self.provider = provider
self.client = CASClient(
service_url=service_url,
version=provider.cas_protocol_version,
server_url=provider.server_url,
renew=renew,
)
def get_login_url(self):
"""
:return: the CAS provider login url
:rtype: unicode
"""
return self.client.get_login_url()
def get_logout_url(self, redirect_url=None):
"""
:param redirect_url: The url to redirect to after logout from the provider, if provided.
:type redirect_url: :obj:`unicode` or :obj:`NoneType`
:return: the CAS provider logout url
:rtype: unicode
"""
return self.client.get_logout_url(redirect_url)
def verify_ticket(self, ticket):
"""
test ``ticket`` against the CAS provider, if valid, create a
:class:`FederatedUser` matching provider returned
username and attributes.
:param unicode ticket: The ticket to validate against the provider CAS
:return: ``True`` if the validation succeed, else ``False``.
:rtype: bool
"""
try:
username, attributs = self.client.verify_ticket(ticket)[:2]
except urllib.error.URLError:
return False
if username is not None:
if attributs is None:
attributs = {}
attributs["provider"] = self.provider.suffix
self.username = username
self.attributs = attributs
user = FederatedUser.objects.update_or_create(
username=username,
provider=self.provider,
defaults=dict(attributs=attributs, ticket=ticket)
)[0]
user.save()
self.federated_username = user.federated_username
return True
else:
return False
@staticmethod
def register_slo(username, session_key, ticket):
"""
association a ``ticket`` with a (``username``, ``session_key``) for processing later SLO
request by creating a :class:`cas_server.models.FederateSLO` object.
:param unicode username: A logged user username, with the ``@`` component.
:param unicode session_key: A logged user session_key matching ``username``.
:param unicode ticket: A ticket used to authentication ``username`` for the session
``session_key``.
"""
try:
FederateSLO.objects.create(
username=username,
session_key=session_key,
ticket=ticket
)
except IntegrityError: # pragma: no cover (ignore if the FederateSLO already exists)
pass
def clean_sessions(self, logout_request):
"""
process a SLO request: Search for ticket values in ``logout_request``. For each
ticket value matching a :class:`cas_server.models.FederateSLO`, disconnect the
corresponding user.
:param unicode logout_request: An XML document contening one or more Single Log Out
requests.
"""
try:
slos = self.client.get_saml_slos(logout_request) or []
except NameError: # pragma: no cover (should not happen)
slos = []
for slo in slos:
for federate_slo in FederateSLO.objects.filter(ticket=slo.text):
logger.info(
"Got an SLO requests for ticket %s, logging out user %s" % (
federate_slo.username,
federate_slo.ticket
)
)
session = SessionStore(session_key=federate_slo.session_key)
session.flush()
try:
user = User.objects.get(
username=federate_slo.username,
session_key=federate_slo.session_key
)
user.logout()
user.delete()
except User.DoesNotExist: # pragma: no cover (should not happen)
pass
federate_slo.delete()
django-cas-server-1.3.1/cas_server/forms.py 0000664 0000000 0000000 00000020030 14070037163 0020656 0 ustar 00root root 0000000 0000000 # This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# (c) 2015-2016 Valentin Samir
"""forms for the app"""
from .default_settings import settings
from django import forms
from django.forms import widgets
import cas_server.utils as utils
import cas_server.models as models
import sys
if sys.version_info < (3, ):
from django.utils.translation import ugettext_lazy as _
else:
from django.utils.translation import gettext_lazy as _
class BootsrapForm(forms.Form):
"""
Bases: :class:`django.forms.Form`
Form base class to use boostrap then rendering the form fields
"""
def __init__(self, *args, **kwargs):
super(BootsrapForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
# Only tweak the field if it will be displayed
if not isinstance(field.widget, widgets.HiddenInput):
attrs = {}
if (
isinstance(field.widget, (widgets.Input, widgets.Select, widgets.Textarea)) and
not isinstance(field.widget, (widgets.CheckboxInput,))
):
attrs['class'] = "form-control"
if isinstance(field.widget, (widgets.Input, widgets.Textarea)) and field.label:
attrs["placeholder"] = field.label
if field.required:
attrs["required"] = "required"
field.widget.attrs.update(attrs)
class BaseLogin(BootsrapForm):
"""
Bases: :class:`BootsrapForm`
Base form with all field possibly hidden on the login pages
"""
#: The service url for which the user want a ticket
service = forms.CharField(widget=forms.HiddenInput(), required=False)
#: A valid LoginTicket to prevent POST replay
lt = forms.CharField(widget=forms.HiddenInput(), required=False)
#: Is the service asking the authentication renewal ?
renew = forms.BooleanField(widget=forms.HiddenInput(), required=False)
#: Url to redirect to if the authentication fail (user not authenticated or bad service)
gateway = forms.CharField(widget=forms.HiddenInput(), required=False)
method = forms.CharField(widget=forms.HiddenInput(), required=False)
class WarnForm(BaseLogin):
"""
Bases: :class:`BaseLogin`
Form used on warn page before emiting a ticket
"""
#: ``True`` if the user has been warned of the ticket emission
warned = forms.BooleanField(widget=forms.HiddenInput(), required=False)
class FederateSelect(BaseLogin):
"""
Bases: :class:`BaseLogin`
Form used on the login page when ``settings.CAS_FEDERATE`` is ``True``
allowing the user to choose an identity provider.
"""
#: The providers the user can choose to be used as authentication backend
provider = forms.ModelChoiceField(
queryset=models.FederatedIendityProvider.objects.filter(display=True).order_by(
"pos",
"verbose_name",
"suffix"
),
to_field_name="suffix",
label=_('Identity provider'),
)
#: A checkbox to ask to be warn before emiting a ticket for another service
warn = forms.BooleanField(
label=_('Warn me before logging me into other sites.'),
required=False
)
#: A checkbox to remember the user choices of :attr:`provider`
remember = forms.BooleanField(label=_('Remember the identity provider'), required=False)
class UserCredential(BaseLogin):
"""
Bases: :class:`BaseLogin`
Form used on the login page to retrive user credentials
"""
#: The user username
username = forms.CharField(
label=_('username'),
widget=forms.TextInput(attrs={'autofocus': 'autofocus'})
)
#: The user password
password = forms.CharField(label=_('password'), widget=forms.PasswordInput)
#: A checkbox to ask to be warn before emiting a ticket for another service
warn = forms.BooleanField(
label=_('Warn me before logging me into other sites.'),
required=False
)
def clean(self):
"""
Validate that the submited :attr:`username` and :attr:`password` are valid
:raises django.forms.ValidationError: if the :attr:`username` and :attr:`password`
are not valid.
:return: The cleaned POST data
:rtype: dict
"""
cleaned_data = super(UserCredential, self).clean()
if "username" in cleaned_data and "password" in cleaned_data:
auth = utils.import_attr(settings.CAS_AUTH_CLASS)(cleaned_data["username"])
if auth.test_password(cleaned_data["password"]):
cleaned_data["username"] = auth.username
else:
raise forms.ValidationError(
_(u"The credentials you provided cannot be determined to be authentic.")
)
return cleaned_data
class FederateUserCredential(UserCredential):
"""
Bases: :class:`UserCredential`
Form used on a auto submited page for linking the views
:class:`FederateAuth` and
:class:`LoginView`.
On successful authentication on a provider, in the view
:class:`FederateAuth` a
:class:`FederatedUser` is created by
:meth:`cas_server.federate.CASFederateValidateUser.verify_ticket` and the user is redirected
to :class:`LoginView`. This form is then automatically filled
with infos matching the created :class:`FederatedUser`
using the ``ticket`` as one time password and submited using javascript. If javascript is
not enabled, a connect button is displayed.
This stub authentication form, allow to implement the federated mode with very few
modificatons to the :class:`LoginView` view.
"""
def __init__(self, *args, **kwargs):
super(FederateUserCredential, self).__init__(*args, **kwargs)
# All fields are hidden and auto filled by the /login view logic
for name, field in self.fields.items():
field.widget = forms.HiddenInput()
self[name].display = False
def clean(self):
"""
Validate that the submited :attr:`username` and :attr:`password` are valid using
the :class:`CASFederateAuth` auth class.
:raises django.forms.ValidationError: if the :attr:`username` and :attr:`password`
do not correspond to a :class:`FederatedUser`.
:return: The cleaned POST data
:rtype: dict
"""
cleaned_data = super(FederateUserCredential, self).clean()
try:
user = models.FederatedUser.get_from_federated_username(cleaned_data["username"])
user.ticket = ""
user.save()
# should not happed as if the FederatedUser do not exists, super should
# raise before a ValidationError("bad user")
except models.FederatedUser.DoesNotExist: # pragma: no cover (should not happend)
raise forms.ValidationError(
_(u"User not found in the temporary database, please try to reconnect")
)
return cleaned_data
class TicketForm(forms.ModelForm):
"""
Bases: :class:`django.forms.ModelForm`
Form for Tickets in the admin interface
"""
class Meta:
model = models.Ticket
exclude = []
service = forms.CharField(label=_('service'), widget=forms.TextInput)
django-cas-server-1.3.1/cas_server/locale/ 0000775 0000000 0000000 00000000000 14070037163 0020422 5 ustar 00root root 0000000 0000000 django-cas-server-1.3.1/cas_server/locale/fr/ 0000775 0000000 0000000 00000000000 14070037163 0021031 5 ustar 00root root 0000000 0000000 django-cas-server-1.3.1/cas_server/locale/fr/LC_MESSAGES/ 0000775 0000000 0000000 00000000000 14070037163 0022616 5 ustar 00root root 0000000 0000000 django-cas-server-1.3.1/cas_server/locale/fr/LC_MESSAGES/django.mo 0000664 0000000 0000000 00000023601 14070037163 0024417 0 ustar 00root root 0000000 0000000 M g - = \ s
7
>
> 0 6 o ' 4 \ w 0 ] = T
<