diff --git a/.flake8 b/.flake8
new file mode 100644
index 00000000..3b2e86e6
--- /dev/null
+++ b/.flake8
@@ -0,0 +1,4 @@
+[flake8]
+ignore = E731,W503,W504,E501
+max-complexity = 50
+max-line-length = 200
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 00000000..ac0a9f6c
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,3 @@
+# These are supported funding model platforms
+
+github: [SAML-Toolkits]
diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml
new file mode 100644
index 00000000..c17b3107
--- /dev/null
+++ b/.github/workflows/python-package.yml
@@ -0,0 +1,100 @@
+# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
+# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
+
+name: Python package
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+ branches:
+ - master
+
+jobs:
+ test_py3:
+ runs-on: ubuntu-22.04
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version:
+ - "3.7"
+ - "3.8"
+ - "3.9"
+ - "3.10"
+ - "3.11"
+ - "3.12"
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ - uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ hashFiles('**/pyproject.toml') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-
+ - name: Install dependencies
+ run: |
+ pip install -U setuptools
+ sudo apt-get update -qq
+ sudo apt-get install -qq swig libxml2-dev libxmlsec1-dev
+ make install-req
+ make install-test
+ - name: Test
+ run: make pytest
+ lint:
+ runs-on: ubuntu-22.04
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ hashFiles('**/pyproject.toml') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-
+ - name: Install dependencies
+ run: |
+ pip install -U setuptools
+ sudo apt-get update -qq
+ sudo apt-get install -qq swig libxml2-dev libxmlsec1-dev
+ make install-req
+ make install-lint
+ - name: Run linters
+ run: |
+ make flake8
+ make black
+ coveralls:
+ if: ${{ github.secret_source == 'Actions' }}
+ runs-on: ubuntu-22.04
+ environment: CI
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ hashFiles('**/pyproject.toml') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-
+ - name: Install dependencies
+ run: |
+ pip install -U setuptools
+ sudo apt-get update -qq
+ sudo apt-get install -qq swig libxml2-dev libxmlsec1-dev
+ make install-req
+ make install-test
+ - name: Run coveralls
+ env:
+ COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
+ run: |
+ pip install coveralls
+ make coverage
+ make coveralls
diff --git a/.gitignore b/.gitignore
index c16b943e..7504184a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,6 +14,7 @@ __pycache_
/*.eg
*.egg-info
/eggs
+/.eggs
/build
/dist
/venv
@@ -21,6 +22,8 @@ __pycache_
.pypirc
/.idea
.mypy_cache/
+.pytest_cache
+poetry.lock
*.key
*.crt
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 3ddd4236..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-language: python
-python:
- - '2.7'
- - '3.5'
- - '3.6'
-
-matrix:
- include:
- - python: '3.7'
- dist: xenial # required for Python >= 3.7 (travis-ci/travis-ci#9069)
-
-install:
- - sudo apt-get update -qq
- - sudo apt-get install -qq swig python-dev libxml2-dev libxmlsec1-dev
- - 'travis_retry pip install .'
- - 'travis_retry pip install -e ".[test]"'
-
-script:
- - 'coverage run --source=src/onelogin/saml2 --rcfile=tests/coverage.rc setup.py test'
- - 'coverage report -m --rcfile=tests/coverage.rc'
-# - 'pylint src/onelogin/saml2 --rcfile=tests/pylint.rc'
- - 'flake8 .'
-
-after_success: 'coveralls'
diff --git a/LICENSE b/LICENSE
index 1c8f814e..c141165e 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,5 @@
-Copyright (c) 2010-2018 OneLogin, Inc.
+Copyright (c) 2010-2022 OneLogin, Inc.
+Copyright (c) 2023 IAM Digital Services, SL.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
diff --git a/MANIFEST.in b/MANIFEST.in
deleted file mode 100644
index 9b0be815..00000000
--- a/MANIFEST.in
+++ /dev/null
@@ -1,6 +0,0 @@
-include README.md
-include LICENSE
-recursive-include src *.py
-recursive-include src *.xsd
-recursive-exclude * __pycache__
-recursive-exclude * *.py[co]
diff --git a/Makefile b/Makefile
new file mode 100644
index 00000000..31efe284
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,43 @@
+PIP=pip
+BLACK=black
+FLAKE8=flake8
+PYTEST=pytest
+COVERAGE=coverage
+COVERAGE_CONFIG=tests/coverage.rc
+COVERALLS=coveralls
+MAIN_SOURCE=src/onelogin/saml2
+DEMOS=demo-django demo-flask demo-tornado demo_pyramid
+TESTS=tests/src/OneLogin/saml2_tests
+SOURCES=$(MAIN_SOURCE) $(DEMOS) $(TESTS)
+
+install-req:
+ $(PIP) install .
+
+install-test:
+ $(PIP) install -e ".[test]"
+
+install-lint:
+ $(PIP) install -e ".[lint]"
+
+pytest:
+ $(PYTEST)
+
+coverage:
+ $(COVERAGE) run -m $(PYTEST)
+ $(COVERAGE) report -m
+
+coveralls:
+ $(COVERALLS)
+
+black:
+ $(BLACK) $(SOURCES)
+
+flake8:
+ $(FLAKE8) $(SOURCES)
+
+clean:
+ rm -rf .pytest_cache/
+ rm -rf .eggs/
+ find . -type d -name "__pycache__" -exec rm -r {} +
+ find . -type d -name "*.egg-info" -exec rm -r {} +
+ rm .coverage
diff --git a/README.md b/README.md
index e652786e..ff71357f 100644
--- a/README.md
+++ b/README.md
@@ -1,19 +1,24 @@
-# OneLogin's SAML Python Toolkit (compatible with Python3)
+# SAML Python3 Toolkit
-[](http://travis-ci.org/onelogin/python3-saml)
-[](https://coveralls.io/github/onelogin/python3-saml?branch=master)
+[](https://github.com/SAML-Toolkits/python3-saml/actions/workflows/python-package.yml)
+
+[](https://coveralls.io/github/SAML-Toolkits/python3-saml?branch=master)
[](https://pypi.python.org/pypi/python3-saml)
-
-
+
Add SAML support to your Python software using this library.
-Forget those complicated libraries and use the open source library provided
-and supported by OneLogin Inc.
+Forget those complicated libraries and use the open source library provided by the SAML tool community.
-This version supports Python3. There is a separate version that only support Python2: [python-saml](https://github.com/onelogin/python-saml)
+This version supports Python3. Python 2 support was deprecated on Jan 1st, 2020: [python-saml](https://github.com/onelogin/python-saml)
#### Warning ####
+Version 1.16.X is the latest version supporting Python2, consider its use deprecated. 1.17 won't be Python2 and old Python3 compatible.
+
+Version 1.13.0 sets sha256 and rsa-sha256 as default algorithms
+
+Version 1.8.0 sets strict mode active by default
+
Update ``python3-saml`` to ``1.5.0``, this version includes security improvements for preventing XEE and Xpath Injections.
Update ``python3-saml`` to ``1.4.0``, this version includes a fix for the [CVE-2017-11427](https://www.cvedetails.com/cve/CVE-2017-11427/) vulnerability.
@@ -30,7 +35,12 @@ Update ``python3-saml`` to ``>= 1.2.1``, ``1.2.0`` had a bug on signature valida
#### Security Guidelines ####
-If you believe you have discovered a security vulnerability in this toolkit, please report it at https://www.onelogin.com/security with a description. We follow responsible disclosure guidelines, and will work with you to quickly find a resolution.
+If you believe you have discovered a security vulnerability in this toolkit, please report it by mail to the maintainer: sixto.martin.garcia+security@gmail.com
+
+### Sponsors
+Thanks to the following sponsors for their support:
+
+[](https://www.maykinmedia.nl)
Why add SAML support to my software?
------------------------------------
@@ -58,7 +68,7 @@ since 2002, but lately it is becoming popular due its advantages:
General Description
-------------------
-OneLogin's SAML Python toolkit lets you turn your Python application into a SP
+SAML Python toolkit lets you turn your Python application into a SP
(Service Provider) that can be connected to an IdP (Identity Provider).
**Supports:**
@@ -79,20 +89,19 @@ OneLogin's SAML Python toolkit lets you turn your Python application into a SP
* **Easy to use** - Programmer will be allowed to code high-level and
low-level programming, 2 easy to use APIs are available.
* **Tested** - Thoroughly tested.
- * **Popular** - OneLogin's customers use it. Add easy support to your Django/Flask web projects.
Installation
------------
### Dependencies ###
- * python 2.7 // python 3.6
+ * python => 3.7
* [xmlsec](https://pypi.python.org/pypi/xmlsec) Python bindings for the XML Security Library.
+ * [lxml](https://pypi.python.org/pypi/lxml) Python bindings for the libxml2 and libxslt libraries.
* [isodate](https://pypi.python.org/pypi/isodate) An ISO 8601 date/time/
duration parser and formatter
- * [defusedxml](https://pypi.python.org/pypi/defusedxml) XML bomb protection for Python stdlib modules
-Review the ``setup.py`` file to know the version of the library that ``python3-saml`` is using
+Review the ``pyproject.toml`` file to know the version of the library that ``python3-saml`` is using
### Code ###
@@ -100,10 +109,10 @@ Review the ``setup.py`` file to know the version of the library that ``python3-s
The toolkit is hosted on GitHub. You can download it from:
- * Latest release: https://github.com/onelogin/python3-saml/releases/latest
- * Master repo: https://github.com/onelogin/python3-saml/tree/master
+ * Latest release: https://github.com/saml-toolkits/python3-saml/releases/latest
+ * Master repo: https://github.com/saml-toolkits/python3-saml/tree/master
-Copy the core of the library ``(src/onelogin/saml2 folder)`` and merge the ``setup.py`` inside the Python application. (Each application has its structure so take your time to locate the Python SAML toolkit in the best place).
+Find the core of the library at ``src/onelogin/saml2`` folder.
#### Option 2. Download from pypi ####
@@ -116,6 +125,14 @@ $ pip install python3-saml
If you want to know how a project can handle python packages review this [guide](https://packaging.python.org/en/latest/tutorial.html) and review this [sampleproject](https://github.com/pypa/sampleproject)
+#### NOTE ####
+To avoid ``libxml2`` library version incompatibilities between ``xmlsec`` and ``lxml`` it is recommended that ``lxml`` is not installed from binary.
+
+This can be ensured by executing:
+```
+$ pip install --force-reinstall --no-binary lxml lxml
+```
+
Security Warning
----------------
@@ -124,12 +141,41 @@ your environment is not secure and will be exposed to attacks.
In production also we highly recommend to register on the settings the IdP certificate instead of using the fingerprint method. The fingerprint, is a hash, so at the end is open to a collision attack that can end on a signature validation bypass. Other SAML toolkits deprecated that mechanism, we maintain it for compatibility and also to be used on test environment.
+
+### Avoiding Open Redirect attacks ###
+
+Some implementations uses the RelayState parameter as a way to control the flow when SSO and SLO succeeded. So basically the
+user is redirected to the value of the RelayState.
+
+If you are using Signature Validation on the HTTP-Redirect binding, you will have the RelayState value integrity covered, otherwise, and
+on HTTP-POST binding, you can't trust the RelayState so before
+executing the validation, you need to verify that its value belong
+a trusted and expected URL.
+
+Read more about Open Redirect [CWE-601](https://cwe.mitre.org/data/definitions/601.html).
+
+### Avoiding Replay attacks ###
+
+A replay attack is basically try to reuse an intercepted valid SAML Message in order to impersonate a SAML action (SSO or SLO).
+
+SAML Messages have a limited timelife (NotBefore, NotOnOrAfter) that
+make harder this kind of attacks, but they are still possible.
+
+In order to avoid them, the SP can keep a list of SAML Messages or Assertion IDs already validated and processed. Those values only need
+to be stored the amount of time of the SAML Message life time, so
+we don't need to store all processed message/assertion Ids, but the most recent ones.
+
+The OneLogin_Saml2_Auth class contains the [get_last_request_id](https://github.com/onelogin/python3-saml/blob/ab62b0d6f3e5ac2ae8e95ce3ed2f85389252a32d/src/onelogin/saml2/auth.py#L357), [get_last_message_id](https://github.com/onelogin/python3-saml/blob/ab62b0d6f3e5ac2ae8e95ce3ed2f85389252a32d/src/onelogin/saml2/auth.py#L364) and [get_last_assertion_id](https://github.com/onelogin/python3-saml/blob/ab62b0d6f3e5ac2ae8e95ce3ed2f85389252a32d/src/onelogin/saml2/auth.py#L371) methods to retrieve the IDs
+
+Checking that the ID of the current Message/Assertion does not exists in the list of the ones already processed will prevent replay attacks.
+
+
Getting Started
---------------
### Knowing the toolkit ###
-The new OneLogin SAML Toolkit contains different folders (``certs``, ``lib``, ``demo-django``, ``demo-flask`` and ``tests``) and some files.
+The new SAML Toolkit contains different folders (``certs``, ``lib``, ``demo-django``, ``demo-flask`` and ``tests``) and some files.
Let's start describing them:
@@ -161,7 +207,7 @@ publish that X.509 certificate on Service Provider metadata.
If you want to create self-signed certs, you can do it at the https://www.samltool.com/self_signed_certs.php service, or using the command:
```bash
-openssl req -new -x509 -days 3652 -nodes -out sp.crt -keyout saml.key
+openssl req -new -x509 -days 3652 -nodes -out sp.crt -keyout sp.key
```
#### demo-flask ####
@@ -172,26 +218,36 @@ This folder contains a Flask project that will be used as demo to show how to ad
This folder contains a Pyramid project that will be used as demo to show how to add SAML support to the [Pyramid Web Framework](http://docs.pylonsproject.org/projects/pyramid/en/latest/). ``\_\_init__.py`` is the main file that configures the app and its routes, ``views.py`` is where all the logic and SAML handling takes place, and the templates are stored in the ``templates`` folder. The ``saml`` folder is the same as in the other two demos.
+#### demo-tornado ####
+
+This folder contains a Tornado project that will be used as demo to show how to add SAML support to the Tornado Framework. ``views.py`` (with its ``settings.py``) is the main Flask file that has all the code, this file uses the templates stored at the ``templates`` folder. In the ``saml`` folder we found the ``certs`` folder to store the X.509 public and private key, and the SAML toolkit settings (``settings.json`` and ``advanced_settings.json``).
-#### setup.py ####
+It requires python3.8 (it's using tornado 6.4.1)
-Setup script is the centre of all activity in building, distributing, and installing modules.
-Read more at https://pythonhosted.org/an_example_pypi_project/setuptools.html
#### tests ####
Contains the unit test of the toolkit.
-In order to execute the test you only need to load the virtualenv with the toolkit installed on it and execute:
+In order to execute the test you only need to load the virtualenv with the toolkit installed on it properly:
+```
+make install-test
+```
+
+and execute:
```
-python setup.py test
+make pytest
```
The previous line will run the tests for the whole toolkit. You can also run the tests for a specific module. To do so for the auth module you would have to execute this:
```
-python setup.py test --test-suite tests.src.OneLogin.saml2_tests.auth_test.OneLogin_Saml2_Auth_Test
+pytest tests/src/OneLogin/saml2_tests/auth_test.py::OneLogin_Saml2_Auth_Test
+```
+
+Or for an specific method:
+```
+pytest tests/src/OneLogin/saml2_tests/auth_test.py::OneLogin_Saml2_Auth_Test::testBuildRequestSignature
```
-With the ``--test-suite`` parameter you can specify the module to test. You'll find all the module available and their class names at ``tests/src/OneLogin/saml2_tests/``.
### How It Works ###
@@ -230,24 +286,31 @@ This is the ``settings.json`` file:
// URL Location where the from the IdP will be returned
"url": "https:///?acs",
// SAML protocol binding to be used when returning the
- // message. OneLogin Toolkit supports this endpoint for the
+ // message. SAML Toolkit supports this endpoint for the
// HTTP-POST binding only.
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
},
- // Specifies info about where and how the message MUST be
- // returned to the requester, in this case our SP.
+ // Specifies info about where and how the message MUST be sent.
"singleLogoutService": {
- // URL Location where the from the IdP will be returned
+ // URL Location where the from the IdP will be sent (IdP-initiated logout)
"url": "https:///?sls",
+ // URL Location where the from the IdP will sent (SP-initiated logout, reply)
+ // OPTIONAL: only specify if different from url parameter
+ //"responseUrl": "https:///?sls",
// SAML protocol binding to be used when returning the
- // message. OneLogin Toolkit supports the HTTP-Redirect binding
+ // message. SAML Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
},
// If you need to specify requested attributes, set a
// attributeConsumingService. nameFormat, attributeValue and
- // friendlyName can be ommited
+ // friendlyName can be omitted
"attributeConsumingService": {
+ // OPTIONAL: only specify if SP requires this.
+ // index is an integer which identifies the attributeConsumingService used
+ // to the SP. SAML toolkit supports configuring only one attributeConsumingService
+ // but in certain cases the SP requires a different value. Defaults to '1'.
+ // "index": '1',
"serviceName": "SP test",
"serviceDescription": "Test Service",
"requestedAttributes": [
@@ -289,16 +352,19 @@ This is the ``settings.json`` file:
// will be sent.
"url": "https://app.onelogin.com/trust/saml2/http-post/sso/",
// SAML protocol binding to be used when returning the
- // message. OneLogin Toolkit supports the HTTP-Redirect binding
+ // message. SAML Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
},
// SLO endpoint info of the IdP.
"singleLogoutService": {
- // URL Location of the IdP where SLO Request will be sent.
+ // URL Location where the from the IdP will be sent (IdP-initiated logout)
"url": "https://app.onelogin.com/trust/saml2/http-redirect/slo/",
+ // URL Location where the from the IdP will sent (SP-initiated logout, reply)
+ // OPTIONAL: only specify if different from url parameter
+ "responseUrl": "https://app.onelogin.com/trust/saml2/http-redirect/slo_return/",
// SAML protocol binding to be used when returning the
- // message. OneLogin Toolkit supports the HTTP-Redirect binding
+ // message. SAML Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
},
@@ -307,8 +373,8 @@ This is the ``settings.json`` file:
/*
* Instead of using the whole X.509cert you can use a fingerprint in order to
* validate a SAMLResponse (but you still need the X.509cert to validate LogoutRequest and LogoutResponse using the HTTP-Redirect binding).
- * But take in mind that the fingerprint, is a hash, so at the end is open to a collision attack that can end on a signature validation bypass,
- * that why we don't recommend it use for production environments.
+ * But take in mind that the algorithm for the fingerprint should be as strong as the algorithm in a normal certificate signature
+ * (e.g. SHA256 or strong)
*
* (openssl x509 -noout -fingerprint -in "idp.crt" to generate it,
* or add for example the -sha256 , -sha384 or -sha512 parameter)
@@ -408,7 +474,7 @@ In addition to the required settings data (idp, sp), extra settings can be defin
"requestedAuthnContext": true,
// Allows the authn comparison parameter to be set, defaults to 'exact' if the setting is not present.
"requestedAuthnContextComparison": "exact",
- // Set to true to check that the AuthnContext received matches the one requested.
+ // Set to true to check that the AuthnContext(s) received match(es) the requested.
"failOnAuthnContextMismatch": false,
// In some environment you will need to set how long the published metadata of the Service Provider gonna be valid.
@@ -418,20 +484,33 @@ In addition to the required settings data (idp, sp), extra settings can be defin
// Provide the desire Duration, for example PT518400S (6 days)
"metadataCacheDuration": null,
+ // If enabled, URLs with single-label-domains will
+ // be allowed and not rejected by the settings validator (Enable it under Docker/Kubernetes/testing env, not recommended on production)
+ "allowSingleLabelDomains": false,
+
// Algorithm that the toolkit will use on signing process. Options:
// 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
// 'http://www.w3.org/2000/09/xmldsig#dsa-sha1'
// 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'
// 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384'
// 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'
- "signatureAlgorithm": "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
+ "signatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
// Algorithm that the toolkit will use on digest process. Options:
// 'http://www.w3.org/2000/09/xmldsig#sha1'
// 'http://www.w3.org/2001/04/xmlenc#sha256'
// 'http://www.w3.org/2001/04/xmldsig-more#sha384'
// 'http://www.w3.org/2001/04/xmlenc#sha512'
- 'digestAlgorithm': "http://www.w3.org/2000/09/xmldsig#sha1"
+ 'digestAlgorithm': "http://www.w3.org/2001/04/xmlenc#sha256",
+
+ // Specify if you want the SP to view assertions with duplicated Name or FriendlyName attributes to be valid
+ // Defaults to false if not specified
+ 'allowRepeatAttributeName': false,
+
+ // If the toolkit receive a message signed with a
+ // deprecated algorithm (defined at the constant class)
+ // will raise an error and reject the message
+ "rejectDeprecatedAlgorithm": true
},
// Contact information template, it is recommended to suply a
@@ -448,7 +527,7 @@ In addition to the required settings data (idp, sp), extra settings can be defin
},
// Organization information template, the info in en_US lang is
- // recomended, add more if required.
+ // recommended, add more if required.
"organization": {
"en-US": {
"name": "sp_test",
@@ -500,12 +579,25 @@ The method above requires a little extra work to manually specify attributes abo
There's an easier method -- use a metadata exchange. Metadata is just an XML file that defines the capabilities of both the IdP and the SP application. It also contains the X.509 public key certificates which add to the trusted relationship. The IdP administrator can also configure custom settings for an SP based on the metadata.
-Using ````parse_remote```` IdP metadata can be obtained and added to the settings withouth further ado.
+Using ````parse_remote```` IdP metadata can be obtained and added to the settings without further ado.
+
+Take in mind that the OneLogin_Saml2_IdPMetadataParser class does not validate in any way the URL that is introduced in order to be parsed.
+
+Usually the same administrator that handles the Service Provider also sets the URL to the IdP, which should be a trusted resource.
+
+But there are other scenarios, like a SAAS app where the administrator of the app delegates this functionality to other users. In this case, extra precaution should be taken in order to validate such URL inputs and avoid attacks like SSRF.
+
``
idp_data = OneLogin_Saml2_IdPMetadataParser.parse_remote('https://example.com/auth/saml2/idp/metadata')
``
+You can specify a timeout in seconds for metadata retrieval, without it is not guaranteed that the request will complete
+
+``
+idp_data = OneLogin_Saml2_IdPMetadataParser.parse_remote('https://example.com/auth/saml2/idp/metadata', timeout=5)
+``
+
If the Metadata contains several entities, the relevant ``EntityDescriptor`` can be specified when retrieving the settings from the ``IdpMetadataParser`` by its ``entityId`` value:
``idp_data = OneLogin_Saml2_IdPMetadataParser.parse_remote(https://example.com/metadatas, entity_id='idp_entity_id')``
@@ -536,15 +628,15 @@ This parameter has the following scheme:
req = {
"http_host": "",
"script_name": "",
- "server_port": "",
"get_data": "",
"post_data": "",
# Advanced request options
"https": "",
- "lowercase_urlencoding": "",
"request_uri": "",
- "query_string": ""
+ "query_string": "",
+ "validate_signature_from_qs": False,
+ "lowercase_urlencoding": False
}
```
@@ -556,7 +648,6 @@ def prepare_from_django_request(request):
return {
'http_host': request.META['HTTP_HOST'],
'script_name': request.META['PATH_INFO'],
- 'server_port': request.META['SERVER_PORT'],
'get_data': request.GET.copy(),
'post_data': request.POST.copy()
}
@@ -564,8 +655,7 @@ def prepare_from_django_request(request):
def prepare_from_flask_request(request):
url_data = urlparse(request.url)
return {
- 'http_host': request.host,
- 'server_port': url_data.port,
+ 'http_host': request.netloc,
'script_name': request.path,
'get_data': request.args.copy(),
'post_data': request.form.copy()
@@ -576,12 +666,12 @@ An explanation of some advanced request parameters:
* `https` - Defaults to ``off``. Set this to ``on`` if you receive responses over HTTPS.
-* `lowercase_urlencoding` - Defaults to `false`. ADFS users should set this to `true`.
-
-* `request_uri` - The path where your SAML server recieves requests. Set this if requests are not recieved at the server's root.
+* `request_uri` - The path where your SAML server receives requests. Set this if requests are not received at the server's root.
* `query_string` - Set this with additional query parameters that should be passed to the request endpoint.
+* `validate_signature_from_qs` - If `True`, use `query_string` to validate request and response signatures. Otherwise, use `get_data`. Defaults to `False`. Note that when using `get_data`, query parameters need to be url-encoded for validation. By default we use upper-case url-encoding. Some IdPs, notably Microsoft AD, use lower-case url-encoding, which makes signature validation to fail. To fix this issue, either pass `query_string` and set `validate_signature_from_qs` to `True`, which works for all IdPs, or set `lowercase_urlencoding` to `True`, which only works for AD.
+
#### Initiate SSO ####
@@ -594,12 +684,13 @@ req = prepare_request_for_toolkit(request)
auth = OneLogin_Saml2_Auth(req) # Constructor of the SP, loads settings.json
# and advanced_settings.json
-auth.login() # Method that builds and sends the AuthNRequest
+auth.login() # This method will build and return a AuthNRequest URL that can be
+ # either redirected to, or printed out onto the screen as a hyperlink
```
The ``AuthNRequest`` will be sent signed or unsigned based on the security info of the ``advanced_settings.json`` file (i.e. ``authnRequestsSigned``).
-The IdP will then return the SAML Response to the user's client. The client is then forwarded to the **Attribute Consumer Service (ACS)** of the SP with this information.
+The IdP will then return the SAML Response to the user's client. The client is then forwarded to the **Assertion Consumer Service (ACS)** of the SP with this information.
We can set a ``return_to`` url parameter to the login function and that will be converted as a ``RelayState`` parameter:
@@ -607,7 +698,7 @@ We can set a ``return_to`` url parameter to the login function and that will be
target_url = 'https://example.com'
auth.login(return_to=target_url)
```
-The login method can recieve 3 more optional parameters:
+The login method can receive 3 more optional parameters:
* ``force_authn`` When ``true``, the ``AuthNReuqest`` will set the ``ForceAuthn='true'``
* ``is_passive`` When true, the ``AuthNReuqest`` will set the ``Ispassive='true'``
@@ -648,7 +739,7 @@ saml_settings = OneLogin_Saml2_Settings(settings=None, custom_base_path=None, sp
```
to get the settings object and with the ``sp_validation_only=True`` parameter we will avoid the IdP settings validation.
-***Attribute Consumer Service (ACS)***
+***Assertion Consumer Service (ACS)***
This code handles the SAML response that the IdP forwards to the SP through the user's client.
@@ -662,6 +753,8 @@ if not errors:
request.session['samlUserdata'] = auth.get_attributes()
if 'RelayState' in req['post_data'] and
OneLogin_Saml2_Utils.get_self_url(req) != req['post_data']['RelayState']:
+ # To avoid 'Open Redirect' attacks, before execute the redirection confirm
+ # the value of the req['post_data']['RelayState'] is a trusted URL.
auth.redirect_to(req['post_data']['RelayState'])
else:
for attr_name in request.session['samlUserdata'].keys():
@@ -669,7 +762,7 @@ if not errors:
else:
print('Not authenticated')
else:
- print("Error when processing SAML Response: %s" % (', '.join(errors)))
+ print("Error when processing SAML Response: %s %s" % (', '.join(errors), auth.get_last_error_reason()))
```
The SAML response is processed and then checked that there are no errors. It also verifies that the user is authenticated and stored the userdata in session.
@@ -684,7 +777,7 @@ Notice that we saved the user data in the session before the redirection to have
In order to retrieve attributes we use:
```python
-attributes = auth.get_attributes();
+attributes = auth.get_attributes()
```
With this method we get a dict with all the user data provided by the IdP in the assertion of the SAML response.
@@ -700,12 +793,12 @@ If we execute print attributes we could get:
}
```
-Each attribute name can be used as a key to obtain the value. Every attribute is a list of values. A single-valued attribute is a listy of a single element.
+Each attribute name can be used as a key to obtain the value. Every attribute is a list of values. A single-valued attribute is a list of a single element.
The following code is equivalent:
```python
-attributes = auth.get_attributes();
+attributes = auth.get_attributes()
print(attributes['cn'])
print(auth.get_attribute('cn'))
@@ -724,11 +817,13 @@ url = auth.process_slo(delete_session_cb=delete_session_callback)
errors = auth.get_errors()
if len(errors) == 0:
if url is not None:
+ # To avoid 'Open Redirect' attacks, before execute the redirection confirm
+ # the value of the url is a trusted URL.
return redirect(url)
else:
- print("Sucessfully Logged out")
+ print("Successfully Logged out")
else:
- print("Error when processing SLO: %s" % (', '.join(errors)))
+ print("Error when processing SLO: %s %s" % (', '.join(errors), auth.get_last_error_reason()))
```
If the SLS endpoints receives a Logout Response, the response is validated and the session could be closed, using the callback.
@@ -851,6 +946,8 @@ elif 'acs' in request.args: # Assertion Consumer Service
request.session['samlSessionIndex'] = auth.get_session_index()
self_url = OneLogin_Saml2_Utils.get_self_url(req)
if 'RelayState' in request.form and self_url != request.form['RelayState']:
+ # To avoid 'Open Redirect' attacks, before execute the redirection confirm
+ # the value of the request.form['RelayState'] is a trusted URL.
return redirect(auth.redirect_to(request.form['RelayState'])) # Redirect if there is a relayState
else: # If there is user data we save that to print it later.
msg = ''
@@ -862,9 +959,11 @@ elif 'sls' in request.args: # Single
errors = auth.get_errors() # Retrieves possible validation errors
if len(errors) == 0:
if url is not None:
+ # To avoid 'Open Redirect' attacks, before execute the redirection confirm
+ # the value of the url is a trusted URL.
return redirect(url)
else:
- msg = "Sucessfully logged out"
+ msg = "Successfully logged out"
if len(errors) == 0:
print(msg)
@@ -906,7 +1005,7 @@ Described below are the main classes and methods that can be invoked from the SA
#### OneLogin_Saml2_Auth - auth.py ####
-Main class of OneLogin Python Toolkit
+Main class of SAML Python Toolkit
* `__init__` Initializes the SP SAML instance.
* ***login*** Initiates the SSO process.
@@ -932,9 +1031,11 @@ Main class of OneLogin Python Toolkit
* ***set_strict*** Set the strict mode active/disable.
* ***get_last_request_xml*** Returns the most recently-constructed/processed XML SAML request (``AuthNRequest``, ``LogoutRequest``)
* ***get_last_response_xml*** Returns the most recently-constructed/processed XML SAML response (``SAMLResponse``, ``LogoutResponse``). If the SAMLResponse had an encrypted assertion, decrypts it.
+* ***get_last_response_in_response_to*** The `InResponseTo` ID of the most recently processed SAML Response.
* ***get_last_message_id*** The ID of the last Response SAML message processed.
* ***get_last_assertion_id*** The ID of the last assertion processed.
* ***get_last_assertion_not_on_or_after*** The ``NotOnOrAfter`` value of the valid ``SubjectConfirmationData`` node (if any) of the last assertion processed (is only calculated with strict = true)
+* ***get_last_assertion_issue_instant*** The `IssueInstant` value of the last assertion processed.
#### OneLogin_Saml2_Auth - authn_request.py ####
@@ -978,7 +1079,7 @@ SAML 2 Logout Request class
* ***get_nameid*** Gets the NameID of the Logout Request Message (returns a string).
* ***get_issuer*** Gets the Issuer of the Logout Request Message.
* ***get_session_indexes*** Gets the ``SessionIndexes`` from the Logout Request.
-* ***is_valid*** Checks if the Logout Request recieved is valid.
+* ***is_valid*** Checks if the Logout Request received is valid.
* ***get_error*** After execute a validation process, if fails this method returns the cause.
* ***get_xml*** Returns the XML that will be sent as part of the request or that was received at the SP
@@ -997,7 +1098,7 @@ SAML 2 Logout Response class
#### OneLogin_Saml2_Settings - settings.py ####
-Configuration of the OneLogin Python Toolkit
+Configuration of the SAML Python Toolkit
* `__init__` Initializes the settings: Sets the paths of the different folders and Loads settings info from settings file or array/object provided.
* ***check_settings*** Checks the settings info.
@@ -1061,7 +1162,7 @@ Auxiliary class that contains several methods
* ***get_expire_time*** Compares 2 dates and returns the earliest.
* ***delete_local_session*** Deletes the local session.
* ***calculate_X.509_fingerprint*** Calculates the fingerprint of a X.509 cert.
-* ***format_finger_print*** Formates a fingerprint.
+* ***format_finger_print*** Formats a fingerprint.
* ***generate_name_id*** Generates a nameID.
* ***get_status*** Gets Status from a Response.
* ***decrypt_element*** Decrypts an encrypted element.
@@ -1095,7 +1196,7 @@ For more info, look at the source code. Each method is documented and details ab
Demos included in the toolkit
-----------------------------
-The toolkit includes 2 demos to teach how use the toolkit (A Django and a Flask project), take a look on it.
+The toolkit includes 3 demos to teach how use the toolkit (A Django, Flask and a Tornado project), take a look on it.
Demos require that SP and IdP are well configured before test it, so edit the settings files.
Notice that each python framework has it own way to handle routes/urls and process request, so focus on
@@ -1111,22 +1212,14 @@ let's see how fast is it to deploy them.
The use of a [virtualenv](http://virtualenv.readthedocs.org/en/latest/) is
highly recommended.
-Virtualenv helps isolating the python enviroment used to run the toolkit. You
+Virtualenv helps isolating the python environment used to run the toolkit. You
can find more details and an installation guide in the
[official documentation](http://virtualenv.readthedocs.org/en/latest/).
Once you have your virtualenv ready and loaded, then you can install the
-toolkit on it in development mode executing this:
-```
- python setup.py develop
-```
-
-Using this method of deployment the toolkit files will be linked instead of
-copied, so if you make changes on them you won't need to reinstall the toolkit.
-
-If you want install it in a normal mode, execute:
+toolkit executing this:
```
- python setup.py install
+ make install-req
```
### Demo Flask ###
@@ -1165,7 +1258,7 @@ The flask project contains:
#### SP setup ####
-The Onelogin's Python Toolkit allows you to provide the settings info in 2 ways: Settings files or define a setting dict. In the ``demo-flask``, it uses the first method.
+The SAML Python Toolkit allows you to provide the settings info in 2 ways: Settings files or define a setting dict. In the ``demo-flask``, it uses the first method.
In the ``index.py`` file we define the ``app.config['SAML_PATH']``, that will target to the ``saml`` folder. We require it in order to load the settings files.
@@ -1175,6 +1268,79 @@ First we need to edit the ``saml/settings.json`` file, configure the SP part and
Once the SP is configured, the metadata of the SP is published at the ``/metadata`` url. Based on that info, configure the IdP.
+#### How it works ####
+
+ 1. First time you access to the main view (http://localhost:8000), you can select to login and return to the same view or login and be redirected to ``/?attrs`` (attrs view).
+
+ 2. When you click:
+
+ 2.1 in the first link, we access to ``/?sso`` (index view). An ``AuthNRequest`` is sent to the IdP, we authenticate at the IdP and then a Response is sent through the user's client to the SP, specifically the Assertion Consumer Service view: ``/?acs``. Notice that a ``RelayState`` parameter is set to the url that initiated the process, the index view.
+
+ 2.2 in the second link we access to ``/?attrs`` (attrs view), we will expetience have the same process described at 2.1 with the diference that as ``RelayState`` is set the ``attrs`` url.
+
+ 3. The SAML Response is processed in the ACS ``/?acs``, if the Response is not valid, the process stops here and a message is shown. Otherwise we are redirected to the ``RelayState`` view. a) / or b) ``/?attrs``
+
+ 4. We are logged in the app and the user attributes are showed. At this point, we can test the single log out functionality.
+
+ The single log out functionality could be tested by 2 ways.
+
+ 5.1 SLO Initiated by SP. Click on the ``logout`` link at the SP, after that a Logout Request is sent to the IdP, the session at the IdP is closed and replies through the client to the SP with a Logout Response (sent to the Single Logout Service endpoint). The SLS endpoint ``/?sls`` of the SP process the Logout Response and if is valid, close the user session of the local app. Notice that the SLO Workflow starts and ends at the SP.
+
+ 5.2 SLO Initiated by IdP. In this case, the action takes place on the IdP side, the logout process is initiated at the IdP, sends a Logout Request to the SP (SLS endpoint, ``/?sls``). The SLS endpoint of the SP process the Logout Request and if is valid, close the session of the user at the local app and send a Logout Response to the IdP (to the SLS endpoint of the IdP). The IdP receives the Logout Response, process it and close the session at of the IdP. Notice that the SLO Workflow starts and ends at the IdP.
+
+Notice that all the SAML Requests and Responses are handled at a unique view (index) and how GET parameters are used to know the action that must be done.
+
+### Demo Tornado ###
+
+You'll need a virtualenv with the toolkit installed on it.
+
+First of all you need some packages, execute:
+```
+apt-get install libxml2-dev libxmlsec1-dev libxmlsec1-openssl
+```
+
+To run the demo you need to install the requirements first. Load your
+virtualenv and execute:
+```
+ pip install -r demo-tornado/requirements.txt
+```
+
+
+This will install tornado and its dependencies. Once it has finished, you have to complete the configuration
+of the toolkit. You'll find it at `demo-tornado/saml/settings.json`
+
+Now, with the virtualenv loaded, you can run the demo like this:
+```
+ cd demo-tornado
+ python views.py
+```
+
+You'll have the demo running at http://localhost:8000
+
+#### Content ####
+
+The tornado project contains:
+
+* ***views.py*** Is the main flask file, where or the SAML handle take place.
+
+* ***settings.py*** Contains the base path and the path where is located the ``saml`` folder and the ``template`` folder
+
+* ***templates***. Is the folder where tornado stores the templates of the project. It was implemented a base.html template that is extended by index.html and attrs.html, the templates of our simple demo that shows messages, user attributes when available and login and logout links.
+
+* ***saml*** Is a folder that contains the 'certs' folder that could be used to store the X.509 public and private key, and the saml toolkit settings (settings.json and advanced_settings.json).
+
+#### SP setup ####
+
+The SAML Python Toolkit allows you to provide the settings info in 2 ways: Settings files or define a setting dict. In the ``demo-tornado``, it uses the first method.
+
+In the ``settings.py`` file we define the ``SAML_PATH``, that will target to the ``saml`` folder. We require it in order to load the settings files.
+
+First we need to edit the ``saml/settings.json`` file, configure the SP part and review the metadata of the IdP and complete the IdP info. Later edit the ``saml/advanced_settings.json`` files and configure the how the toolkit will work. Check the settings section of this document if you have any doubt.
+
+#### IdP setup ####
+
+Once the SP is configured, the metadata of the SP is published at the ``/metadata`` url. Based on that info, configure the IdP.
+
#### How it works ####
1. First time you access to the main view (http://localhost:8000), you can select to login and return to the same view or login and be redirected to ``/?attrs`` (attrs view).
@@ -1238,7 +1404,7 @@ The django project contains:
#### SP setup ####
-The Onelogin's Python Toolkit allows you to provide the settings info in 2 ways: settings files or define a setting dict. In the demo-django it used the first method.
+The SAML Python Toolkit allows you to provide the settings info in 2 ways: settings files or define a setting dict. In the demo-django it used the first method.
After set the ``SAML_FOLDER`` in the ``demo/settings.py``, the settings of the Python toolkit will be loaded on the Django web.
@@ -1318,7 +1484,7 @@ The Pyramid project contains:
#### SP setup ####
-The Onelogin's Python Toolkit allows you to provide the settings info in 2 ways: settings files or define a setting dict. In ``demo_pyramid`` the first method is used.
+The SAML Python Toolkit allows you to provide the settings info in 2 ways: settings files or define a setting dict. In ``demo_pyramid`` the first method is used.
In the ``views.py`` file we define the ``SAML_PATH``, which will target the ``saml`` folder. We require it in order to load the settings files.
@@ -1342,7 +1508,7 @@ Once the SP is configured, the metadata of the SP is published at the ``/metadat
4. We are logged in the app and the user attributes are showed. At this point, we can test the single log out functionality.
- The single log out funcionality could be tested by 2 ways.
+ The single log out functionality could be tested by 2 ways.
5.1 SLO Initiated by SP. Click on the "logout" link at the SP, after that a Logout Request is sent to the IdP, the session at the IdP is closed and replies through the client to the SP with a Logout Response (sent to the Single Logout Service endpoint). The SLS endpoint /?sls of the SP process the Logout Response and if is valid, close the user session of the local app. Notice that the SLO Workflow starts and ends at the SP.
diff --git a/changelog.md b/changelog.md
index 9d7e4384..10a066f0 100644
--- a/changelog.md
+++ b/changelog.md
@@ -1,6 +1,74 @@
# python3-saml changelog
-### 1.7.1 (unrelease)
-* Drop python3.4 support
+### 1.16.0 (Oct 9, 2023)
+- [#364](https://github.com/SAML-Toolkits/python3-saml/commit/d1bfaeb17a786735827b8252b91deafde29dabd8) Improve get_metadata method from Parser, allowing to set headers
+- Fix WantAuthnRequestsSigned parser
+- Fix expired payloads used on tests
+- Updated content from docs folder
+
+### 1.15.0 (Dec 27, 2022)
+- [#317](https://github.com/SAML-Toolkits/python3-saml/pull/317) Handle unicode characters gracefully in python 2
+- [#338](https://github.com/SAML-Toolkits/python3-saml/pull/338) Fix WantAuthnRequestsSigned parser
+- [#339](https://github.com/SAML-Toolkits/python3-saml/pull/339) Add Poetry support
+- Remove version restriction on lxml dependency
+- Updated Django demo to 4.X (only py3 compatible)
+- Updated Travis file. Forced lxml to be installed using no-validate_binary
+- Removed references to OneLogin from documentation
+
+### 1.14.0 (Feb 18, 2022)
+- [#297](https://github.com/onelogin/python3-saml/pull/297) Don't require yanked version of lxml.
+- [#298](https://github.com/onelogin/python3-saml/pull/298) Add support for python 3.10 and cleanup the GHA.
+- [#299](https://github.com/onelogin/python3-saml/pull/299) Remove stats from coveralls removed as they are no longer maintained.
+
+### 1.13.0 (Jan 28, 2022)
+- [#296](https://github.com/onelogin/python3-saml/pull/296) Add rejectDeprecatedAlgorithm settings in order to be able reject messages signed with deprecated algorithms.
+- Set sha256 and rsa-sha256 as default algorithms
+- [#288](https://github.com/onelogin/python3-saml/pull/288) Support building a LogoutResponse with non-success status
+- Added warning about Open Redirect and Reply attacks
+- [##274](https://github.com/onelogin/python3-saml/pull/274) Replace double-underscored names with single underscores
+- Add at OneLogin_Saml2_Auth get_last_assertion_issue_instant() and get_last_response_in_response_to() methods
+- Upgrade dependencies
+
+### 1.12.0 (Aug 13, 2021)
+* [#276](https://github.com/onelogin/python3-saml/pull/276) Deprecate server_port from request data dictionary
+
+### 1.11.0 (Jul 23, 2021)
+* [#261](https://github.com/onelogin/python3-saml/pull/261) Allow duplicate named attributes, controlled by a new setting
+* [#268](https://github.com/onelogin/python3-saml/pull/268) Make the redirect scheme matcher case-insensitive
+* [#256](https://github.com/onelogin/python3-saml/pull/256) Improve signature validation process. Add an option to use query string for validation
+* [#259](https://github.com/onelogin/python3-saml/pull/259) Add get metadata timeout
+* [#246](https://github.com/onelogin/python3-saml/pull/246) Add the ability to change the ProtocolBinding in the authn request.
+* [#248](https://github.com/onelogin/python3-saml/pull/248) Move storing the response data into its own method in the Auth class
+* Remove the dependency on defusedxml
+* [#241](https://github.com/onelogin/python3-saml/pull/241) Improve AttributeConsumingService support
+* Update expired dates from test responses
+* Migrate from Travis to Github Actions
+
+### 1.10.1 (Jan 27, 2021)
+* Fix bug on LogoutRequest class, get_idp_slo_response_url was used instead get_idp_slo_url
+
+### 1.10.0 (Jan 14, 2021)
+* Added custom lxml parser based on the one defined at xmldefused. Parser will ignore comments and processing instructions and by default have deactivated huge_tree, DTD and access to external documents
+* Destination URL Comparison is now case-insensitive for netloc
+* Support single-label-domains as valid. New security parameter allowSingleLabelDomains
+* Added get_idp_sso_url, get_idp_slo_url and get_idp_slo_response_url methods to the Settings class and use it in the toolkit
+* [#212](https://github.com/onelogin/python3-saml/pull/212) Overridability enhancements. Made classes overridable by subclassing. Use of classmethods instead staticmethods
+* Add get_friendlyname_attributes support
+* Remove external lib method get_ext_lib_path. Add set_cert_path in order to allow set the cert path in a different folder than the toolkit
+* Add sha256 instead sha1 algorithm for sign/digest as recommended value on documentation and settings
+* [#178](https://github.com/onelogin/python3-saml/pull/178) Support for adding idp.crt from filesystem
+* Add samlUserdata to demo-flask session
+* Fix autoreloading in demo-tornado
+
+### 1.9.0 (Nov 20, 2019)
+* Allow any number of decimal places for seconds on SAML datetimes
+* Fix failOnAuthnContextMismatch code
+* Improve signature validation when no reference uri
+* Update demo versions. Improve them and add Tornado demo.
+
+### 1.8.0 (Sep 11, 2019)
+* Set true as the default value for strict setting
+* [#152](https://github.com/onelogin/python3-saml/pull/152/files) Don't clean xsd and xsi namespaces
+* Drop python3.4 support due lxml. See lxml 4.4.0 (2019-07-27)
### 1.7.0 (Jul 02, 2019)
* Adjusted acs endpoint to extract NameQualifier and SPNameQualifier from SAMLResponse. Adjusted single logout service to provide NameQualifier and SPNameQualifier to logout method. Add getNameIdNameQualifier to Auth and SamlResponse. Extend logout method from Auth and LogoutRequest constructor to support SPNameQualifier parameter. Align LogoutRequest constructor with SAML specs
@@ -39,7 +107,7 @@
### 1.3.0 (Sep 15, 2017)
* Improve decrypt method, Add an option to decrypt an element in place or copy it before decryption.
* [#63](https://github.com/onelogin/python3-saml/pull/63) Be able to get at the auth object the last processed ID (response/assertion) and the last generated ID, as well as the NotOnOrAfter value of the valid SubjectConfirmationData in the processed SAMLResponse
-* On a LogoutRequest if the NameIdFormat is entity, NameQualifier and SPNameQualifier will be ommited. If the NameIdFormat is not entity and a NameQualifier is provided, then the SPNameQualifier will be also added.
+* On a LogoutRequest if the NameIdFormat is entity, NameQualifier and SPNameQualifier will be omitted. If the NameIdFormat is not entity and a NameQualifier is provided, then the SPNameQualifier will be also added.
* Reset errorReason attribute of the auth object before each Process method
* [#65](https://github.com/onelogin/python3-saml/pull/65) Fix issue on getting multiple certs when only sign or encryption certs
diff --git a/demo-django/demo/urls.py b/demo-django/demo/urls.py
index cb05b321..92bc0a2b 100644
--- a/demo-django/demo/urls.py
+++ b/demo-django/demo/urls.py
@@ -1,10 +1,11 @@
-from django.conf.urls import url
+from django.urls import re_path
from django.contrib import admin
from .views import attrs, index, metadata
+
admin.autodiscover()
urlpatterns = [
- url(r'^$', index, name='index'),
- url(r'^attrs/$', attrs, name='attrs'),
- url(r'^metadata/$', metadata, name='metadata'),
+ re_path(r"^$", index, name="index"),
+ re_path(r"^attrs/$", attrs, name="attrs"),
+ re_path(r"^metadata/$", metadata, name="metadata"),
]
diff --git a/demo-django/demo/views.py b/demo-django/demo/views.py
index 4c61e599..82ae55eb 100644
--- a/demo-django/demo/views.py
+++ b/demo-django/demo/views.py
@@ -1,7 +1,6 @@
from django.conf import settings
from django.urls import reverse
-from django.http import (HttpResponse, HttpResponseRedirect,
- HttpResponseServerError)
+from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render
from onelogin.saml2.auth import OneLogin_Saml2_Auth
@@ -17,14 +16,13 @@ def init_saml_auth(req):
def prepare_django_request(request):
# If server is behind proxys or balancers use the HTTP_X_FORWARDED fields
result = {
- 'https': 'on' if request.is_secure() else 'off',
- 'http_host': request.META['HTTP_HOST'],
- 'script_name': request.META['PATH_INFO'],
- 'server_port': request.META['SERVER_PORT'],
- 'get_data': request.GET.copy(),
+ "https": "on" if request.is_secure() else "off",
+ "http_host": request.META["HTTP_HOST"],
+ "script_name": request.META["PATH_INFO"],
+ "get_data": request.GET.copy(),
# Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144
# 'lowercase_urlencoding': True,
- 'post_data': request.POST.copy()
+ "post_data": request.POST.copy(),
}
return result
@@ -39,89 +37,93 @@ def index(request):
attributes = False
paint_logout = False
- if 'sso' in req['get_data']:
+ if "sso" in req["get_data"]:
return HttpResponseRedirect(auth.login())
# If AuthNRequest ID need to be stored in order to later validate it, do instead
# sso_built_url = auth.login()
# request.session['AuthNRequestID'] = auth.get_last_request_id()
# return HttpResponseRedirect(sso_built_url)
- elif 'sso2' in req['get_data']:
- return_to = OneLogin_Saml2_Utils.get_self_url(req) + reverse('attrs')
+ elif "sso2" in req["get_data"]:
+ return_to = OneLogin_Saml2_Utils.get_self_url(req) + reverse("attrs")
return HttpResponseRedirect(auth.login(return_to))
- elif 'slo' in req['get_data']:
+ elif "slo" in req["get_data"]:
name_id = session_index = name_id_format = name_id_nq = name_id_spnq = None
- if 'samlNameId' in request.session:
- name_id = request.session['samlNameId']
- if 'samlSessionIndex' in request.session:
- session_index = request.session['samlSessionIndex']
- if 'samlNameIdFormat' in request.session:
- name_id_format = request.session['samlNameIdFormat']
- if 'samlNameIdNameQualifier' in request.session:
- name_id_nq = request.session['samlNameIdNameQualifier']
- if 'samlNameIdSPNameQualifier' in request.session:
- name_id_spnq = request.session['samlNameIdSPNameQualifier']
+ if "samlNameId" in request.session:
+ name_id = request.session["samlNameId"]
+ if "samlSessionIndex" in request.session:
+ session_index = request.session["samlSessionIndex"]
+ if "samlNameIdFormat" in request.session:
+ name_id_format = request.session["samlNameIdFormat"]
+ if "samlNameIdNameQualifier" in request.session:
+ name_id_nq = request.session["samlNameIdNameQualifier"]
+ if "samlNameIdSPNameQualifier" in request.session:
+ name_id_spnq = request.session["samlNameIdSPNameQualifier"]
return HttpResponseRedirect(auth.logout(name_id=name_id, session_index=session_index, nq=name_id_nq, name_id_format=name_id_format, spnq=name_id_spnq))
# If LogoutRequest ID need to be stored in order to later validate it, do instead
# slo_built_url = auth.logout(name_id=name_id, session_index=session_index)
# request.session['LogoutRequestID'] = auth.get_last_request_id()
# return HttpResponseRedirect(slo_built_url)
- elif 'acs' in req['get_data']:
+ elif "acs" in req["get_data"]:
request_id = None
- if 'AuthNRequestID' in request.session:
- request_id = request.session['AuthNRequestID']
+ if "AuthNRequestID" in request.session:
+ request_id = request.session["AuthNRequestID"]
auth.process_response(request_id=request_id)
errors = auth.get_errors()
not_auth_warn = not auth.is_authenticated()
if not errors:
- if 'AuthNRequestID' in request.session:
- del request.session['AuthNRequestID']
- request.session['samlUserdata'] = auth.get_attributes()
- request.session['samlNameId'] = auth.get_nameid()
- request.session['samlNameIdFormat'] = auth.get_nameid_format()
- request.session['samlNameIdNameQualifier'] = auth.get_nameid_nq()
- request.session['samlNameIdSPNameQualifier'] = auth.get_nameid_spnq()
- request.session['samlSessionIndex'] = auth.get_session_index()
- if 'RelayState' in req['post_data'] and OneLogin_Saml2_Utils.get_self_url(req) != req['post_data']['RelayState']:
- return HttpResponseRedirect(auth.redirect_to(req['post_data']['RelayState']))
- else:
- if auth.get_settings().is_debug_active():
- error_reason = auth.get_last_error_reason()
- elif 'sls' in req['get_data']:
+ if "AuthNRequestID" in request.session:
+ del request.session["AuthNRequestID"]
+ request.session["samlUserdata"] = auth.get_attributes()
+ request.session["samlNameId"] = auth.get_nameid()
+ request.session["samlNameIdFormat"] = auth.get_nameid_format()
+ request.session["samlNameIdNameQualifier"] = auth.get_nameid_nq()
+ request.session["samlNameIdSPNameQualifier"] = auth.get_nameid_spnq()
+ request.session["samlSessionIndex"] = auth.get_session_index()
+ if "RelayState" in req["post_data"] and OneLogin_Saml2_Utils.get_self_url(req) != req["post_data"]["RelayState"]:
+ # To avoid 'Open Redirect' attacks, before execute the redirection confirm
+ # the value of the req['post_data']['RelayState'] is a trusted URL.
+ return HttpResponseRedirect(auth.redirect_to(req["post_data"]["RelayState"]))
+ elif auth.get_settings().is_debug_active():
+ error_reason = auth.get_last_error_reason()
+ elif "sls" in req["get_data"]:
request_id = None
- if 'LogoutRequestID' in request.session:
- request_id = request.session['LogoutRequestID']
+ if "LogoutRequestID" in request.session:
+ request_id = request.session["LogoutRequestID"]
dscb = lambda: request.session.flush()
url = auth.process_slo(request_id=request_id, delete_session_cb=dscb)
errors = auth.get_errors()
if len(errors) == 0:
if url is not None:
+ # To avoid 'Open Redirect' attacks, before execute the redirection confirm
+ # the value of the url is a trusted URL
return HttpResponseRedirect(url)
else:
success_slo = True
+ elif auth.get_settings().is_debug_active():
+ error_reason = auth.get_last_error_reason()
- if 'samlUserdata' in request.session:
+ if "samlUserdata" in request.session:
paint_logout = True
- if len(request.session['samlUserdata']) > 0:
- attributes = request.session['samlUserdata'].items()
+ if len(request.session["samlUserdata"]) > 0:
+ attributes = request.session["samlUserdata"].items()
- return render(request, 'index.html', {'errors': errors, 'error_reason': error_reason, 'not_auth_warn': not_auth_warn, 'success_slo': success_slo,
- 'attributes': attributes, 'paint_logout': paint_logout})
+ return render(
+ request, "index.html", {"errors": errors, "error_reason": error_reason, "not_auth_warn": not_auth_warn, "success_slo": success_slo, "attributes": attributes, "paint_logout": paint_logout}
+ )
def attrs(request):
paint_logout = False
attributes = False
- if 'samlUserdata' in request.session:
+ if "samlUserdata" in request.session:
paint_logout = True
- if len(request.session['samlUserdata']) > 0:
- attributes = request.session['samlUserdata'].items()
- return render(request, 'attrs.html',
- {'paint_logout': paint_logout,
- 'attributes': attributes})
+ if len(request.session["samlUserdata"]) > 0:
+ attributes = request.session["samlUserdata"].items()
+ return render(request, "attrs.html", {"paint_logout": paint_logout, "attributes": attributes})
def metadata(request):
@@ -133,7 +135,7 @@ def metadata(request):
errors = saml_settings.validate_metadata(metadata)
if len(errors) == 0:
- resp = HttpResponse(content=metadata, content_type='text/xml')
+ resp = HttpResponse(content=metadata, content_type="text/xml")
else:
- resp = HttpResponseServerError(content=', '.join(errors))
+ resp = HttpResponseServerError(content=", ".join(errors))
return resp
diff --git a/demo-django/demo/wsgi.py b/demo-django/demo/wsgi.py
index b1c7db13..49617a60 100644
--- a/demo-django/demo/wsgi.py
+++ b/demo-django/demo/wsgi.py
@@ -8,7 +8,9 @@
"""
import os
+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")
from django.core.wsgi import get_wsgi_application # noqa: E402
+
application = get_wsgi_application()
diff --git a/demo-django/requirements.txt b/demo-django/requirements.txt
index 1aa1df39..c4d84d80 100644
--- a/demo-django/requirements.txt
+++ b/demo-django/requirements.txt
@@ -1,2 +1,2 @@
-Django==1.11
+Django==4.1.13
python3-saml
diff --git a/demo-django/saml/advanced_settings.json b/demo-django/saml/advanced_settings.json
index 3115e17e..3960911a 100644
--- a/demo-django/saml/advanced_settings.json
+++ b/demo-django/saml/advanced_settings.json
@@ -10,8 +10,10 @@
"wantNameId" : true,
"wantNameIdEncrypted": false,
"wantAssertionsEncrypted": false,
- "signatureAlgorithm": "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
- "digestAlgorithm": "http://www.w3.org/2000/09/xmldsig#sha1"
+ "allowSingleLabelDomains": false,
+ "signatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
+ "digestAlgorithm": "http://www.w3.org/2001/04/xmlenc#sha256",
+ "rejectDeprecatedAlgorithm": true
},
"contactPerson": {
"technical": {
diff --git a/demo-django/saml/certs/README b/demo-django/saml/certs/README
index 7e837fb9..ed973e05 100644
--- a/demo-django/saml/certs/README
+++ b/demo-django/saml/certs/README
@@ -1,6 +1,6 @@
Take care of this folder that could contain private key. Be sure that this folder never is published.
-Onelogin Python Toolkit expects that certs for the SP could be stored in this folder as:
+SAML Python Toolkit expects that certs for the SP could be stored in this folder as:
* sp.key Private Key
* sp.crt Public cert
diff --git a/demo-django/templates/base.html b/demo-django/templates/base.html
index a55dbf0b..960ca0bc 100644
--- a/demo-django/templates/base.html
+++ b/demo-django/templates/base.html
@@ -5,7 +5,7 @@
- A Python SAML Toolkit by OneLogin demo
+ A Python SAML Toolkit demo
@@ -18,7 +18,7 @@
-
A Python SAML Toolkit by OneLogin demo
+
A Python SAML Toolkit demo
{% block content %}{% endblock %}
diff --git a/demo-flask/index.py b/demo-flask/index.py
index b344da4c..a03eeccd 100644
--- a/demo-flask/index.py
+++ b/demo-flask/index.py
@@ -1,134 +1,131 @@
import os
-from flask import (Flask, request, render_template, redirect, session,
- make_response)
-
-from urllib.parse import urlparse
+from flask import Flask, request, render_template, redirect, session, make_response
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from onelogin.saml2.utils import OneLogin_Saml2_Utils
app = Flask(__name__)
-app.config['SECRET_KEY'] = 'onelogindemopytoolkit'
-app.config['SAML_PATH'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'saml')
+app.config["SECRET_KEY"] = "onelogindemopytoolkit"
+app.config["SAML_PATH"] = os.path.join(os.path.dirname(os.path.abspath(__file__)), "saml")
def init_saml_auth(req):
- auth = OneLogin_Saml2_Auth(req, custom_base_path=app.config['SAML_PATH'])
+ auth = OneLogin_Saml2_Auth(req, custom_base_path=app.config["SAML_PATH"])
return auth
def prepare_flask_request(request):
# If server is behind proxys or balancers use the HTTP_X_FORWARDED fields
- url_data = urlparse(request.url)
return {
- 'https': 'on' if request.scheme == 'https' else 'off',
- 'http_host': request.host,
- 'server_port': url_data.port,
- 'script_name': request.path,
- 'get_data': request.args.copy(),
+ "https": "on" if request.scheme == "https" else "off",
+ "http_host": request.host,
+ "script_name": request.path,
+ "get_data": request.args.copy(),
# Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144
# 'lowercase_urlencoding': True,
- 'post_data': request.form.copy()
+ "post_data": request.form.copy(),
}
-@app.route('/', methods=['GET', 'POST'])
+@app.route("/", methods=["GET", "POST"])
def index():
req = prepare_flask_request(request)
auth = init_saml_auth(req)
errors = []
+ error_reason = None
not_auth_warn = False
success_slo = False
attributes = False
paint_logout = False
- if 'sso' in request.args:
+ if "sso" in request.args:
return redirect(auth.login())
# If AuthNRequest ID need to be stored in order to later validate it, do instead
# sso_built_url = auth.login()
# request.session['AuthNRequestID'] = auth.get_last_request_id()
# return redirect(sso_built_url)
- elif 'sso2' in request.args:
- return_to = '%sattrs/' % request.host_url
+ elif "sso2" in request.args:
+ return_to = "%sattrs/" % request.host_url
return redirect(auth.login(return_to))
- elif 'slo' in request.args:
+ elif "slo" in request.args:
name_id = session_index = name_id_format = name_id_nq = name_id_spnq = None
- if 'samlNameId' in session:
- name_id = session['samlNameId']
- if 'samlSessionIndex' in session:
- session_index = session['samlSessionIndex']
- if 'samlNameIdFormat' in session:
- name_id_format = session['samlNameIdFormat']
- if 'samlNameIdNameQualifier' in session:
- name_id_nq = session['samlNameIdNameQualifier']
- if 'samlNameIdSPNameQualifier' in session:
- name_id_spnq = session['samlNameIdSPNameQualifier']
+ if "samlNameId" in session:
+ name_id = session["samlNameId"]
+ if "samlSessionIndex" in session:
+ session_index = session["samlSessionIndex"]
+ if "samlNameIdFormat" in session:
+ name_id_format = session["samlNameIdFormat"]
+ if "samlNameIdNameQualifier" in session:
+ name_id_nq = session["samlNameIdNameQualifier"]
+ if "samlNameIdSPNameQualifier" in session:
+ name_id_spnq = session["samlNameIdSPNameQualifier"]
return redirect(auth.logout(name_id=name_id, session_index=session_index, nq=name_id_nq, name_id_format=name_id_format, spnq=name_id_spnq))
- elif 'acs' in request.args:
+ elif "acs" in request.args:
request_id = None
- if 'AuthNRequestID' in session:
- request_id = session['AuthNRequestID']
+ if "AuthNRequestID" in session:
+ request_id = session["AuthNRequestID"]
auth.process_response(request_id=request_id)
errors = auth.get_errors()
not_auth_warn = not auth.is_authenticated()
if len(errors) == 0:
- if 'AuthNRequestID' in session:
- del session['AuthNRequestID']
- session['samlNameId'] = auth.get_nameid()
- session['samlNameIdFormat'] = auth.get_nameid_format()
- session['samlNameIdNameQualifier'] = auth.get_nameid_nq()
- session['samlNameIdSPNameQualifier'] = auth.get_nameid_spnq()
- session['samlSessionIndex'] = auth.get_session_index()
+ if "AuthNRequestID" in session:
+ del session["AuthNRequestID"]
+ session["samlUserdata"] = auth.get_attributes()
+ session["samlNameId"] = auth.get_nameid()
+ session["samlNameIdFormat"] = auth.get_nameid_format()
+ session["samlNameIdNameQualifier"] = auth.get_nameid_nq()
+ session["samlNameIdSPNameQualifier"] = auth.get_nameid_spnq()
+ session["samlSessionIndex"] = auth.get_session_index()
self_url = OneLogin_Saml2_Utils.get_self_url(req)
- if 'RelayState' in request.form and self_url != request.form['RelayState']:
- return redirect(auth.redirect_to(request.form['RelayState']))
- elif 'sls' in request.args:
+ if "RelayState" in request.form and self_url != request.form["RelayState"]:
+ # To avoid 'Open Redirect' attacks, before execute the redirection confirm
+ # the value of the request.form['RelayState'] is a trusted URL.
+ return redirect(auth.redirect_to(request.form["RelayState"]))
+ elif auth.get_settings().is_debug_active():
+ error_reason = auth.get_last_error_reason()
+ elif "sls" in request.args:
request_id = None
- if 'LogoutRequestID' in session:
- request_id = session['LogoutRequestID']
+ if "LogoutRequestID" in session:
+ request_id = session["LogoutRequestID"]
dscb = lambda: session.clear()
url = auth.process_slo(request_id=request_id, delete_session_cb=dscb)
errors = auth.get_errors()
if len(errors) == 0:
if url is not None:
+ # To avoid 'Open Redirect' attacks, before execute the redirection confirm
+ # the value of the url is a trusted URL.
return redirect(url)
else:
success_slo = True
+ elif auth.get_settings().is_debug_active():
+ error_reason = auth.get_last_error_reason()
- if 'samlUserdata' in session:
+ if "samlUserdata" in session:
paint_logout = True
- if len(session['samlUserdata']) > 0:
- attributes = session['samlUserdata'].items()
+ if len(session["samlUserdata"]) > 0:
+ attributes = session["samlUserdata"].items()
- return render_template(
- 'index.html',
- errors=errors,
- not_auth_warn=not_auth_warn,
- success_slo=success_slo,
- attributes=attributes,
- paint_logout=paint_logout
- )
+ return render_template("index.html", errors=errors, error_reason=error_reason, not_auth_warn=not_auth_warn, success_slo=success_slo, attributes=attributes, paint_logout=paint_logout)
-@app.route('/attrs/')
+@app.route("/attrs/")
def attrs():
paint_logout = False
attributes = False
- if 'samlUserdata' in session:
+ if "samlUserdata" in session:
paint_logout = True
- if len(session['samlUserdata']) > 0:
- attributes = session['samlUserdata'].items()
+ if len(session["samlUserdata"]) > 0:
+ attributes = session["samlUserdata"].items()
- return render_template('attrs.html', paint_logout=paint_logout,
- attributes=attributes)
+ return render_template("attrs.html", paint_logout=paint_logout, attributes=attributes)
-@app.route('/metadata/')
+@app.route("/metadata/")
def metadata():
req = prepare_flask_request(request)
auth = init_saml_auth(req)
@@ -138,11 +135,11 @@ def metadata():
if len(errors) == 0:
resp = make_response(metadata, 200)
- resp.headers['Content-Type'] = 'text/xml'
+ resp.headers["Content-Type"] = "text/xml"
else:
- resp = make_response(', '.join(errors), 500)
+ resp = make_response(", ".join(errors), 500)
return resp
if __name__ == "__main__":
- app.run(host='0.0.0.0', port=8000, debug=True)
+ app.run(host="0.0.0.0", port=8000, debug=True)
diff --git a/demo-flask/requirements.txt b/demo-flask/requirements.txt
index 335836f7..d9340937 100644
--- a/demo-flask/requirements.txt
+++ b/demo-flask/requirements.txt
@@ -1 +1 @@
-flask==0.10.1
+flask==1.0
diff --git a/demo-flask/saml/advanced_settings.json b/demo-flask/saml/advanced_settings.json
index 3115e17e..3960911a 100644
--- a/demo-flask/saml/advanced_settings.json
+++ b/demo-flask/saml/advanced_settings.json
@@ -10,8 +10,10 @@
"wantNameId" : true,
"wantNameIdEncrypted": false,
"wantAssertionsEncrypted": false,
- "signatureAlgorithm": "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
- "digestAlgorithm": "http://www.w3.org/2000/09/xmldsig#sha1"
+ "allowSingleLabelDomains": false,
+ "signatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
+ "digestAlgorithm": "http://www.w3.org/2001/04/xmlenc#sha256",
+ "rejectDeprecatedAlgorithm": true
},
"contactPerson": {
"technical": {
diff --git a/demo-flask/saml/certs/README b/demo-flask/saml/certs/README
index 7e837fb9..ed973e05 100644
--- a/demo-flask/saml/certs/README
+++ b/demo-flask/saml/certs/README
@@ -1,6 +1,6 @@
Take care of this folder that could contain private key. Be sure that this folder never is published.
-Onelogin Python Toolkit expects that certs for the SP could be stored in this folder as:
+SAML Python Toolkit expects that certs for the SP could be stored in this folder as:
* sp.key Private Key
* sp.crt Public cert
diff --git a/demo-flask/templates/base.html b/demo-flask/templates/base.html
index a55dbf0b..960ca0bc 100644
--- a/demo-flask/templates/base.html
+++ b/demo-flask/templates/base.html
@@ -5,7 +5,7 @@
- A Python SAML Toolkit by OneLogin demo
+ A Python SAML Toolkit demo
@@ -18,7 +18,7 @@
[docs]defprocess_response(self,request_id=None):
+"""
+ Process the SAML Response sent by the IdP.
+
+ :param request_id: Is an optional argument. Is the ID of the AuthNRequest sent by this SP to the IdP.
+ :type request_id: string
+
+ :raises: OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND, when a POST with a SAMLResponse is not found
+ """
+ self._errors=[]
+ self._error_reason=None
+
+ if'post_data'inself._request_dataand'SAMLResponse'inself._request_data['post_data']:
+ # AuthnResponse -- HTTP_POST Binding
+ response=self.response_class(self._settings,self._request_data['post_data']['SAMLResponse'])
+ self._last_response=response.get_xml_document()
+
+ ifresponse.is_valid(self._request_data,request_id):
+ self.store_valid_response(response)
+ else:
+ self._errors.append('invalid_response')
+ self._error_reason=response.get_error()
+
+ else:
+ self._errors.append('invalid_binding')
+ raiseOneLogin_Saml2_Error(
+ 'SAML Response not found, Only supported HTTP_POST Binding',
+ OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND
+ )
+
+
[docs]defprocess_slo(self,keep_local_session=False,request_id=None,delete_session_cb=None):
+"""
+ Process the SAML Logout Response / Logout Request sent by the IdP.
+
+ :param keep_local_session: When false will destroy the local session, otherwise will destroy it
+ :type keep_local_session: bool
+
+ :param request_id: The ID of the LogoutRequest sent by this SP to the IdP
+ :type request_id: string
+
+ :returns: Redirection url
+ """
+ self._errors=[]
+ self._error_reason=None
+
+ get_data='get_data'inself._request_dataandself._request_data['get_data']
+ ifget_dataand'SAMLResponse'inget_data:
+ logout_response=self.logout_response_class(self._settings,get_data['SAMLResponse'])
+ self._last_response=logout_response.get_xml()
+ ifnotself.validate_response_signature(get_data):
+ self._errors.append('invalid_logout_response_signature')
+ self._errors.append('Signature validation failed. Logout Response rejected')
+ elifnotlogout_response.is_valid(self._request_data,request_id):
+ self._errors.append('invalid_logout_response')
+ eliflogout_response.get_status()!=OneLogin_Saml2_Constants.STATUS_SUCCESS:
+ self._errors.append('logout_not_success')
+ else:
+ self._last_message_id=logout_response.id
+ ifnotkeep_local_session:
+ OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
+
+ elifget_dataand'SAMLRequest'inget_data:
+ logout_request=self.logout_request_class(self._settings,get_data['SAMLRequest'])
+ self._last_request=logout_request.get_xml()
+ ifnotself.validate_request_signature(get_data):
+ self._errors.append("invalid_logout_request_signature")
+ self._errors.append('Signature validation failed. Logout Request rejected')
+ elifnotlogout_request.is_valid(self._request_data):
+ self._errors.append('invalid_logout_request')
+ else:
+ ifnotkeep_local_session:
+ OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
+
+ in_response_to=logout_request.id
+ self._last_message_id=logout_request.id
+ response_builder=self.logout_response_class(self._settings)
+ response_builder.build(in_response_to)
+ self._last_response=response_builder.get_xml()
+ logout_response=response_builder.get_response()
+
+ parameters={'SAMLResponse':logout_response}
+ if'RelayState'inself._request_data['get_data']:
+ parameters['RelayState']=self._request_data['get_data']['RelayState']
+
+ security=self._settings.get_security_data()
+ ifsecurity['logoutResponseSigned']:
+ self.add_response_signature(parameters,security['signatureAlgorithm'])
+
+ returnself.redirect_to(self.get_slo_response_url(),parameters)
+ else:
+ self._errors.append('invalid_binding')
+ raiseOneLogin_Saml2_Error(
+ 'SAML LogoutRequest/LogoutResponse not found. Only supported HTTP_REDIRECT Binding',
+ OneLogin_Saml2_Error.SAML_LOGOUTMESSAGE_NOT_FOUND
+ )
+
+
[docs]defredirect_to(self,url=None,parameters={}):
+"""
+ Redirects the user to the URL passed by parameter or to the URL that we defined in our SSO Request.
+
+ :param url: The target URL to redirect the user
+ :type url: string
+ :param parameters: Extra parameters to be passed as part of the URL
+ :type parameters: dict
+
+ :returns: Redirection URL
+ """
+ ifurlisNoneand'RelayState'inself._request_data['get_data']:
+ url=self._request_data['get_data']['RelayState']
+ returnOneLogin_Saml2_Utils.redirect(url,parameters,request_data=self._request_data)
+
+
[docs]defis_authenticated(self):
+"""
+ Checks if the user is authenticated or not.
+
+ :returns: True if is authenticated, False if not
+ :rtype: bool
+ """
+ returnself._authenticated
+
+
[docs]defget_attributes(self):
+"""
+ Returns the set of SAML attributes.
+
+ :returns: SAML attributes
+ :rtype: dict
+ """
+ returnself._attributes
+
+
[docs]defget_friendlyname_attributes(self):
+"""
+ Returns the set of SAML attributes indexed by FiendlyName.
+
+ :returns: SAML attributes
+ :rtype: dict
+ """
+ returnself._friendlyname_attributes
[docs]defget_nameid_format(self):
+"""
+ Returns the nameID Format.
+
+ :returns: NameID Format
+ :rtype: string|None
+ """
+ returnself._nameid_format
+
+
[docs]defget_nameid_nq(self):
+"""
+ Returns the nameID NameQualifier of the Assertion.
+
+ :returns: NameID NameQualifier
+ :rtype: string|None
+ """
+ returnself._nameid_nq
+
+
[docs]defget_nameid_spnq(self):
+"""
+ Returns the nameID SP NameQualifier of the Assertion.
+
+ :returns: NameID SP NameQualifier
+ :rtype: string|None
+ """
+ returnself._nameid_spnq
+
+
[docs]defget_session_index(self):
+"""
+ Returns the SessionIndex from the AuthnStatement.
+ :returns: The SessionIndex of the assertion
+ :rtype: string
+ """
+ returnself._session_index
+
+
[docs]defget_session_expiration(self):
+"""
+ Returns the SessionNotOnOrAfter from the AuthnStatement.
+ :returns: The SessionNotOnOrAfter of the assertion
+ :rtype: unix/posix timestamp|None
+ """
+ returnself._session_expiration
+
+
[docs]defget_last_assertion_not_on_or_after(self):
+"""
+ The NotOnOrAfter value of the valid SubjectConfirmationData node
+ (if any) of the last assertion processed
+ """
+ returnself._last_assertion_not_on_or_after
+
+
[docs]defget_errors(self):
+"""
+ Returns a list with code errors if something went wrong
+
+ :returns: List of errors
+ :rtype: list
+ """
+ returnself._errors
+
+
[docs]defget_last_error_reason(self):
+"""
+ Returns the reason for the last error
+
+ :returns: Reason of the last error
+ :rtype: None | string
+ """
+ returnself._error_reason
+
+
[docs]defget_attribute(self,name):
+"""
+ Returns the requested SAML attribute.
+
+ :param name: Name of the attribute
+ :type name: string
+
+ :returns: Attribute value(s) if exists or None
+ :rtype: list
+ """
+ assertisinstance(name,compat.str_type)
+ returnself._attributes.get(name)
+
+
[docs]defget_friendlyname_attribute(self,friendlyname):
+"""
+ Returns the requested SAML attribute searched by FriendlyName.
+
+ :param friendlyname: FriendlyName of the attribute
+ :type friendlyname: string
+
+ :returns: Attribute value(s) if exists or None
+ :rtype: list
+ """
+ assertisinstance(friendlyname,compat.str_type)
+ returnself._friendlyname_attributes.get(friendlyname)
+
+
[docs]defget_last_request_id(self):
+"""
+ :returns: The ID of the last Request SAML message generated.
+ :rtype: string
+ """
+ returnself._last_request_id
+
+
[docs]defget_last_message_id(self):
+"""
+ :returns: The ID of the last Response SAML message processed.
+ :rtype: string
+ """
+ returnself._last_message_id
+
+
[docs]defget_last_assertion_id(self):
+"""
+ :returns: The ID of the last assertion processed.
+ :rtype: string
+ """
+ returnself._last_assertion_id
+
+
[docs]defget_last_assertion_issue_instant(self):
+"""
+ :returns: The IssueInstant of the last assertion processed.
+ :rtype: unix/posix timestamp|None
+ """
+ returnself._last_assertion_issue_instant
+
+
[docs]defget_last_authn_contexts(self):
+"""
+ :returns: The list of authentication contexts sent in the last SAML Response.
+ :rtype: list
+ """
+ returnself._last_authn_contexts
+
+
[docs]defget_last_response_in_response_to(self):
+"""
+ :returns: InResponseTo attribute of the last Response SAML processed or None if it is not present.
+ :rtype: string
+ """
+ returnself._last_response_in_response_to
+
+
[docs]deflogin(self,return_to=None,force_authn=False,is_passive=False,set_nameid_policy=True,name_id_value_req=None):
+"""
+ Initiates the SSO process.
+
+ :param return_to: Optional argument. The target URL the user should be redirected to after login.
+ :type return_to: string
+
+ :param force_authn: Optional argument. When true the AuthNRequest will set the ForceAuthn='true'.
+ :type force_authn: bool
+
+ :param is_passive: Optional argument. When true the AuthNRequest will set the Ispassive='true'.
+ :type is_passive: bool
+
+ :param set_nameid_policy: Optional argument. When true the AuthNRequest will set a nameIdPolicy element.
+ :type set_nameid_policy: bool
+
+ :param name_id_value_req: Optional argument. Indicates to the IdP the subject that should be authenticated
+ :type name_id_value_req: string
+
+ :returns: Redirection URL
+ :rtype: string
+ """
+ authn_request=self.authn_request_class(self._settings,force_authn,is_passive,set_nameid_policy,name_id_value_req)
+ self._last_request=authn_request.get_xml()
+ self._last_request_id=authn_request.get_id()
+
+ saml_request=authn_request.get_request()
+ parameters={'SAMLRequest':saml_request}
+
+ ifreturn_toisnotNone:
+ parameters['RelayState']=return_to
+ else:
+ parameters['RelayState']=OneLogin_Saml2_Utils.get_self_url_no_query(self._request_data)
+
+ security=self._settings.get_security_data()
+ ifsecurity.get('authnRequestsSigned',False):
+ self.add_request_signature(parameters,security['signatureAlgorithm'])
+ returnself.redirect_to(self.get_sso_url(),parameters)
+
+
[docs]deflogout(self,return_to=None,name_id=None,session_index=None,nq=None,name_id_format=None,spnq=None):
+"""
+ Initiates the SLO process.
+
+ :param return_to: Optional argument. The target URL the user should be redirected to after logout.
+ :type return_to: string
+
+ :param name_id: The NameID that will be set in the LogoutRequest.
+ :type name_id: string
+
+ :param session_index: SessionIndex that identifies the session of the user.
+ :type session_index: string
+
+ :param nq: IDP Name Qualifier
+ :type: string
+
+ :param name_id_format: The NameID Format that will be set in the LogoutRequest.
+ :type: string
+
+ :param spnq: SP Name Qualifier
+ :type: string
+
+ :returns: Redirection URL
+ """
+ slo_url=self.get_slo_url()
+ ifslo_urlisNone:
+ raiseOneLogin_Saml2_Error(
+ 'The IdP does not support Single Log Out',
+ OneLogin_Saml2_Error.SAML_SINGLE_LOGOUT_NOT_SUPPORTED
+ )
+
+ ifname_idisNoneandself._nameidisnotNone:
+ name_id=self._nameid
+
+ ifname_id_formatisNoneandself._nameid_formatisnotNone:
+ name_id_format=self._nameid_format
+
+ logout_request=self.logout_request_class(
+ self._settings,
+ name_id=name_id,
+ session_index=session_index,
+ nq=nq,
+ name_id_format=name_id_format,
+ spnq=spnq
+ )
+ self._last_request=logout_request.get_xml()
+ self._last_request_id=logout_request.id
+
+ parameters={'SAMLRequest':logout_request.get_request()}
+ ifreturn_toisnotNone:
+ parameters['RelayState']=return_to
+ else:
+ parameters['RelayState']=OneLogin_Saml2_Utils.get_self_url_no_query(self._request_data)
+
+ security=self._settings.get_security_data()
+ ifsecurity.get('logoutRequestSigned',False):
+ self.add_request_signature(parameters,security['signatureAlgorithm'])
+ returnself.redirect_to(slo_url,parameters)
+
+
[docs]defget_sso_url(self):
+"""
+ Gets the SSO URL.
+
+ :returns: An URL, the SSO endpoint of the IdP
+ :rtype: string
+ """
+ returnself._settings.get_idp_sso_url()
+
+
[docs]defget_slo_url(self):
+"""
+ Gets the SLO URL.
+
+ :returns: An URL, the SLO endpoint of the IdP
+ :rtype: string
+ """
+ returnself._settings.get_idp_slo_url()
+
+
[docs]defget_slo_response_url(self):
+"""
+ Gets the SLO return URL for IdP-initiated logout.
+
+ :returns: an URL, the SLO return endpoint of the IdP
+ :rtype: string
+ """
+ returnself._settings.get_idp_slo_response_url()
+
+
[docs]defadd_request_signature(self,request_data,sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA256):
+"""
+ Builds the Signature of the SAML Request.
+
+ :param request_data: The Request parameters
+ :type request_data: dict
+
+ :param sign_algorithm: Signature algorithm method
+ :type sign_algorithm: string
+ """
+ returnself._build_signature(request_data,'SAMLRequest',sign_algorithm)
+
+
[docs]defadd_response_signature(self,response_data,sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA256):
+"""
+ Builds the Signature of the SAML Response.
+ :param response_data: The Response parameters
+ :type response_data: dict
+
+ :param sign_algorithm: Signature algorithm method
+ :type sign_algorithm: string
+ """
+ returnself._build_signature(response_data,'SAMLResponse',sign_algorithm)
+
+ @staticmethod
+ def_build_sign_query_from_qs(query_string,saml_type):
+"""
+ Build sign query from query string
+
+ :param query_string: The query string
+ :type query_string: str
+
+ :param saml_type: The target URL the user should be redirected to
+ :type saml_type: string SAMLRequest | SAMLResponse
+ """
+ args=('%s='%saml_type,'RelayState=','SigAlg=')
+ parts=query_string.split('&')
+ # Join in the order of arguments rather than the original order of parts.
+ return'&'.join(partforarginargsforpartinpartsifpart.startswith(arg))
+
+ @staticmethod
+ def_build_sign_query(saml_data,relay_state,algorithm,saml_type,lowercase_urlencoding=False):
+"""
+ Build sign query
+
+ :param saml_data: The Request data
+ :type saml_data: str
+
+ :param relay_state: The Relay State
+ :type relay_state: str
+
+ :param algorithm: The Signature Algorithm
+ :type algorithm: str
+
+ :param saml_type: The target URL the user should be redirected to
+ :type saml_type: string SAMLRequest | SAMLResponse
+
+ :param lowercase_urlencoding: lowercase or no
+ :type lowercase_urlencoding: boolean
+ """
+ sign_data=['%s=%s'%(saml_type,OneLogin_Saml2_Utils.escape_url(saml_data,lowercase_urlencoding))]
+ ifrelay_stateisnotNone:
+ sign_data.append('RelayState=%s'%OneLogin_Saml2_Utils.escape_url(relay_state,lowercase_urlencoding))
+ sign_data.append('SigAlg=%s'%OneLogin_Saml2_Utils.escape_url(algorithm,lowercase_urlencoding))
+ return'&'.join(sign_data)
+
+ def_build_signature(self,data,saml_type,sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA256):
+"""
+ Builds the Signature
+ :param data: The Request data
+ :type data: dict
+
+ :param saml_type: The target URL the user should be redirected to
+ :type saml_type: string SAMLRequest | SAMLResponse
+
+ :param sign_algorithm: Signature algorithm method
+ :type sign_algorithm: string
+ """
+ assertsaml_typein('SAMLRequest','SAMLResponse')
+ key=self.get_settings().get_sp_key()
+
+ ifnotkey:
+ raiseOneLogin_Saml2_Error(
+ "Trying to sign the %s but can't load the SP private key."%saml_type,
+ OneLogin_Saml2_Error.PRIVATE_KEY_NOT_FOUND
+ )
+
+ msg=self._build_sign_query(data[saml_type],
+ data.get('RelayState',None),
+ sign_algorithm,
+ saml_type)
+
+ sign_algorithm_transform_map={
+ OneLogin_Saml2_Constants.DSA_SHA1:xmlsec.Transform.DSA_SHA1,
+ OneLogin_Saml2_Constants.RSA_SHA1:xmlsec.Transform.RSA_SHA1,
+ OneLogin_Saml2_Constants.RSA_SHA256:xmlsec.Transform.RSA_SHA256,
+ OneLogin_Saml2_Constants.RSA_SHA384:xmlsec.Transform.RSA_SHA384,
+ OneLogin_Saml2_Constants.RSA_SHA512:xmlsec.Transform.RSA_SHA512
+ }
+ sign_algorithm_transform=sign_algorithm_transform_map.get(sign_algorithm,xmlsec.Transform.RSA_SHA256)
+
+ signature=OneLogin_Saml2_Utils.sign_binary(msg,key,sign_algorithm_transform,self._settings.is_debug_active())
+ data['Signature']=OneLogin_Saml2_Utils.b64encode(signature)
+ data['SigAlg']=sign_algorithm
+
+
+
+ def_validate_signature(self,data,saml_type,raise_exceptions=False):
+"""
+ Validate Signature
+
+ :param data: The Request data
+ :type data: dict
+
+ :param cert: The certificate to check signature
+ :type cert: str
+
+ :param saml_type: The target URL the user should be redirected to
+ :type saml_type: string SAMLRequest | SAMLResponse
+
+ :param raise_exceptions: Whether to return false on failure or raise an exception
+ :type raise_exceptions: Boolean
+ """
+ try:
+ signature=data.get('Signature',None)
+ ifsignatureisNone:
+ ifself._settings.is_strict()andself._settings.get_security_data().get('wantMessagesSigned',False):
+ raiseOneLogin_Saml2_ValidationError(
+ 'The %s is not signed. Rejected.'%saml_type,
+ OneLogin_Saml2_ValidationError.NO_SIGNED_MESSAGE
+ )
+ returnTrue
+
+ idp_data=self.get_settings().get_idp_data()
+
+ exists_x509cert=self.get_settings().get_idp_cert()isnotNone
+ exists_multix509sign='x509certMulti'inidp_dataand \
+ 'signing'inidp_data['x509certMulti']and \
+ idp_data['x509certMulti']['signing']
+
+ ifnot(exists_x509certorexists_multix509sign):
+ error_msg='In order to validate the sign on the %s, the x509cert of the IdP is required'%saml_type
+ self._errors.append(error_msg)
+ raiseOneLogin_Saml2_Error(
+ error_msg,
+ OneLogin_Saml2_Error.CERT_NOT_FOUND
+ )
+
+ sign_alg=data.get('SigAlg',OneLogin_Saml2_Constants.RSA_SHA1)
+ ifisinstance(sign_alg,bytes):
+ sign_alg=sign_alg.decode('utf8')
+
+ security=self._settings.get_security_data()
+ reject_deprecated_alg=security.get('rejectDeprecatedAlgorithm',False)
+ ifreject_deprecated_alg:
+ ifsign_alginOneLogin_Saml2_Constants.DEPRECATED_ALGORITHMS:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Deprecated signature algorithm found: %s'%sign_alg,
+ OneLogin_Saml2_ValidationError.DEPRECATED_SIGNATURE_METHOD
+ )
+
+ query_string=self._request_data.get('query_string')
+ ifquery_stringandself._request_data.get('validate_signature_from_qs'):
+ signed_query=self._build_sign_query_from_qs(query_string,saml_type)
+ else:
+ lowercase_urlencoding=self._request_data.get('lowercase_urlencoding',False)
+ signed_query=self._build_sign_query(data[saml_type],
+ data.get('RelayState'),
+ sign_alg,
+ saml_type,
+ lowercase_urlencoding)
+
+ ifexists_multix509sign:
+ forcertinidp_data['x509certMulti']['signing']:
+ ifOneLogin_Saml2_Utils.validate_binary_sign(signed_query,
+ OneLogin_Saml2_Utils.b64decode(signature),
+ cert,
+ sign_alg):
+ returnTrue
+ raiseOneLogin_Saml2_ValidationError(
+ 'Signature validation failed. %s rejected'%saml_type,
+ OneLogin_Saml2_ValidationError.INVALID_SIGNATURE
+ )
+ else:
+ cert=self.get_settings().get_idp_cert()
+
+ ifnotOneLogin_Saml2_Utils.validate_binary_sign(signed_query,
+ OneLogin_Saml2_Utils.b64decode(signature),
+ cert,
+ sign_alg,
+ self._settings.is_debug_active()):
+ raiseOneLogin_Saml2_ValidationError(
+ 'Signature validation failed. %s rejected'%saml_type,
+ OneLogin_Saml2_ValidationError.INVALID_SIGNATURE
+ )
+ returnTrue
+ exceptExceptionase:
+ self._error_reason=str(e)
+ ifraise_exceptions:
+ raisee
+ returnFalse
+
+
[docs]defget_last_response_xml(self,pretty_print_if_possible=False):
+"""
+ Retrieves the raw XML (decrypted) of the last SAML response,
+ or the last Logout Response generated or processed
+ :returns: SAML response XML
+ :rtype: string|None
+ """
+ response=None
+ ifself._last_responseisnotNone:
+ ifisinstance(self._last_response,compat.str_type):
+ response=self._last_response
+ else:
+ response=tostring(self._last_response,encoding='unicode',pretty_print=pretty_print_if_possible)
+ returnresponse
+
+
[docs]defget_last_request_xml(self):
+"""
+ Retrieves the raw XML sent in the last SAML request
+ :returns: SAML request XML
+ :rtype: string|None
+ """
+ returnself._last_requestorNone
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/saml2/_modules/onelogin/saml2/authn_request.html b/docs/saml2/_modules/onelogin/saml2/authn_request.html
new file mode 100644
index 00000000..b72bd675
--- /dev/null
+++ b/docs/saml2/_modules/onelogin/saml2/authn_request.html
@@ -0,0 +1,265 @@
+
+
+
+
+
+ onelogin.saml2.authn_request — SAML Python2/3 Toolkit 1 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
[docs]defget_request(self,deflate=True):
+"""
+ Returns unsigned AuthnRequest.
+ :param deflate: It makes the deflate process optional
+ :type: bool
+ :return: AuthnRequest maybe deflated and base64 encoded
+ :rtype: str object
+ """
+ ifdeflate:
+ request=OneLogin_Saml2_Utils.deflate_and_base64_encode(self._authn_request)
+ else:
+ request=OneLogin_Saml2_Utils.b64encode(self._authn_request)
+ returnrequest
+
+
[docs]defget_id(self):
+"""
+ Returns the AuthNRequest ID.
+ :return: AuthNRequest ID
+ :rtype: string
+ """
+ returnself._id
+
+
[docs]defget_xml(self):
+"""
+ Returns the XML that will be sent as part of the request
+ :return: XML request body
+ :rtype: string
+ """
+ returnself._authn_request
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/saml2/_modules/onelogin/saml2/compat.html b/docs/saml2/_modules/onelogin/saml2/compat.html
new file mode 100644
index 00000000..0497cf19
--- /dev/null
+++ b/docs/saml2/_modules/onelogin/saml2/compat.html
@@ -0,0 +1,166 @@
+
+
+
+
+
+ onelogin.saml2.compat — SAML Python2/3 Toolkit 1 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# -*- coding: utf-8 -*-
+
+""" OneLogin_Saml2_Error class
+
+
+Error class of SAML Python Toolkit.
+
+Defines common Error codes and has a custom initializator.
+
+"""
+
+
+
[docs]classOneLogin_Saml2_IdPMetadataParser(object):
+"""
+ A class that contain methods related to obtaining and parsing metadata from IdP
+
+ This class does not validate in any way the URL that is introduced,
+ make sure to validate it properly before use it in a get_metadata method.
+ """
+
+
[docs]@classmethod
+ defget_metadata(cls,url,validate_cert=True,timeout=None,headers=None):
+"""
+ Gets the metadata XML from the provided URL
+ :param url: Url where the XML of the Identity Provider Metadata is published.
+ :type url: string
+
+ :param validate_cert: If the url uses https schema, that flag enables or not the verification of the associated certificate.
+ :type validate_cert: bool
+
+ :param timeout: Timeout in seconds to wait for metadata response
+ :type timeout: int
+ :param headers: Extra headers to send in the request
+ :type headers: dict
+
+ :returns: metadata XML
+ :rtype: string
+ """
+ valid=False
+
+ request=urllib2.Request(url,headers=headersor{})
+
+ ifvalidate_cert:
+ response=urllib2.urlopen(request,timeout=timeout)
+ else:
+ ctx=ssl.create_default_context()
+ ctx.check_hostname=False
+ ctx.verify_mode=ssl.CERT_NONE
+ response=urllib2.urlopen(request,context=ctx,timeout=timeout)
+ xml=response.read()
+
+ ifxml:
+ try:
+ dom=OneLogin_Saml2_XML.to_etree(xml)
+ idp_descriptor_nodes=OneLogin_Saml2_XML.query(dom,'//md:IDPSSODescriptor')
+ ifidp_descriptor_nodes:
+ valid=True
+ exceptException:
+ pass
+
+ ifnotvalid:
+ raiseException('Not valid IdP XML found from URL: %s'%(url))
+
+ returnxml
+
+
[docs]@classmethod
+ defparse_remote(cls,url,validate_cert=True,entity_id=None,timeout=None,**kwargs):
+"""
+ Gets the metadata XML from the provided URL and parse it, returning a dict with extracted data
+ :param url: Url where the XML of the Identity Provider Metadata is published.
+ :type url: string
+
+ :param validate_cert: If the url uses https schema, that flag enables or not the verification of the associated certificate.
+ :type validate_cert: bool
+
+ :param entity_id: Specify the entity_id of the EntityDescriptor that you want to parse a XML
+ that contains multiple EntityDescriptor.
+ :type entity_id: string
+
+ :param timeout: Timeout in seconds to wait for metadata response
+ :type timeout: int
+
+ :returns: settings dict with extracted data
+ :rtype: dict
+ """
+ idp_metadata=cls.get_metadata(url,validate_cert,timeout,headers=kwargs.pop('headers',None))
+ returncls.parse(idp_metadata,entity_id=entity_id,**kwargs)
+
+
[docs]@classmethod
+ defparse(
+ cls,
+ idp_metadata,
+ required_sso_binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
+ required_slo_binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
+ entity_id=None):
+"""
+ Parses the Identity Provider metadata and return a dict with extracted data.
+
+ If there are multiple <IDPSSODescriptor> tags, parse only the first.
+
+ Parses only those SSO endpoints with the same binding as given by
+ the `required_sso_binding` parameter.
+
+ Parses only those SLO endpoints with the same binding as given by
+ the `required_slo_binding` parameter.
+
+ If the metadata specifies multiple SSO endpoints with the required
+ binding, extract only the first (the same holds true for SLO
+ endpoints).
+
+ :param idp_metadata: XML of the Identity Provider Metadata.
+ :type idp_metadata: string
+
+ :param required_sso_binding: Parse only POST or REDIRECT SSO endpoints.
+ :type required_sso_binding: one of OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT
+ or OneLogin_Saml2_Constants.BINDING_HTTP_POST
+
+ :param required_slo_binding: Parse only POST or REDIRECT SLO endpoints.
+ :type required_slo_binding: one of OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT
+ or OneLogin_Saml2_Constants.BINDING_HTTP_POST
+
+ :param entity_id: Specify the entity_id of the EntityDescriptor that you want to parse a XML
+ that contains multiple EntityDescriptor.
+ :type entity_id: string
+
+ :returns: settings dict with extracted data
+ :rtype: dict
+ """
+ data={}
+
+ dom=OneLogin_Saml2_XML.to_etree(idp_metadata)
+ idp_entity_id=want_authn_requests_signed=idp_name_id_format=idp_sso_url=idp_slo_url=certs=None
+
+ entity_desc_path='//md:EntityDescriptor'
+ ifentity_id:
+ entity_desc_path+="[@entityID='%s']"%entity_id
+ entity_descriptor_nodes=OneLogin_Saml2_XML.query(dom,entity_desc_path)
+
+ iflen(entity_descriptor_nodes)>0:
+ entity_descriptor_node=entity_descriptor_nodes[0]
+ idp_descriptor_nodes=OneLogin_Saml2_XML.query(entity_descriptor_node,'./md:IDPSSODescriptor')
+ iflen(idp_descriptor_nodes)>0:
+ idp_descriptor_node=idp_descriptor_nodes[0]
+
+ idp_entity_id=entity_descriptor_node.get('entityID',None)
+
+ want_authn_requests_signed=idp_descriptor_node.get('WantAuthnRequestsSigned',None)
+
+ name_id_format_nodes=OneLogin_Saml2_XML.query(idp_descriptor_node,'./md:NameIDFormat')
+ iflen(name_id_format_nodes)>0:
+ idp_name_id_format=OneLogin_Saml2_XML.element_text(name_id_format_nodes[0])
+
+ sso_nodes=OneLogin_Saml2_XML.query(
+ idp_descriptor_node,
+ "./md:SingleSignOnService[@Binding='%s']"%required_sso_binding
+ )
+
+ iflen(sso_nodes)>0:
+ idp_sso_url=sso_nodes[0].get('Location',None)
+
+ slo_nodes=OneLogin_Saml2_XML.query(
+ idp_descriptor_node,
+ "./md:SingleLogoutService[@Binding='%s']"%required_slo_binding
+ )
+
+ iflen(slo_nodes)>0:
+ idp_slo_url=slo_nodes[0].get('Location',None)
+
+ signing_nodes=OneLogin_Saml2_XML.query(idp_descriptor_node,"./md:KeyDescriptor[not(contains(@use, 'encryption'))]/ds:KeyInfo/ds:X509Data/ds:X509Certificate")
+ encryption_nodes=OneLogin_Saml2_XML.query(idp_descriptor_node,"./md:KeyDescriptor[not(contains(@use, 'signing'))]/ds:KeyInfo/ds:X509Data/ds:X509Certificate")
+
+ iflen(signing_nodes)>0orlen(encryption_nodes)>0:
+ certs={}
+ iflen(signing_nodes)>0:
+ certs['signing']=[]
+ forcert_nodeinsigning_nodes:
+ certs['signing'].append(''.join(OneLogin_Saml2_XML.element_text(cert_node).split()))
+ iflen(encryption_nodes)>0:
+ certs['encryption']=[]
+ forcert_nodeinencryption_nodes:
+ certs['encryption'].append(''.join(OneLogin_Saml2_XML.element_text(cert_node).split()))
+
+ data['idp']={}
+
+ ifidp_entity_idisnotNone:
+ data['idp']['entityId']=idp_entity_id
+
+ ifidp_sso_urlisnotNone:
+ data['idp']['singleSignOnService']={}
+ data['idp']['singleSignOnService']['url']=idp_sso_url
+ data['idp']['singleSignOnService']['binding']=required_sso_binding
+
+ ifidp_slo_urlisnotNone:
+ data['idp']['singleLogoutService']={}
+ data['idp']['singleLogoutService']['url']=idp_slo_url
+ data['idp']['singleLogoutService']['binding']=required_slo_binding
+
+ ifwant_authn_requests_signedisnotNone:
+ data['security']={}
+ data['security']['authnRequestsSigned']=want_authn_requests_signed=="true"
+
+ ifidp_name_id_format:
+ data['sp']={}
+ data['sp']['NameIDFormat']=idp_name_id_format
+
+ ifcertsisnotNone:
+ if(len(certs)==1and
+ (('signing'incertsandlen(certs['signing'])==1)or
+ ('encryption'incertsandlen(certs['encryption'])==1)))or \
+ (('signing'incertsandlen(certs['signing'])==1)and
+ ('encryption'incertsandlen(certs['encryption'])==1and
+ certs['signing'][0]==certs['encryption'][0])):
+ if'signing'incerts:
+ data['idp']['x509cert']=certs['signing'][0]
+ else:
+ data['idp']['x509cert']=certs['encryption'][0]
+ else:
+ data['idp']['x509certMulti']=certs
+ returndata
+
+
[docs]@staticmethod
+ defmerge_settings(settings,new_metadata_settings):
+"""
+ Will update the settings with the provided new settings data extracted from the IdP metadata
+ :param settings: Current settings dict data
+ :type settings: dict
+ :param new_metadata_settings: Settings to be merged (extracted from IdP metadata after parsing)
+ :type new_metadata_settings: dict
+ :returns: merged settings
+ :rtype: dict
+ """
+ fordin(settings,new_metadata_settings):
+ ifnotisinstance(d,dict):
+ raiseTypeError('Both arguments must be dictionaries.')
+
+ # Guarantee to not modify original data (`settings.copy()` would not
+ # be sufficient, as it's just a shallow copy).
+ result_settings=deepcopy(settings)
+
+ # previously I will take care of cert stuff
+ if'idp'innew_metadata_settingsand'idp'inresult_settings:
+ ifnew_metadata_settings['idp'].get('x509cert',None)andresult_settings['idp'].get('x509certMulti',None):
+ delresult_settings['idp']['x509certMulti']
+ ifnew_metadata_settings['idp'].get('x509certMulti',None)andresult_settings['idp'].get('x509cert',None):
+ delresult_settings['idp']['x509cert']
+
+ # Merge `new_metadata_settings` into `result_settings`.
+ dict_deep_merge(result_settings,new_metadata_settings)
+ returnresult_settings
+
+
+
[docs]defdict_deep_merge(a,b,path=None):
+"""Deep-merge dictionary `b` into dictionary `a`.
+
+ Kudos to http://stackoverflow.com/a/7205107/145400
+ """
+ ifpathisNone:
+ path=[]
+ forkeyinb:
+ ifkeyina:
+ ifisinstance(a[key],dict)andisinstance(b[key],dict):
+ dict_deep_merge(a[key],b[key],path+[str(key)])
+ elifa[key]==b[key]:
+ # Key conflict, but equal value.
+ pass
+ else:
+ # Key/value conflict. Prioritize b over a.
+ a[key]=b[key]
+ else:
+ a[key]=b[key]
+ returna
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/saml2/_modules/onelogin/saml2/logout_request.html b/docs/saml2/_modules/onelogin/saml2/logout_request.html
new file mode 100644
index 00000000..bdc48e77
--- /dev/null
+++ b/docs/saml2/_modules/onelogin/saml2/logout_request.html
@@ -0,0 +1,465 @@
+
+
+
+
+
+ onelogin.saml2.logout_request — SAML Python2/3 Toolkit 1 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# -*- coding: utf-8 -*-
+
+""" OneLogin_Saml2_Logout_Request class
+
+
+Logout Request class of SAML Python Toolkit.
+
+"""
+
+fromonelogin.saml2importcompat
+fromonelogin.saml2.constantsimportOneLogin_Saml2_Constants
+fromonelogin.saml2.utilsimportOneLogin_Saml2_Utils,OneLogin_Saml2_Error,OneLogin_Saml2_ValidationError
+fromonelogin.saml2.xml_templatesimportOneLogin_Saml2_Templates
+fromonelogin.saml2.xml_utilsimportOneLogin_Saml2_XML
+
+
+
[docs]classOneLogin_Saml2_Logout_Request(object):
+"""
+
+ This class handles a Logout Request.
+
+ Builds a Logout Response object and validates it.
+
+ """
+
+ def__init__(self,settings,request=None,name_id=None,session_index=None,nq=None,name_id_format=None,spnq=None):
+"""
+ Constructs the Logout Request object.
+
+ :param settings: Setting data
+ :type settings: OneLogin_Saml2_Settings
+
+ :param request: Optional. A LogoutRequest to be loaded instead build one.
+ :type request: string
+
+ :param name_id: The NameID that will be set in the LogoutRequest.
+ :type name_id: string
+
+ :param session_index: SessionIndex that identifies the session of the user.
+ :type session_index: string
+
+ :param nq: IDP Name Qualifier
+ :type: string
+
+ :param name_id_format: The NameID Format that will be set in the LogoutRequest.
+ :type: string
+
+ :param spnq: SP Name Qualifier
+ :type: string
+ """
+ self._settings=settings
+ self._error=None
+ self.id=None
+
+ ifrequestisNone:
+ sp_data=self._settings.get_sp_data()
+ idp_data=self._settings.get_idp_data()
+ security=self._settings.get_security_data()
+
+ self.id=self._generate_request_id()
+
+ issue_instant=OneLogin_Saml2_Utils.parse_time_to_SAML(OneLogin_Saml2_Utils.now())
+
+ cert=None
+ ifsecurity['nameIdEncrypted']:
+ exists_multix509enc='x509certMulti'inidp_dataand \
+ 'encryption'inidp_data['x509certMulti']and \
+ idp_data['x509certMulti']['encryption']
+ ifexists_multix509enc:
+ cert=idp_data['x509certMulti']['encryption'][0]
+ else:
+ cert=self._settings.get_idp_cert()
+
+ ifname_idisnotNone:
+ ifnotname_id_formatandsp_data['NameIDFormat']!=OneLogin_Saml2_Constants.NAMEID_UNSPECIFIED:
+ name_id_format=sp_data['NameIDFormat']
+ else:
+ name_id=idp_data['entityId']
+ name_id_format=OneLogin_Saml2_Constants.NAMEID_ENTITY
+
+ # From saml-core-2.0-os 8.3.6, when the entity Format is used:
+ # "The NameQualifier, SPNameQualifier, and SPProvidedID attributes
+ # MUST be omitted.
+ ifname_id_formatandname_id_format==OneLogin_Saml2_Constants.NAMEID_ENTITY:
+ nq=None
+ spnq=None
+
+ # NameID Format UNSPECIFIED omitted
+ ifname_id_formatandname_id_format==OneLogin_Saml2_Constants.NAMEID_UNSPECIFIED:
+ name_id_format=None
+
+ name_id_obj=OneLogin_Saml2_Utils.generate_name_id(
+ name_id,
+ spnq,
+ name_id_format,
+ cert,
+ False,
+ nq
+ )
+
+ ifsession_index:
+ session_index_str='<samlp:SessionIndex>%s</samlp:SessionIndex>'%session_index
+ else:
+ session_index_str=''
+
+ logout_request=OneLogin_Saml2_Templates.LOGOUT_REQUEST% \
+ {
+ 'id':self.id,
+ 'issue_instant':issue_instant,
+ 'single_logout_url':self._settings.get_idp_slo_url(),
+ 'entity_id':sp_data['entityId'],
+ 'name_id':name_id_obj,
+ 'session_index':session_index_str,
+ }
+ else:
+ logout_request=OneLogin_Saml2_Utils.decode_base64_and_inflate(request,ignore_zip=True)
+ self.id=self.get_id(logout_request)
+
+ self._logout_request=compat.to_string(logout_request)
+
+
[docs]defget_request(self,deflate=True):
+"""
+ Returns the Logout Request deflated, base64encoded
+ :param deflate: It makes the deflate process optional
+ :type: bool
+ :return: Logout Request maybe deflated and base64 encoded
+ :rtype: str object
+ """
+ ifdeflate:
+ request=OneLogin_Saml2_Utils.deflate_and_base64_encode(self._logout_request)
+ else:
+ request=OneLogin_Saml2_Utils.b64encode(self._logout_request)
+ returnrequest
+
+
[docs]defget_xml(self):
+"""
+ Returns the XML that will be sent as part of the request
+ or that was received at the SP
+ :return: XML request body
+ :rtype: string
+ """
+ returnself._logout_request
+
+
[docs]@classmethod
+ defget_id(cls,request):
+"""
+ Returns the ID of the Logout Request
+ :param request: Logout Request Message
+ :type request: string|DOMDocument
+ :return: string ID
+ :rtype: str object
+ """
+
+ elem=OneLogin_Saml2_XML.to_etree(request)
+ returnelem.get('ID',None)
+
+
[docs]@classmethod
+ defget_nameid_data(cls,request,key=None):
+"""
+ Gets the NameID Data of the the Logout Request
+ :param request: Logout Request Message
+ :type request: string|DOMDocument
+ :param key: The SP key
+ :type key: string
+ :return: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
+ :rtype: dict
+ """
+ elem=OneLogin_Saml2_XML.to_etree(request)
+ name_id=None
+ encrypted_entries=OneLogin_Saml2_XML.query(elem,'/samlp:LogoutRequest/saml:EncryptedID')
+
+ iflen(encrypted_entries)==1:
+ ifkeyisNone:
+ raiseOneLogin_Saml2_Error(
+ 'Private Key is required in order to decrypt the NameID, check settings',
+ OneLogin_Saml2_Error.PRIVATE_KEY_NOT_FOUND
+ )
+
+ encrypted_data_nodes=OneLogin_Saml2_XML.query(elem,'/samlp:LogoutRequest/saml:EncryptedID/xenc:EncryptedData')
+ iflen(encrypted_data_nodes)==1:
+ encrypted_data=encrypted_data_nodes[0]
+ name_id=OneLogin_Saml2_Utils.decrypt_element(encrypted_data,key)
+ else:
+ entries=OneLogin_Saml2_XML.query(elem,'/samlp:LogoutRequest/saml:NameID')
+ iflen(entries)==1:
+ name_id=entries[0]
+
+ ifname_idisNone:
+ raiseOneLogin_Saml2_ValidationError(
+ 'NameID not found in the Logout Request',
+ OneLogin_Saml2_ValidationError.NO_NAMEID
+ )
+
+ name_id_data={
+ 'Value':OneLogin_Saml2_XML.element_text(name_id)
+ }
+ forattrin['Format','SPNameQualifier','NameQualifier']:
+ ifattrinname_id.attrib:
+ name_id_data[attr]=name_id.attrib[attr]
+
+ returnname_id_data
+
+
[docs]@classmethod
+ defget_nameid(cls,request,key=None):
+"""
+ Gets the NameID of the Logout Request Message
+ :param request: Logout Request Message
+ :type request: string|DOMDocument
+ :param key: The SP key
+ :type key: string
+ :return: Name ID Value
+ :rtype: string
+ """
+ name_id=cls.get_nameid_data(request,key)
+ returnname_id['Value']
+
+
[docs]@classmethod
+ defget_nameid_format(cls,request,key=None):
+"""
+ Gets the NameID Format of the Logout Request Message
+ :param request: Logout Request Message
+ :type request: string|DOMDocument
+ :param key: The SP key
+ :type key: string
+ :return: Name ID Format
+ :rtype: string
+ """
+ name_id_format=None
+ name_id_data=cls.get_nameid_data(request,key)
+ ifname_id_dataand'Format'inname_id_data.keys():
+ name_id_format=name_id_data['Format']
+ returnname_id_format
+# -*- coding: utf-8 -*-
+
+""" OneLogin_Saml2_Logout_Response class
+
+
+Logout Response class of SAML Python Toolkit.
+
+"""
+
+fromonelogin.saml2importcompat
+fromonelogin.saml2.constantsimportOneLogin_Saml2_Constants
+fromonelogin.saml2.utilsimportOneLogin_Saml2_Utils,OneLogin_Saml2_ValidationError
+fromonelogin.saml2.xml_templatesimportOneLogin_Saml2_Templates
+fromonelogin.saml2.xml_utilsimportOneLogin_Saml2_XML
+
+
+
[docs]classOneLogin_Saml2_Logout_Response(object):
+"""
+
+ This class handles a Logout Response. It Builds or parses a Logout Response object
+ and validates it.
+
+ """
+
+ def__init__(self,settings,response=None):
+"""
+ Constructs a Logout Response object (Initialize params from settings
+ and if provided load the Logout Response.
+
+ Arguments are:
+ * (OneLogin_Saml2_Settings) settings. Setting data
+ * (string) response. An UUEncoded SAML Logout
+ response from the IdP.
+ """
+ self._settings=settings
+ self._error=None
+ self.id=None
+
+ ifresponseisnotNone:
+ self._logout_response=compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(response,ignore_zip=True))
+ self.document=OneLogin_Saml2_XML.to_etree(self._logout_response)
+ self.id=self.document.get('ID',None)
+
+
[docs]defget_issuer(self):
+"""
+ Gets the Issuer of the Logout Response Message
+ :return: The Issuer
+ :rtype: string
+ """
+ issuer=None
+ issuer_nodes=self._query('/samlp:LogoutResponse/saml:Issuer')
+ iflen(issuer_nodes)==1:
+ issuer=OneLogin_Saml2_XML.element_text(issuer_nodes[0])
+ returnissuer
+
+
[docs]defget_status(self):
+"""
+ Gets the Status
+ :return: The Status
+ :rtype: string
+ """
+ entries=self._query('/samlp:LogoutResponse/samlp:Status/samlp:StatusCode')
+ iflen(entries)==0:
+ returnNone
+ status=entries[0].attrib['Value']
+ returnstatus
+
+
[docs]defis_valid(self,request_data,request_id=None,raise_exceptions=False):
+"""
+ Determines if the SAML LogoutResponse is valid
+ :param request_id: The ID of the LogoutRequest sent by this SP to the IdP
+ :type request_id: string
+
+ :param raise_exceptions: Whether to return false on failure or raise an exception
+ :type raise_exceptions: Boolean
+
+ :return: Returns if the SAML LogoutResponse is or not valid
+ :rtype: boolean
+ """
+ self._error=None
+ try:
+ idp_data=self._settings.get_idp_data()
+ idp_entity_id=idp_data['entityId']
+ get_data=request_data['get_data']
+
+ ifself._settings.is_strict():
+ res=OneLogin_Saml2_XML.validate_xml(self.document,'saml-schema-protocol-2.0.xsd',self._settings.is_debug_active())
+ ifisinstance(res,str):
+ raiseOneLogin_Saml2_ValidationError(
+ 'Invalid SAML Logout Request. Not match the saml-schema-protocol-2.0.xsd',
+ OneLogin_Saml2_ValidationError.INVALID_XML_FORMAT
+ )
+
+ security=self._settings.get_security_data()
+
+ # Check if the InResponseTo of the Logout Response matches the ID of the Logout Request (requestId) if provided
+ in_response_to=self.get_in_response_to()
+ ifrequest_idisnotNoneandin_response_toandin_response_to!=request_id:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The InResponseTo of the Logout Response: %s, does not match the ID of the Logout request sent by the SP: %s'%(in_response_to,request_id),
+ OneLogin_Saml2_ValidationError.WRONG_INRESPONSETO
+ )
+
+ # Check issuer
+ issuer=self.get_issuer()
+ ifissuerisnotNoneandissuer!=idp_entity_id:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Invalid issuer in the Logout Response (expected %(idpEntityId)s, got %(issuer)s)'%
+ {
+ 'idpEntityId':idp_entity_id,
+ 'issuer':issuer
+ },
+ OneLogin_Saml2_ValidationError.WRONG_ISSUER
+ )
+
+ current_url=OneLogin_Saml2_Utils.get_self_url_no_query(request_data)
+
+ # Check destination
+ destination=self.document.get('Destination',None)
+ ifdestination:
+ ifnotOneLogin_Saml2_Utils.normalize_url(url=destination).startswith(OneLogin_Saml2_Utils.normalize_url(url=current_url)):
+ raiseOneLogin_Saml2_ValidationError(
+ 'The LogoutResponse was received at %s instead of %s'%(current_url,destination),
+ OneLogin_Saml2_ValidationError.WRONG_DESTINATION
+ )
+
+ ifsecurity['wantMessagesSigned']:
+ if'Signature'notinget_data:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The Message of the Logout Response is not signed and the SP require it',
+ OneLogin_Saml2_ValidationError.NO_SIGNED_MESSAGE
+ )
+ returnTrue
+ # pylint: disable=R0801
+ exceptExceptionaserr:
+ self._error=str(err)
+ debug=self._settings.is_debug_active()
+ ifdebug:
+ print(err)
+ ifraise_exceptions:
+ raise
+ returnFalse
+
+ def_query(self,query):
+"""
+ Extracts a node from the Etree (Logout Response Message)
+ :param query: Xpath Expression
+ :type query: string
+ :return: The queried node
+ :rtype: Element
+ """
+ returnOneLogin_Saml2_XML.query(self.document,query)
+
+
[docs]defbuild(self,in_response_to,status=OneLogin_Saml2_Constants.STATUS_SUCCESS):
+"""
+ Creates a Logout Response object.
+ :param in_response_to: InResponseTo value for the Logout Response.
+ :type in_response_to: string
+ :param: status: The status of the response
+ :type: status: string
+ """
+ sp_data=self._settings.get_sp_data()
+
+ self.id=self._generate_request_id()
+
+ issue_instant=OneLogin_Saml2_Utils.parse_time_to_SAML(OneLogin_Saml2_Utils.now())
+
+ logout_response=OneLogin_Saml2_Templates.LOGOUT_RESPONSE%{
+ "id":self.id,
+ "issue_instant":issue_instant,
+ "destination":self._settings.get_idp_slo_response_url(),
+ "in_response_to":in_response_to,
+ "entity_id":sp_data["entityId"],
+ "status":status,
+ }
+
+ self._logout_response=logout_response
+
+
[docs]defget_in_response_to(self):
+"""
+ Gets the ID of the LogoutRequest which this response is in response to
+ :returns: ID of LogoutRequest this LogoutResponse is in response to or None if it is not present
+ :rtype: str
+ """
+ returnself.document.get('InResponseTo')
+
+
[docs]defget_response(self,deflate=True):
+"""
+ Returns a Logout Response object.
+ :param deflate: It makes the deflate process optional
+ :type: bool
+ :return: Logout Response maybe deflated and base64 encoded
+ :rtype: string
+ """
+ ifdeflate:
+ response=OneLogin_Saml2_Utils.deflate_and_base64_encode(self._logout_response)
+ else:
+ response=OneLogin_Saml2_Utils.b64encode(self._logout_response)
+ returnresponse
+
+
[docs]defget_error(self):
+"""
+ After executing a validation process, if it fails this method returns the cause
+ """
+ returnself._error
+
+
[docs]defget_xml(self):
+"""
+ Returns the XML that will be sent as part of the response
+ or that was received at the SP
+ :return: XML response body
+ :rtype: string
+ """
+ returnself._logout_response
[docs]classOneLogin_Saml2_Metadata(object):
+"""
+
+ A class that contains methods related to the metadata of the SP
+
+ """
+
+ TIME_VALID=172800# 2 days
+ TIME_CACHED=604800# 1 week
+
+
+# -*- coding: utf-8 -*-
+
+""" OneLogin_Saml2_Response class
+
+
+SAML Response class of SAML Python Toolkit.
+
+"""
+
+fromcopyimportdeepcopy
+fromonelogin.saml2.constantsimportOneLogin_Saml2_Constants
+fromonelogin.saml2.utilsimportOneLogin_Saml2_Utils,OneLogin_Saml2_Error,OneLogin_Saml2_ValidationError,return_false_on_exception
+fromonelogin.saml2.xml_utilsimportOneLogin_Saml2_XML
+
+
+
[docs]classOneLogin_Saml2_Response(object):
+"""
+
+ This class handles a SAML Response. It parses or validates
+ a Logout Response object.
+
+ """
+
+ def__init__(self,settings,response):
+"""
+ Constructs the response object.
+
+ :param settings: The setting info
+ :type settings: OneLogin_Saml2_Setting object
+
+ :param response: The base64 encoded, XML string containing the samlp:Response
+ :type response: string
+ """
+ self._settings=settings
+ self._error=None
+ self.response=OneLogin_Saml2_Utils.b64decode(response)
+ self.document=OneLogin_Saml2_XML.to_etree(self.response)
+ self.decrypted_document=None
+ self.encrypted=None
+ self.valid_scd_not_on_or_after=None
+
+ # Quick check for the presence of EncryptedAssertion
+ encrypted_assertion_nodes=self._query('/samlp:Response/saml:EncryptedAssertion')
+ ifencrypted_assertion_nodes:
+ decrypted_document=deepcopy(self.document)
+ self.encrypted=True
+ self.decrypted_document=self._decrypt_assertion(decrypted_document)
+
+
[docs]defis_valid(self,request_data,request_id=None,raise_exceptions=False):
+"""
+ Validates the response object.
+
+ :param request_data: Request Data
+ :type request_data: dict
+
+ :param request_id: Optional argument. The ID of the AuthNRequest sent by this SP to the IdP
+ :type request_id: string
+
+ :param raise_exceptions: Whether to return false on failure or raise an exception
+ :type raise_exceptions: Boolean
+
+ :returns: True if the SAML Response is valid, False if not
+ :rtype: bool
+ """
+ self._error=None
+ try:
+ # Checks SAML version
+ ifself.document.get('Version',None)!='2.0':
+ raiseOneLogin_Saml2_ValidationError(
+ 'Unsupported SAML version',
+ OneLogin_Saml2_ValidationError.UNSUPPORTED_SAML_VERSION
+ )
+
+ # Checks that ID exists
+ ifself.document.get('ID',None)isNone:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Missing ID attribute on SAML Response',
+ OneLogin_Saml2_ValidationError.MISSING_ID
+ )
+
+ # Checks that the response has the SUCCESS status
+ self.check_status()
+
+ # Checks that the response only has one assertion
+ ifnotself.validate_num_assertions():
+ raiseOneLogin_Saml2_ValidationError(
+ 'SAML Response must contain 1 assertion',
+ OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_ASSERTIONS
+ )
+
+ idp_data=self._settings.get_idp_data()
+ idp_entity_id=idp_data['entityId']
+ sp_data=self._settings.get_sp_data()
+ sp_entity_id=sp_data['entityId']
+
+ signed_elements=self.process_signed_elements()
+
+ has_signed_response='{%s}Response'%OneLogin_Saml2_Constants.NS_SAMLPinsigned_elements
+ has_signed_assertion='{%s}Assertion'%OneLogin_Saml2_Constants.NS_SAMLinsigned_elements
+
+ ifself._settings.is_strict():
+ no_valid_xml_msg='Invalid SAML Response. Not match the saml-schema-protocol-2.0.xsd'
+ res=OneLogin_Saml2_XML.validate_xml(self.document,'saml-schema-protocol-2.0.xsd',self._settings.is_debug_active())
+ ifisinstance(res,str):
+ raiseOneLogin_Saml2_ValidationError(
+ no_valid_xml_msg,
+ OneLogin_Saml2_ValidationError.INVALID_XML_FORMAT
+ )
+
+ # If encrypted, check also the decrypted document
+ ifself.encrypted:
+ res=OneLogin_Saml2_XML.validate_xml(self.decrypted_document,'saml-schema-protocol-2.0.xsd',self._settings.is_debug_active())
+ ifisinstance(res,str):
+ raiseOneLogin_Saml2_ValidationError(
+ no_valid_xml_msg,
+ OneLogin_Saml2_ValidationError.INVALID_XML_FORMAT
+ )
+
+ security=self._settings.get_security_data()
+ current_url=OneLogin_Saml2_Utils.get_self_url_no_query(request_data)
+
+ # Check if the InResponseTo of the Response matchs the ID of the AuthNRequest (requestId) if provided
+ in_response_to=self.get_in_response_to()
+ ifin_response_toisnotNoneandrequest_idisnotNone:
+ ifin_response_to!=request_id:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The InResponseTo of the Response: %s, does not match the ID of the AuthNRequest sent by the SP: %s'%(in_response_to,request_id),
+ OneLogin_Saml2_ValidationError.WRONG_INRESPONSETO
+ )
+
+ ifnotself.encryptedandsecurity['wantAssertionsEncrypted']:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The assertion of the Response is not encrypted and the SP require it',
+ OneLogin_Saml2_ValidationError.NO_ENCRYPTED_ASSERTION
+ )
+
+ ifsecurity['wantNameIdEncrypted']:
+ encrypted_nameid_nodes=self._query_assertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData')
+ iflen(encrypted_nameid_nodes)!=1:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The NameID of the Response is not encrypted and the SP require it',
+ OneLogin_Saml2_ValidationError.NO_ENCRYPTED_NAMEID
+ )
+
+ # Checks that a Conditions element exists
+ ifnotself.check_one_condition():
+ raiseOneLogin_Saml2_ValidationError(
+ 'The Assertion must include a Conditions element',
+ OneLogin_Saml2_ValidationError.MISSING_CONDITIONS
+ )
+
+ # Validates Assertion timestamps
+ self.validate_timestamps(raise_exceptions=True)
+
+ # Checks that an AuthnStatement element exists and is unique
+ ifnotself.check_one_authnstatement():
+ raiseOneLogin_Saml2_ValidationError(
+ 'The Assertion must include an AuthnStatement element',
+ OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_AUTHSTATEMENTS
+ )
+
+ # Checks that the response has all of the AuthnContexts that we provided in the request.
+ # Only check if failOnAuthnContextMismatch is true and requestedAuthnContext is set to a list.
+ requested_authn_contexts=security['requestedAuthnContext']
+ ifsecurity['failOnAuthnContextMismatch']andrequested_authn_contextsandrequested_authn_contextsisnotTrue:
+ authn_contexts=self.get_authn_contexts()
+ unmatched_contexts=set(authn_contexts).difference(requested_authn_contexts)
+ ifunmatched_contexts:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The AuthnContext "%s" was not a requested context "%s"'%(', '.join(unmatched_contexts),', '.join(requested_authn_contexts)),
+ OneLogin_Saml2_ValidationError.AUTHN_CONTEXT_MISMATCH
+ )
+
+ # Checks that there is at least one AttributeStatement if required
+ attribute_statement_nodes=self._query_assertion('/saml:AttributeStatement')
+ ifsecurity.get('wantAttributeStatement',True)andnotattribute_statement_nodes:
+ raiseOneLogin_Saml2_ValidationError(
+ 'There is no AttributeStatement on the Response',
+ OneLogin_Saml2_ValidationError.NO_ATTRIBUTESTATEMENT
+ )
+
+ encrypted_attributes_nodes=self._query_assertion('/saml:AttributeStatement/saml:EncryptedAttribute')
+ ifencrypted_attributes_nodes:
+ raiseOneLogin_Saml2_ValidationError(
+ 'There is an EncryptedAttribute in the Response and this SP not support them',
+ OneLogin_Saml2_ValidationError.ENCRYPTED_ATTRIBUTES
+ )
+
+ # Checks destination
+ destination=self.document.get('Destination',None)
+ ifdestination:
+ ifnotOneLogin_Saml2_Utils.normalize_url(url=destination).startswith(OneLogin_Saml2_Utils.normalize_url(url=current_url)):
+ # TODO: Review if following lines are required, since we can control the
+ # request_data
+ # current_url_routed = OneLogin_Saml2_Utils.get_self_routed_url_no_query(request_data)
+ # if not destination.startswith(current_url_routed):
+ raiseOneLogin_Saml2_ValidationError(
+ 'The response was received at %s instead of %s'%(current_url,destination),
+ OneLogin_Saml2_ValidationError.WRONG_DESTINATION
+ )
+ elifdestination=='':
+ raiseOneLogin_Saml2_ValidationError(
+ 'The response has an empty Destination value',
+ OneLogin_Saml2_ValidationError.EMPTY_DESTINATION
+ )
+ # Checks audience
+ valid_audiences=self.get_audiences()
+ ifvalid_audiencesandsp_entity_idnotinvalid_audiences:
+ raiseOneLogin_Saml2_ValidationError(
+ '%s is not a valid audience for this Response'%sp_entity_id,
+ OneLogin_Saml2_ValidationError.WRONG_AUDIENCE
+ )
+
+ # Checks the issuers
+ issuers=self.get_issuers()
+ forissuerinissuers:
+ ifissuerisNoneorissuer!=idp_entity_id:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Invalid issuer in the Assertion/Response (expected %(idpEntityId)s, got %(issuer)s)'%
+ {
+ 'idpEntityId':idp_entity_id,
+ 'issuer':issuer
+ },
+ OneLogin_Saml2_ValidationError.WRONG_ISSUER
+ )
+
+ # Checks the session Expiration
+ session_expiration=self.get_session_not_on_or_after()
+ ifsession_expirationandsession_expiration<=OneLogin_Saml2_Utils.now():
+ raiseOneLogin_Saml2_ValidationError(
+ 'The attributes have expired, based on the SessionNotOnOrAfter of the AttributeStatement of this Response',
+ OneLogin_Saml2_ValidationError.SESSION_EXPIRED
+ )
+
+ # Checks the SubjectConfirmation, at least one SubjectConfirmation must be valid
+ any_subject_confirmation=False
+ subject_confirmation_nodes=self._query_assertion('/saml:Subject/saml:SubjectConfirmation')
+
+ forscninsubject_confirmation_nodes:
+ method=scn.get('Method',None)
+ ifmethodandmethod!=OneLogin_Saml2_Constants.CM_BEARER:
+ continue
+ sc_data=scn.find('saml:SubjectConfirmationData',namespaces=OneLogin_Saml2_Constants.NSMAP)
+ ifsc_dataisNone:
+ continue
+ else:
+ irt=sc_data.get('InResponseTo',None)
+ ifin_response_toandirtandirt!=in_response_to:
+ continue
+ recipient=sc_data.get('Recipient',None)
+ ifrecipientandcurrent_urlnotinrecipient:
+ continue
+ nooa=sc_data.get('NotOnOrAfter',None)
+ ifnooa:
+ parsed_nooa=OneLogin_Saml2_Utils.parse_SAML_to_time(nooa)
+ ifparsed_nooa<=OneLogin_Saml2_Utils.now():
+ continue
+ nb=sc_data.get('NotBefore',None)
+ ifnb:
+ parsed_nb=OneLogin_Saml2_Utils.parse_SAML_to_time(nb)
+ ifparsed_nb>OneLogin_Saml2_Utils.now():
+ continue
+
+ ifnooa:
+ self.valid_scd_not_on_or_after=OneLogin_Saml2_Utils.parse_SAML_to_time(nooa)
+
+ any_subject_confirmation=True
+ break
+
+ ifnotany_subject_confirmation:
+ raiseOneLogin_Saml2_ValidationError(
+ 'A valid SubjectConfirmation was not found on this Response',
+ OneLogin_Saml2_ValidationError.WRONG_SUBJECTCONFIRMATION
+ )
+
+ ifsecurity['wantAssertionsSigned']andnothas_signed_assertion:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The Assertion of the Response is not signed and the SP require it',
+ OneLogin_Saml2_ValidationError.NO_SIGNED_ASSERTION
+ )
+
+ ifsecurity['wantMessagesSigned']andnothas_signed_response:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The Message of the Response is not signed and the SP require it',
+ OneLogin_Saml2_ValidationError.NO_SIGNED_MESSAGE
+ )
+
+ ifnotsigned_elementsor(nothas_signed_responseandnothas_signed_assertion):
+ raiseOneLogin_Saml2_ValidationError(
+ 'No Signature found. SAML Response rejected',
+ OneLogin_Saml2_ValidationError.NO_SIGNATURE_FOUND
+ )
+ else:
+ cert=self._settings.get_idp_cert()
+ fingerprint=idp_data.get('certFingerprint',None)
+ iffingerprint:
+ fingerprint=OneLogin_Saml2_Utils.format_finger_print(fingerprint)
+ fingerprintalg=idp_data.get('certFingerprintAlgorithm',None)
+
+ multicerts=None
+ if'x509certMulti'inidp_dataand'signing'inidp_data['x509certMulti']andidp_data['x509certMulti']['signing']:
+ multicerts=idp_data['x509certMulti']['signing']
+
+ # If find a Signature on the Response, validates it checking the original response
+ ifhas_signed_responseandnotOneLogin_Saml2_Utils.validate_sign(self.document,cert,fingerprint,fingerprintalg,xpath=OneLogin_Saml2_Utils.RESPONSE_SIGNATURE_XPATH,multicerts=multicerts,raise_exceptions=False):
+ raiseOneLogin_Saml2_ValidationError(
+ 'Signature validation failed. SAML Response rejected',
+ OneLogin_Saml2_ValidationError.INVALID_SIGNATURE
+ )
+
+ document_check_assertion=self.decrypted_documentifself.encryptedelseself.document
+ ifhas_signed_assertionandnotOneLogin_Saml2_Utils.validate_sign(document_check_assertion,cert,fingerprint,fingerprintalg,xpath=OneLogin_Saml2_Utils.ASSERTION_SIGNATURE_XPATH,multicerts=multicerts,raise_exceptions=False):
+ raiseOneLogin_Saml2_ValidationError(
+ 'Signature validation failed. SAML Response rejected',
+ OneLogin_Saml2_ValidationError.INVALID_SIGNATURE
+ )
+
+ returnTrue
+ exceptExceptionaserr:
+ self._error=str(err)
+ debug=self._settings.is_debug_active()
+ ifdebug:
+ print(err)
+ ifraise_exceptions:
+ raise
+ returnFalse
+
+
[docs]defcheck_status(self):
+"""
+ Check if the status of the response is success or not
+
+ :raises: Exception. If the status is not success
+ """
+ status=OneLogin_Saml2_Utils.get_status(self.document)
+ code=status.get('code',None)
+ ifcodeandcode!=OneLogin_Saml2_Constants.STATUS_SUCCESS:
+ splited_code=code.split(':')
+ printable_code=splited_code.pop()
+ status_exception_msg='The status code of the Response was not Success, was %s'%printable_code
+ status_msg=status.get('msg',None)
+ ifstatus_msg:
+ status_exception_msg+=' -> '+status_msg
+ raiseOneLogin_Saml2_ValidationError(
+ status_exception_msg,
+ OneLogin_Saml2_ValidationError.STATUS_CODE_IS_NOT_SUCCESS
+ )
+
+
[docs]defcheck_one_condition(self):
+"""
+ Checks that the samlp:Response/saml:Assertion/saml:Conditions element exists and is unique.
+ """
+ condition_nodes=self._query_assertion('/saml:Conditions')
+ iflen(condition_nodes)==1:
+ returnTrue
+ else:
+ returnFalse
+
+
[docs]defcheck_one_authnstatement(self):
+"""
+ Checks that the samlp:Response/saml:Assertion/saml:AuthnStatement element exists and is unique.
+ """
+ authnstatement_nodes=self._query_assertion('/saml:AuthnStatement')
+ iflen(authnstatement_nodes)==1:
+ returnTrue
+ else:
+ returnFalse
+
+
[docs]defget_audiences(self):
+"""
+ Gets the audiences
+
+ :returns: The valid audiences for the SAML Response
+ :rtype: list
+ """
+ audience_nodes=self._query_assertion('/saml:Conditions/saml:AudienceRestriction/saml:Audience')
+ return[OneLogin_Saml2_XML.element_text(node)fornodeinaudience_nodesifOneLogin_Saml2_XML.element_text(node)isnotNone]
+
+
[docs]defget_authn_contexts(self):
+"""
+ Gets the authentication contexts
+
+ :returns: The authentication classes for the SAML Response
+ :rtype: list
+ """
+ authn_context_nodes=self._query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef')
+ return[OneLogin_Saml2_XML.element_text(node)fornodeinauthn_context_nodes]
+
+
[docs]defget_in_response_to(self):
+"""
+ Gets the ID of the request which this response is in response to
+ :returns: ID of AuthNRequest this Response is in response to or None if it is not present
+ :rtype: str
+ """
+ returnself.document.get('InResponseTo')
+
+
[docs]defget_issuers(self):
+"""
+ Gets the issuers (from message and from assertion)
+
+ :returns: The issuers
+ :rtype: list
+ """
+ issuers=set()
+
+ message_issuer_nodes=OneLogin_Saml2_XML.query(self.document,'/samlp:Response/saml:Issuer')
+ iflen(message_issuer_nodes)>0:
+ iflen(message_issuer_nodes)==1:
+ issuer_value=OneLogin_Saml2_XML.element_text(message_issuer_nodes[0])
+ ifissuer_value:
+ issuers.add(issuer_value)
+ else:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Issuer of the Response is multiple.',
+ OneLogin_Saml2_ValidationError.ISSUER_MULTIPLE_IN_RESPONSE
+ )
+
+ assertion_issuer_nodes=self._query_assertion('/saml:Issuer')
+ iflen(assertion_issuer_nodes)==1:
+ issuer_value=OneLogin_Saml2_XML.element_text(assertion_issuer_nodes[0])
+ ifissuer_value:
+ issuers.add(issuer_value)
+ else:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Issuer of the Assertion not found or multiple.',
+ OneLogin_Saml2_ValidationError.ISSUER_NOT_FOUND_IN_ASSERTION
+ )
+
+ returnlist(set(issuers))
+
+
[docs]defget_nameid_data(self):
+"""
+ Gets the NameID Data provided by the SAML Response from the IdP
+
+ :returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
+ :rtype: dict
+ """
+ nameid=None
+ nameid_data={}
+
+ encrypted_id_data_nodes=self._query_assertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData')
+ ifencrypted_id_data_nodes:
+ encrypted_data=encrypted_id_data_nodes[0]
+ key=self._settings.get_sp_key()
+ nameid=OneLogin_Saml2_Utils.decrypt_element(encrypted_data,key)
+ else:
+ nameid_nodes=self._query_assertion('/saml:Subject/saml:NameID')
+ ifnameid_nodes:
+ nameid=nameid_nodes[0]
+
+ is_strict=self._settings.is_strict()
+ want_nameid=self._settings.get_security_data().get('wantNameId',True)
+ ifnameidisNone:
+ ifis_strictandwant_nameid:
+ raiseOneLogin_Saml2_ValidationError(
+ 'NameID not found in the assertion of the Response',
+ OneLogin_Saml2_ValidationError.NO_NAMEID
+ )
+ else:
+ ifis_strictandwant_nameidandnotOneLogin_Saml2_XML.element_text(nameid):
+ raiseOneLogin_Saml2_ValidationError(
+ 'An empty NameID value found',
+ OneLogin_Saml2_ValidationError.EMPTY_NAMEID
+ )
+
+ nameid_data={'Value':OneLogin_Saml2_XML.element_text(nameid)}
+ forattrin['Format','SPNameQualifier','NameQualifier']:
+ value=nameid.get(attr,None)
+ ifvalue:
+ ifis_strictandattr=='SPNameQualifier':
+ sp_data=self._settings.get_sp_data()
+ sp_entity_id=sp_data.get('entityId','')
+ ifsp_entity_id!=value:
+ raiseOneLogin_Saml2_ValidationError(
+ 'The SPNameQualifier value mistmatch the SP entityID value.',
+ OneLogin_Saml2_ValidationError.SP_NAME_QUALIFIER_NAME_MISMATCH
+ )
+
+ nameid_data[attr]=value
+ returnnameid_data
+
+
[docs]defget_nameid(self):
+"""
+ Gets the NameID provided by the SAML Response from the IdP
+
+ :returns: NameID (value)
+ :rtype: string|None
+ """
+ nameid_value=None
+ nameid_data=self.get_nameid_data()
+ ifnameid_dataand'Value'innameid_data.keys():
+ nameid_value=nameid_data['Value']
+ returnnameid_value
+
+
[docs]defget_nameid_format(self):
+"""
+ Gets the NameID Format provided by the SAML Response from the IdP
+
+ :returns: NameID Format
+ :rtype: string|None
+ """
+ nameid_format=None
+ nameid_data=self.get_nameid_data()
+ ifnameid_dataand'Format'innameid_data.keys():
+ nameid_format=nameid_data['Format']
+ returnnameid_format
+
+
[docs]defget_nameid_nq(self):
+"""
+ Gets the NameID NameQualifier provided by the SAML Response from the IdP
+
+ :returns: NameID NameQualifier
+ :rtype: string|None
+ """
+ nameid_nq=None
+ nameid_data=self.get_nameid_data()
+ ifnameid_dataand'NameQualifier'innameid_data.keys():
+ nameid_nq=nameid_data['NameQualifier']
+ returnnameid_nq
+
+
[docs]defget_nameid_spnq(self):
+"""
+ Gets the NameID SP NameQualifier provided by the SAML response from the IdP.
+
+ :returns: NameID SP NameQualifier
+ :rtype: string|None
+ """
+ nameid_spnq=None
+ nameid_data=self.get_nameid_data()
+ ifnameid_dataand'SPNameQualifier'innameid_data.keys():
+ nameid_spnq=nameid_data['SPNameQualifier']
+ returnnameid_spnq
+
+
[docs]defget_session_not_on_or_after(self):
+"""
+ Gets the SessionNotOnOrAfter from the AuthnStatement
+ Could be used to set the local session expiration
+
+ :returns: The SessionNotOnOrAfter value
+ :rtype: time|None
+ """
+ not_on_or_after=None
+ authn_statement_nodes=self._query_assertion('/saml:AuthnStatement[@SessionNotOnOrAfter]')
+ ifauthn_statement_nodes:
+ not_on_or_after=OneLogin_Saml2_Utils.parse_SAML_to_time(authn_statement_nodes[0].get('SessionNotOnOrAfter'))
+ returnnot_on_or_after
+
+
[docs]defget_assertion_not_on_or_after(self):
+"""
+ Returns the NotOnOrAfter value of the valid SubjectConfirmationData node if any
+ """
+ returnself.valid_scd_not_on_or_after
+
+
[docs]defget_session_index(self):
+"""
+ Gets the SessionIndex from the AuthnStatement
+ Could be used to be stored in the local session in order
+ to be used in a future Logout Request that the SP could
+ send to the SP, to set what specific session must be deleted
+
+ :returns: The SessionIndex value
+ :rtype: string|None
+ """
+ session_index=None
+ authn_statement_nodes=self._query_assertion('/saml:AuthnStatement[@SessionIndex]')
+ ifauthn_statement_nodes:
+ session_index=authn_statement_nodes[0].get('SessionIndex')
+ returnsession_index
+
+
[docs]defget_attributes(self):
+"""
+ Gets the Attributes from the AttributeStatement element.
+ EncryptedAttributes are not supported
+ """
+ returnself._get_attributes('Name')
+
+
[docs]defget_friendlyname_attributes(self):
+"""
+ Gets the Attributes from the AttributeStatement element indexed by FiendlyName.
+ EncryptedAttributes are not supported
+ """
+ returnself._get_attributes('FriendlyName')
[docs]defvalidate_num_assertions(self):
+"""
+ Verifies that the document only contains a single Assertion (encrypted or not)
+
+ :returns: True if only 1 assertion encrypted or not
+ :rtype: bool
+ """
+ encrypted_assertion_nodes=OneLogin_Saml2_XML.query(self.document,'//saml:EncryptedAssertion')
+ assertion_nodes=OneLogin_Saml2_XML.query(self.document,'//saml:Assertion')
+
+ valid=len(encrypted_assertion_nodes)+len(assertion_nodes)==1
+
+ if(self.encrypted):
+ assertion_nodes=OneLogin_Saml2_XML.query(self.decrypted_document,'//saml:Assertion')
+ valid=validandlen(assertion_nodes)==1
+
+ returnvalid
+
+
[docs]defprocess_signed_elements(self):
+"""
+ Verifies the signature nodes:
+ - Checks that are Response or Assertion
+ - Check that IDs and reference URI are unique and consistent.
+
+ :returns: The signed elements tag names
+ :rtype: list
+ """
+ sign_nodes=self._query('//ds:Signature')
+
+ signed_elements=[]
+ verified_seis=[]
+ verified_ids=[]
+ response_tag='{%s}Response'%OneLogin_Saml2_Constants.NS_SAMLP
+ assertion_tag='{%s}Assertion'%OneLogin_Saml2_Constants.NS_SAML
+
+ security=self._settings.get_security_data()
+ reject_deprecated_alg=security.get('rejectDeprecatedAlgorithm',False)
+
+ forsign_nodeinsign_nodes:
+ signed_element=sign_node.getparent().tag
+ ifsigned_element!=response_tagandsigned_element!=assertion_tag:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Invalid Signature Element %s SAML Response rejected'%signed_element,
+ OneLogin_Saml2_ValidationError.WRONG_SIGNED_ELEMENT
+ )
+
+ ifnotsign_node.getparent().get('ID'):
+ raiseOneLogin_Saml2_ValidationError(
+ 'Signed Element must contain an ID. SAML Response rejected',
+ OneLogin_Saml2_ValidationError.ID_NOT_FOUND_IN_SIGNED_ELEMENT
+ )
+
+ id_value=sign_node.getparent().get('ID')
+ ifid_valueinverified_ids:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Duplicated ID. SAML Response rejected',
+ OneLogin_Saml2_ValidationError.DUPLICATED_ID_IN_SIGNED_ELEMENTS
+ )
+ verified_ids.append(id_value)
+
+ # Check that reference URI matches the parent ID and no duplicate References or IDs
+ ref=OneLogin_Saml2_XML.query(sign_node,'.//ds:Reference')
+ ifref:
+ ref=ref[0]
+ ifref.get('URI'):
+ sei=ref.get('URI')[1:]
+
+ ifsei!=id_value:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Found an invalid Signed Element. SAML Response rejected',
+ OneLogin_Saml2_ValidationError.INVALID_SIGNED_ELEMENT
+ )
+
+ ifseiinverified_seis:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Duplicated Reference URI. SAML Response rejected',
+ OneLogin_Saml2_ValidationError.DUPLICATED_REFERENCE_IN_SIGNED_ELEMENTS
+ )
+ verified_seis.append(sei)
+
+ # Check the signature and digest algorithm
+ ifreject_deprecated_alg:
+ sig_method_node=OneLogin_Saml2_XML.query(sign_node,'.//ds:SignatureMethod')
+ ifsig_method_node:
+ sig_method=sig_method_node[0].get("Algorithm")
+ ifsig_methodinOneLogin_Saml2_Constants.DEPRECATED_ALGORITHMS:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Deprecated signature algorithm found: %s'%sig_method,
+ OneLogin_Saml2_ValidationError.DEPRECATED_SIGNATURE_METHOD
+ )
+
+ dig_method_node=OneLogin_Saml2_XML.query(sign_node,'.//ds:DigestMethod')
+ ifdig_method_node:
+ dig_method=dig_method_node[0].get("Algorithm")
+ ifdig_methodinOneLogin_Saml2_Constants.DEPRECATED_ALGORITHMS:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Deprecated digest algorithm found: %s'%dig_method,
+ OneLogin_Saml2_ValidationError.DEPRECATED_DIGEST_METHOD
+ )
+
+ signed_elements.append(signed_element)
+
+ ifsigned_elements:
+ ifnotself.validate_signed_elements(signed_elements,raise_exceptions=True):
+ raiseOneLogin_Saml2_ValidationError(
+ 'Found an unexpected Signature Element. SAML Response rejected',
+ OneLogin_Saml2_ValidationError.UNEXPECTED_SIGNED_ELEMENTS
+ )
+ returnsigned_elements
+
+
[docs]@return_false_on_exception
+ defvalidate_signed_elements(self,signed_elements):
+"""
+ Verifies that the document has the expected signed nodes.
+
+ :param signed_elements: The signed elements to be checked
+ :type signed_elements: list
+ :param raise_exceptions: Whether to return false on failure or raise an exception
+ :type raise_exceptions: Boolean
+ """
+ iflen(signed_elements)>2:
+ returnFalse
+
+ response_tag='{%s}Response'%OneLogin_Saml2_Constants.NS_SAMLP
+ assertion_tag='{%s}Assertion'%OneLogin_Saml2_Constants.NS_SAML
+
+ if(response_taginsigned_elementsandsigned_elements.count(response_tag)>1)or \
+ (assertion_taginsigned_elementsandsigned_elements.count(assertion_tag)>1)or \
+ (response_tagnotinsigned_elementsandassertion_tagnotinsigned_elements):
+ returnFalse
+
+ # Check that the signed elements found here, are the ones that will be verified
+ # by OneLogin_Saml2_Utils.validate_sign
+ ifresponse_taginsigned_elements:
+ expected_signature_nodes=OneLogin_Saml2_XML.query(self.document,OneLogin_Saml2_Utils.RESPONSE_SIGNATURE_XPATH)
+ iflen(expected_signature_nodes)!=1:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Unexpected number of Response signatures found. SAML Response rejected.',
+ OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES_IN_RESPONSE
+ )
+
+ ifassertion_taginsigned_elements:
+ expected_signature_nodes=self._query(OneLogin_Saml2_Utils.ASSERTION_SIGNATURE_XPATH)
+ iflen(expected_signature_nodes)!=1:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Unexpected number of Assertion signatures found. SAML Response rejected.',
+ OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES_IN_ASSERTION
+ )
+
+ returnTrue
+
+
[docs]@return_false_on_exception
+ defvalidate_timestamps(self):
+"""
+ Verifies that the document is valid according to Conditions Element
+
+ :returns: True if the condition is valid, False otherwise
+ :rtype: bool
+ """
+ conditions_nodes=self._query_assertion('/saml:Conditions')
+
+ forconditions_nodeinconditions_nodes:
+ nb_attr=conditions_node.get('NotBefore')
+ nooa_attr=conditions_node.get('NotOnOrAfter')
+ ifnb_attrandOneLogin_Saml2_Utils.parse_SAML_to_time(nb_attr)>OneLogin_Saml2_Utils.now()+OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Could not validate timestamp: not yet valid. Check system clock.',
+ OneLogin_Saml2_ValidationError.ASSERTION_TOO_EARLY
+ )
+ ifnooa_attrandOneLogin_Saml2_Utils.parse_SAML_to_time(nooa_attr)+OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT<=OneLogin_Saml2_Utils.now():
+ raiseOneLogin_Saml2_ValidationError(
+ 'Could not validate timestamp: expired. Check system clock.',
+ OneLogin_Saml2_ValidationError.ASSERTION_EXPIRED
+ )
+ returnTrue
+
+ def_query_assertion(self,xpath_expr):
+"""
+ Extracts nodes that match the query from the Assertion
+
+ :param xpath_expr: Xpath Expresion
+ :type xpath_expr: String
+
+ :returns: The queried nodes
+ :rtype: list
+ """
+
+ assertion_expr='/saml:Assertion'
+ signature_expr='/ds:Signature/ds:SignedInfo/ds:Reference'
+ signed_assertion_query='/samlp:Response'+assertion_expr+signature_expr
+ assertion_reference_nodes=self._query(signed_assertion_query)
+ tagid=None
+
+ ifnotassertion_reference_nodes:
+ # Check if the message is signed
+ signed_message_query='/samlp:Response'+signature_expr
+ message_reference_nodes=self._query(signed_message_query)
+ ifmessage_reference_nodes:
+ message_id=message_reference_nodes[0].get('URI')
+ final_query="/samlp:Response[@ID=$tagid]/"
+ tagid=message_id[1:]
+ else:
+ final_query="/samlp:Response"
+ final_query+=assertion_expr
+ else:
+ assertion_id=assertion_reference_nodes[0].get('URI')
+ final_query='/samlp:Response'+assertion_expr+"[@ID=$tagid]"
+ tagid=assertion_id[1:]
+ final_query+=xpath_expr
+ returnself._query(final_query,tagid)
+
+ def_query(self,query,tagid=None):
+"""
+ Extracts nodes that match the query from the Response
+
+ :param query: Xpath Expresion
+ :type query: String
+
+ :param tagid: Tag ID
+ :type query: String
+
+ :returns: The queried nodes
+ :rtype: list
+ """
+ ifself.encrypted:
+ document=self.decrypted_document
+ else:
+ document=self.document
+ returnOneLogin_Saml2_XML.query(document,query,None,tagid)
+
+ def_decrypt_assertion(self,xml):
+"""
+ Decrypts the Assertion
+
+ :raises: Exception if no private key available
+ :param xml: Encrypted Assertion
+ :type xml: Element
+ :returns: Decrypted Assertion
+ :rtype: Element
+ """
+ key=self._settings.get_sp_key()
+ debug=self._settings.is_debug_active()
+
+ ifnotkey:
+ raiseOneLogin_Saml2_Error(
+ 'No private key available to decrypt the assertion, check settings',
+ OneLogin_Saml2_Error.PRIVATE_KEY_NOT_FOUND
+ )
+
+ encrypted_assertion_nodes=OneLogin_Saml2_XML.query(xml,'/samlp:Response/saml:EncryptedAssertion')
+ ifencrypted_assertion_nodes:
+ encrypted_data_nodes=OneLogin_Saml2_XML.query(encrypted_assertion_nodes[0],'//saml:EncryptedAssertion/xenc:EncryptedData')
+ ifencrypted_data_nodes:
+ keyinfo=OneLogin_Saml2_XML.query(encrypted_assertion_nodes[0],'//saml:EncryptedAssertion/xenc:EncryptedData/ds:KeyInfo')
+ ifnotkeyinfo:
+ raiseOneLogin_Saml2_ValidationError(
+ 'No KeyInfo present, invalid Assertion',
+ OneLogin_Saml2_ValidationError.KEYINFO_NOT_FOUND_IN_ENCRYPTED_DATA
+ )
+ keyinfo=keyinfo[0]
+ children=keyinfo.getchildren()
+ ifnotchildren:
+ raiseOneLogin_Saml2_ValidationError(
+ 'KeyInfo has no children nodes, invalid Assertion',
+ OneLogin_Saml2_ValidationError.CHILDREN_NODE_NOT_FOUND_IN_KEYINFO
+ )
+ forchildinchildren:
+ if'RetrievalMethod'inchild.tag:
+ ifchild.attrib['Type']!='http://www.w3.org/2001/04/xmlenc#EncryptedKey':
+ raiseOneLogin_Saml2_ValidationError(
+ 'Unsupported Retrieval Method found',
+ OneLogin_Saml2_ValidationError.UNSUPPORTED_RETRIEVAL_METHOD
+ )
+ uri=child.attrib['URI']
+ ifnoturi.startswith('#'):
+ break
+ uri=uri.split('#')[1]
+ encrypted_key=OneLogin_Saml2_XML.query(encrypted_assertion_nodes[0],'./xenc:EncryptedKey[@Id=$tagid]',None,uri)
+ ifencrypted_key:
+ keyinfo.append(encrypted_key[0])
+
+ encrypted_data=encrypted_data_nodes[0]
+ decrypted=OneLogin_Saml2_Utils.decrypt_element(encrypted_data,key,debug=debug,inplace=True)
+ xml.replace(encrypted_assertion_nodes[0],decrypted)
+ returnxml
+
+
[docs]defget_error(self):
+"""
+ After executing a validation process, if it fails this method returns the cause
+ """
+ returnself._error
[docs]defget_id(self):
+"""
+ :returns: the ID of the response
+ :rtype: string
+ """
+ returnself.document.get('ID',None)
+
+
[docs]defget_assertion_id(self):
+"""
+ :returns: the ID of the assertion in the response
+ :rtype: string
+ """
+ ifnotself.validate_num_assertions():
+ raiseOneLogin_Saml2_ValidationError(
+ 'SAML Response must contain 1 assertion',
+ OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_ASSERTIONS
+ )
+ returnself._query_assertion('')[0].get('ID',None)
+
+
[docs]defget_assertion_issue_instant(self):
+"""
+ :returns: the IssueInstant of the assertion in the response
+ :rtype: unix/posix timestamp|None
+ """
+ ifnotself.validate_num_assertions():
+ raiseOneLogin_Saml2_ValidationError(
+ 'SAML Response must contain 1 assertion',
+ OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_ASSERTIONS
+ )
+ issue_instant=self._query_assertion('')[0].get('IssueInstant',None)
+ returnOneLogin_Saml2_Utils.parse_SAML_to_time(issue_instant)
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/saml2/_modules/onelogin/saml2/settings.html b/docs/saml2/_modules/onelogin/saml2/settings.html
new file mode 100644
index 00000000..70185c17
--- /dev/null
+++ b/docs/saml2/_modules/onelogin/saml2/settings.html
@@ -0,0 +1,961 @@
+
+
+
+
+
+ onelogin.saml2.settings — SAML Python2/3 Toolkit 1 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
[docs]defcheck_sp_certs(self):
+"""
+ Checks if the x509 certs of the SP exists and are valid.
+ :returns: If the x509 certs of the SP exists and are valid
+ :rtype: boolean
+ """
+ key=self.get_sp_key()
+ cert=self.get_sp_cert()
+ returnkeyisnotNoneandcertisnotNone
+
+
[docs]defget_idp_sso_url(self):
+"""
+ Gets the IdP SSO URL.
+
+ :returns: An URL, the SSO endpoint of the IdP
+ :rtype: string
+ """
+ idp_data=self.get_idp_data()
+ returnidp_data['singleSignOnService']['url']
+
+
[docs]defget_idp_slo_url(self):
+"""
+ Gets the IdP SLO URL.
+
+ :returns: An URL, the SLO endpoint of the IdP
+ :rtype: string
+ """
+ idp_data=self.get_idp_data()
+ if'url'inidp_data['singleLogoutService']:
+ returnidp_data['singleLogoutService']['url']
+
+
[docs]defget_idp_slo_response_url(self):
+"""
+ Gets the IdP SLO return URL for IdP-initiated logout.
+
+ :returns: an URL, the SLO return endpoint of the IdP
+ :rtype: string
+ """
+ idp_data=self.get_idp_data()
+ if'url'inidp_data['singleLogoutService']:
+ returnidp_data['singleLogoutService'].get('responseUrl',self.get_idp_slo_url())
+
+
[docs]defget_sp_key(self):
+"""
+ Returns the x509 private key of the SP.
+ :returns: SP private key
+ :rtype: string or None
+ """
+ key=self._sp.get('privateKey')
+ key_file_name=self._paths['cert']+'sp.key'
+
+ ifnotkeyandexists(key_file_name):
+ withopen(key_file_name)asf:
+ key=f.read()
+
+ returnkeyorNone
+
+
[docs]defget_sp_cert(self):
+"""
+ Returns the x509 public cert of the SP.
+ :returns: SP public cert
+ :rtype: string or None
+ """
+ cert=self._sp.get('x509cert')
+ cert_file_name=self._paths['cert']+'sp.crt'
+
+ ifnotcertandexists(cert_file_name):
+ withopen(cert_file_name)asf:
+ cert=f.read()
+
+ returncertorNone
+
+
[docs]defget_sp_cert_new(self):
+"""
+ Returns the x509 public of the SP planned
+ to be used soon instead the other public cert
+ :returns: SP public cert new
+ :rtype: string or None
+ """
+ cert=self._sp.get('x509certNew')
+ cert_file_name=self._paths['cert']+'sp_new.crt'
+
+ ifnotcertandexists(cert_file_name):
+ withopen(cert_file_name)asf:
+ cert=f.read()
+
+ returncertorNone
+
+
[docs]defget_idp_cert(self):
+"""
+ Returns the x509 public cert of the IdP.
+ :returns: IdP public cert
+ :rtype: string
+ """
+ cert=self._idp.get('x509cert')
+ cert_file_name=self.get_cert_path()+'idp.crt'
+ ifnotcertandexists(cert_file_name):
+ withopen(cert_file_name)asf:
+ cert=f.read()
+ returncertorNone
+
+
[docs]defget_idp_data(self):
+"""
+ Gets the IdP data.
+
+ :returns: IdP info
+ :rtype: dict
+ """
+ returnself._idp
+
+
[docs]defget_sp_data(self):
+"""
+ Gets the SP data.
+
+ :returns: SP info
+ :rtype: dict
+ """
+ returnself._sp
[docs]defget_errors(self):
+"""
+ Returns an array with the errors, the array is empty when the settings is ok.
+
+ :returns: Errors
+ :rtype: list
+ """
+ returnself._errors
[docs]defreturn_false_on_exception(func):
+"""
+ Decorator. When applied to a function, it will, by default, suppress any exceptions
+ raised by that function and return False. It may be overridden by passing a
+ "raise_exceptions" keyword argument when calling the wrapped function.
+ """
+ @wraps(func)
+ defexceptfalse(*args,**kwargs):
+ ifnotkwargs.pop('raise_exceptions',False):
+ try:
+ returnfunc(*args,**kwargs)
+ exceptException:
+ returnFalse
+ else:
+ returnfunc(*args,**kwargs)
+ returnexceptfalse
+
+
+
[docs]classOneLogin_Saml2_Utils(object):
+"""
+
+ Auxiliary class that contains several utility methods to parse time,
+ urls, add sign, encrypt, decrypt, sign validation, handle xml ...
+
+ """
+
+ RESPONSE_SIGNATURE_XPATH='/samlp:Response/ds:Signature'
+ ASSERTION_SIGNATURE_XPATH='/samlp:Response/saml:Assertion/ds:Signature'
+
+ TIME_FORMAT="%Y-%m-%dT%H:%M:%SZ"
+ TIME_FORMAT_2="%Y-%m-%dT%H:%M:%S.%fZ"
+ TIME_FORMAT_WITH_FRAGMENT=re.compile(r'^(\d{4,4}-\d{2,2}-\d{2,2}T\d{2,2}:\d{2,2}:\d{2,2})(\.\d*)?Z?$')
+
+
[docs]@staticmethod
+ defescape_url(url,lowercase_urlencoding=False):
+"""
+ escape the non-safe symbols in url
+ The encoding used by ADFS 3.0 is not compatible with
+ python's quote_plus (ADFS produces lower case hex numbers and quote_plus produces
+ upper case hex numbers)
+ :param url: the url to escape
+ :type url: str
+
+ :param lowercase_urlencoding: lowercase or no
+ :type lowercase_urlencoding: boolean
+
+ :return: the escaped url
+ :rtype str
+ """
+ encoded=quote_plus(url)
+ returnre.sub(r"%[A-F0-9]{2}",lambdam:m.group(0).lower(),encoded)iflowercase_urlencodingelseencoded
[docs]@staticmethod
+ defdecode_base64_and_inflate(value,ignore_zip=False):
+"""
+ base64 decodes and then inflates according to RFC1951
+ :param value: a deflated and encoded string
+ :type value: string
+ :param ignore_zip: ignore zip errors
+ :returns: the string after decoding and inflating
+ :rtype: string
+ """
+ encoded=OneLogin_Saml2_Utils.b64decode(value)
+ try:
+ returnzlib.decompress(encoded,-15)
+ exceptzlib.error:
+ ifnotignore_zip:
+ raise
+ returnencoded
+
+
[docs]@staticmethod
+ defdeflate_and_base64_encode(value):
+"""
+ Deflates and then base64 encodes a string
+ :param value: The string to deflate and encode
+ :type value: string
+ :returns: The deflated and encoded string
+ :rtype: string
+ """
+ returnOneLogin_Saml2_Utils.b64encode(zlib.compress(compat.to_bytes(value))[2:-4])
+
+
[docs]@staticmethod
+ defformat_cert(cert,heads=True):
+"""
+ Returns a x509 cert (adding header & footer if required).
+
+ :param cert: A x509 unformatted cert
+ :type: string
+
+ :param heads: True if we want to include head and footer
+ :type: boolean
+
+ :returns: Formatted cert
+ :rtype: string
+ """
+ x509_cert=cert.replace('\x0D','')
+ x509_cert=x509_cert.replace('\r','')
+ x509_cert=x509_cert.replace('\n','')
+ iflen(x509_cert)>0:
+ x509_cert=x509_cert.replace('-----BEGIN CERTIFICATE-----','')
+ x509_cert=x509_cert.replace('-----END CERTIFICATE-----','')
+ x509_cert=x509_cert.replace(' ','')
+
+ ifheads:
+ x509_cert="-----BEGIN CERTIFICATE-----\n"+"\n".join(wrap(x509_cert,64))+"\n-----END CERTIFICATE-----\n"
+
+ returnx509_cert
[docs]@staticmethod
+ defredirect(url,parameters={},request_data={}):
+"""
+ Executes a redirection to the provided url (or return the target url).
+
+ :param url: The target url
+ :type: string
+
+ :param parameters: Extra parameters to be passed as part of the url
+ :type: dict
+
+ :param request_data: The request as a dict
+ :type: dict
+
+ :returns: Url
+ :rtype: string
+ """
+ assertisinstance(url,compat.str_type)
+ assertisinstance(parameters,dict)
+
+ ifurl.startswith('/'):
+ url='%s%s'%(OneLogin_Saml2_Utils.get_self_url_host(request_data),url)
+
+ # Verify that the URL is to a http or https site.
+ ifre.search('^https?://',url,flags=re.IGNORECASE)isNone:
+ raiseOneLogin_Saml2_Error(
+ 'Redirect to invalid URL: '+url,
+ OneLogin_Saml2_Error.REDIRECT_INVALID_URL
+ )
+
+ # Add encoded parameters
+ ifurl.find('?')<0:
+ param_prefix='?'
+ else:
+ param_prefix='&'
+
+ forname,valueinparameters.items():
+
+ ifvalueisNone:
+ param=OneLogin_Saml2_Utils.escape_url(name)
+ elifisinstance(value,list):
+ param=''
+ forvalinvalue:
+ param+=OneLogin_Saml2_Utils.escape_url(name)+'[]='+OneLogin_Saml2_Utils.escape_url(val)+'&'
+ iflen(param)>0:
+ param=param[0:-1]
+ else:
+ param=OneLogin_Saml2_Utils.escape_url(name)+'='+OneLogin_Saml2_Utils.escape_url(value)
+
+ ifparam:
+ url+=param_prefix+param
+ param_prefix='&'
+
+ returnurl
+
+
[docs]@staticmethod
+ defget_self_url_host(request_data):
+"""
+ Returns the protocol + the current host + the port (if different than
+ common ports).
+
+ :param request_data: The request as a dict
+ :type: dict
+
+ :return: Url
+ :rtype: string
+ """
+ current_host=OneLogin_Saml2_Utils.get_self_host(request_data)
+ protocol='https'ifOneLogin_Saml2_Utils.is_https(request_data)else'http'
+
+ ifrequest_data.get('server_port')isnotNone:
+ warnings.warn(
+ 'The server_port key in request data is deprecated. '
+ 'The http_host key should include a port, if required.',
+ category=DeprecationWarning,
+ )
+ port_suffix=':%s'%request_data['server_port']
+ ifnotcurrent_host.endswith(port_suffix):
+ ifnot((protocol=='https'andport_suffix==':443')or(protocol=='http'andport_suffix==':80')):
+ current_host+=port_suffix
+
+ return'%s://%s'%(protocol,current_host)
+
+
[docs]@staticmethod
+ defget_self_host(request_data):
+"""
+ Returns the current host (which may include a port number part).
+
+ :param request_data: The request as a dict
+ :type: dict
+
+ :return: The current host
+ :rtype: string
+ """
+ if'http_host'inrequest_data:
+ returnrequest_data['http_host']
+ elif'server_name'inrequest_data:
+ warnings.warn("The server_name key in request data is undocumented & deprecated.",category=DeprecationWarning)
+ returnrequest_data['server_name']
+ raiseException('No hostname defined')
+
+
[docs]@staticmethod
+ defis_https(request_data):
+"""
+ Checks if https or http.
+
+ :param request_data: The request as a dict
+ :type: dict
+
+ :return: False if https is not active
+ :rtype: boolean
+ """
+ is_https='https'inrequest_dataandrequest_data['https']!='off'
+ # TODO: this use of server_port should be removed too
+ is_https=is_httpsor('server_port'inrequest_dataandstr(request_data['server_port'])=='443')
+ returnis_https
+
+
[docs]@staticmethod
+ defget_self_url_no_query(request_data):
+"""
+ Returns the URL of the current host + current view.
+
+ :param request_data: The request as a dict
+ :type: dict
+
+ :return: The url of current host + current view
+ :rtype: string
+ """
+ self_url_host=OneLogin_Saml2_Utils.get_self_url_host(request_data)
+ script_name=request_data['script_name']
+ ifscript_name:
+ ifscript_name[0]!='/':
+ script_name='/'+script_name
+ else:
+ script_name=''
+ self_url_no_query=self_url_host+script_name
+ if'path_info'inrequest_data:
+ self_url_no_query+=request_data['path_info']
+
+ returnself_url_no_query
+
+
[docs]@staticmethod
+ defget_self_routed_url_no_query(request_data):
+"""
+ Returns the routed URL of the current host + current view.
+
+ :param request_data: The request as a dict
+ :type: dict
+
+ :return: The url of current host + current view
+ :rtype: string
+ """
+ self_url_host=OneLogin_Saml2_Utils.get_self_url_host(request_data)
+ route=''
+ if'request_uri'inrequest_dataandrequest_data['request_uri']:
+ route=request_data['request_uri']
+ if'query_string'inrequest_dataandrequest_data['query_string']:
+ route=route.replace(request_data['query_string'],'')
+
+ returnself_url_host+route
+
+
[docs]@staticmethod
+ defget_self_url(request_data):
+"""
+ Returns the URL of the current host + current view + query.
+
+ :param request_data: The request as a dict
+ :type: dict
+
+ :return: The url of current host + current view + query
+ :rtype: string
+ """
+ self_url_host=OneLogin_Saml2_Utils.get_self_url_host(request_data)
+
+ request_uri=''
+ if'request_uri'inrequest_data:
+ request_uri=request_data['request_uri']
+ ifnotrequest_uri.startswith('/'):
+ match=re.search('^https?://[^/]*(/.*)',request_uri)
+ ifmatchisnotNone:
+ request_uri=match.groups()[0]
+
+ returnself_url_host+request_uri
+
+
[docs]@staticmethod
+ defgenerate_unique_id():
+"""
+ Generates an unique string (used for example as ID for assertions).
+
+ :return: A unique string
+ :rtype: string
+ """
+ return'ONELOGIN_%s'%sha1(compat.to_bytes(uuid4().hex)).hexdigest()
+
+
[docs]@staticmethod
+ defparse_time_to_SAML(time):
+r"""
+ Converts a UNIX timestamp to SAML2 timestamp on the form
+ yyyy-mm-ddThh:mm:ss(\.s+)?Z.
+
+ :param time: The time we should convert (DateTime).
+ :type: string
+
+ :return: SAML2 timestamp.
+ :rtype: string
+ """
+ data=datetime.utcfromtimestamp(float(time))
+ returndata.strftime(OneLogin_Saml2_Utils.TIME_FORMAT)
+
+
[docs]@staticmethod
+ defparse_SAML_to_time(timestr):
+r"""
+ Converts a SAML2 timestamp on the form yyyy-mm-ddThh:mm:ss(\.s+)?Z
+ to a UNIX timestamp. The sub-second part is ignored.
+
+ :param timestr: The time we should convert (SAML Timestamp).
+ :type: string
+
+ :return: Converted to a unix timestamp.
+ :rtype: int
+ """
+ try:
+ data=datetime.strptime(timestr,OneLogin_Saml2_Utils.TIME_FORMAT)
+ exceptValueError:
+ try:
+ data=datetime.strptime(timestr,OneLogin_Saml2_Utils.TIME_FORMAT_2)
+ exceptValueError:
+ elem=OneLogin_Saml2_Utils.TIME_FORMAT_WITH_FRAGMENT.match(timestr)
+ ifnotelem:
+ raiseException("time data %s does not match format %s"%(timestr,r'yyyy-mm-ddThh:mm:ss(\.s+)?Z'))
+ data=datetime.strptime(elem.groups()[0]+"Z",OneLogin_Saml2_Utils.TIME_FORMAT)
+
+ returncalendar.timegm(data.utctimetuple())
+
+
[docs]@staticmethod
+ defnow():
+"""
+ :return: unix timestamp of actual time.
+ :rtype: int
+ """
+ returncalendar.timegm(datetime.utcnow().utctimetuple())
+
+
[docs]@staticmethod
+ defparse_duration(duration,timestamp=None):
+"""
+ Interprets a ISO8601 duration value relative to a given timestamp.
+
+ :param duration: The duration, as a string.
+ :type: string
+
+ :param timestamp: The unix timestamp we should apply the duration to.
+ Optional, default to the current time.
+ :type: string
+
+ :return: The new timestamp, after the duration is applied.
+ :rtype: int
+ """
+ assertisinstance(duration,compat.str_type)
+ asserttimestampisNoneorisinstance(timestamp,int)
+
+ timedelta=duration_parser(duration)
+ iftimestampisNone:
+ data=datetime.utcnow()+timedelta
+ else:
+ data=datetime.utcfromtimestamp(timestamp)+timedelta
+ returncalendar.timegm(data.utctimetuple())
+
+
[docs]@staticmethod
+ defget_expire_time(cache_duration=None,valid_until=None):
+"""
+ Compares 2 dates and returns the earliest.
+
+ :param cache_duration: The duration, as a string.
+ :type: string
+
+ :param valid_until: The valid until date, as a string or as a timestamp
+ :type: string
+
+ :return: The expiration time.
+ :rtype: int
+ """
+ expire_time=None
+
+ ifcache_durationisnotNone:
+ expire_time=OneLogin_Saml2_Utils.parse_duration(cache_duration)
+
+ ifvalid_untilisnotNone:
+ ifisinstance(valid_until,int):
+ valid_until_time=valid_until
+ else:
+ valid_until_time=OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until)
+ ifexpire_timeisNoneorexpire_time>valid_until_time:
+ expire_time=valid_until_time
+
+ ifexpire_timeisnotNone:
+ return'%d'%expire_time
+ returnNone
+
+
[docs]@staticmethod
+ defdelete_local_session(callback=None):
+"""
+ Deletes the local session.
+ """
+
+ ifcallbackisnotNone:
+ callback()
+
+
[docs]@staticmethod
+ defcalculate_x509_fingerprint(x509_cert,alg='sha1'):
+"""
+ Calculates the fingerprint of a formatted x509cert.
+
+ :param x509_cert: x509 cert formatted
+ :type: string
+
+ :param alg: The algorithm to build the fingerprint
+ :type: string
+
+ :returns: fingerprint
+ :rtype: string
+ """
+ assertisinstance(x509_cert,compat.str_type)
+
+ lines=x509_cert.split('\n')
+ data=''
+ inData=False
+
+ forlineinlines:
+ # Remove '\r' from end of line if present.
+ line=line.rstrip()
+ ifnotinData:
+ ifline=='-----BEGIN CERTIFICATE-----':
+ inData=True
+ elifline=='-----BEGIN PUBLIC KEY-----'orline=='-----BEGIN RSA PRIVATE KEY-----':
+ # This isn't an X509 certificate.
+ returnNone
+ else:
+ ifline=='-----END CERTIFICATE-----':
+ break
+
+ # Append the current line to the certificate data.
+ data+=line
+
+ ifnotdata:
+ returnNone
+
+ decoded_data=base64.b64decode(compat.to_bytes(data))
+
+ ifalg=='sha512':
+ fingerprint=sha512(decoded_data)
+ elifalg=='sha384':
+ fingerprint=sha384(decoded_data)
+ elifalg=='sha256':
+ fingerprint=sha256(decoded_data)
+ else:
+ fingerprint=sha1(decoded_data)
+
+ returnfingerprint.hexdigest().lower()
[docs]@staticmethod
+ @return_false_on_exception
+ defvalidate_sign(xml,cert=None,fingerprint=None,fingerprintalg='sha1',validatecert=False,debug=False,xpath=None,multicerts=None):
+"""
+ Validates a signature (Message or Assertion).
+
+ :param xml: The element we should validate
+ :type: string | Document
+
+ :param cert: The public cert
+ :type: string
+
+ :param fingerprint: The fingerprint of the public cert
+ :type: string
+
+ :param fingerprintalg: The algorithm used to build the fingerprint
+ :type: string
+
+ :param validatecert: If true, will verify the signature and if the cert is valid.
+ :type: bool
+
+ :param debug: Activate the xmlsec debug
+ :type: bool
+
+ :param xpath: The xpath of the signed element
+ :type: string
+
+ :param multicerts: Multiple public certs
+ :type: list
+
+ :param raise_exceptions: Whether to return false on failure or raise an exception
+ :type raise_exceptions: Boolean
+ """
+ ifxmlisNoneorxml=='':
+ raiseException('Empty string supplied as input')
+
+ elem=OneLogin_Saml2_XML.to_etree(xml)
+ xmlsec.enable_debug_trace(debug)
+ xmlsec.tree.add_ids(elem,["ID"])
+
+ ifxpath:
+ signature_nodes=OneLogin_Saml2_XML.query(elem,xpath)
+ else:
+ signature_nodes=OneLogin_Saml2_XML.query(elem,OneLogin_Saml2_Utils.RESPONSE_SIGNATURE_XPATH)
+
+ iflen(signature_nodes)==0:
+ signature_nodes=OneLogin_Saml2_XML.query(elem,OneLogin_Saml2_Utils.ASSERTION_SIGNATURE_XPATH)
+
+ iflen(signature_nodes)==1:
+ signature_node=signature_nodes[0]
+
+ ifnotmulticerts:
+ returnOneLogin_Saml2_Utils.validate_node_sign(signature_node,elem,cert,fingerprint,fingerprintalg,validatecert,debug,raise_exceptions=True)
+ else:
+ # If multiple certs are provided, I may ignore cert and
+ # fingerprint provided by the method and just check the
+ # certs multicerts
+ fingerprint=fingerprintalg=None
+ forcertinmulticerts:
+ ifOneLogin_Saml2_Utils.validate_node_sign(signature_node,elem,cert,fingerprint,fingerprintalg,validatecert,False,raise_exceptions=False):
+ returnTrue
+ raiseOneLogin_Saml2_ValidationError(
+ 'Signature validation failed. SAML Response rejected.',
+ OneLogin_Saml2_ValidationError.INVALID_SIGNATURE
+ )
+ else:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Expected exactly one signature node; got {}.'.format(len(signature_nodes)),
+ OneLogin_Saml2_ValidationError.WRONG_NUMBER_OF_SIGNATURES
+ )
+
+
[docs]@staticmethod
+ @return_false_on_exception
+ defvalidate_metadata_sign(xml,cert=None,fingerprint=None,fingerprintalg='sha1',validatecert=False,debug=False):
+"""
+ Validates a signature of a EntityDescriptor.
+
+ :param xml: The element we should validate
+ :type: string | Document
+
+ :param cert: The public cert
+ :type: string
+
+ :param fingerprint: The fingerprint of the public cert
+ :type: string
+
+ :param fingerprintalg: The algorithm used to build the fingerprint
+ :type: string
+
+ :param validatecert: If true, will verify the signature and if the cert is valid.
+ :type: bool
+
+ :param debug: Activate the xmlsec debug
+ :type: bool
+
+ :param raise_exceptions: Whether to return false on failure or raise an exception
+ :type raise_exceptions: Boolean
+ """
+ ifxmlisNoneorxml=='':
+ raiseException('Empty string supplied as input')
+
+ elem=OneLogin_Saml2_XML.to_etree(xml)
+ xmlsec.enable_debug_trace(debug)
+ xmlsec.tree.add_ids(elem,["ID"])
+
+ signature_nodes=OneLogin_Saml2_XML.query(elem,'/md:EntitiesDescriptor/ds:Signature')
+
+ iflen(signature_nodes)==0:
+ signature_nodes+=OneLogin_Saml2_XML.query(elem,'/md:EntityDescriptor/ds:Signature')
+
+ iflen(signature_nodes)==0:
+ signature_nodes+=OneLogin_Saml2_XML.query(elem,'/md:EntityDescriptor/md:SPSSODescriptor/ds:Signature')
+ signature_nodes+=OneLogin_Saml2_XML.query(elem,'/md:EntityDescriptor/md:IDPSSODescriptor/ds:Signature')
+
+ iflen(signature_nodes)>0:
+ forsignature_nodeinsignature_nodes:
+ # Raises exception if invalid
+ OneLogin_Saml2_Utils.validate_node_sign(signature_node,elem,cert,fingerprint,fingerprintalg,validatecert,debug,raise_exceptions=True)
+ returnTrue
+ else:
+ raiseException('Could not validate metadata signature: No signature nodes found.')
+
+
[docs]@staticmethod
+ @return_false_on_exception
+ defvalidate_node_sign(signature_node,elem,cert=None,fingerprint=None,fingerprintalg='sha1',validatecert=False,debug=False):
+"""
+ Validates a signature node.
+
+ :param signature_node: The signature node
+ :type: Node
+
+ :param xml: The element we should validate
+ :type: Document
+
+ :param cert: The public cert
+ :type: string
+
+ :param fingerprint: The fingerprint of the public cert
+ :type: string
+
+ :param fingerprintalg: The algorithm used to build the fingerprint
+ :type: string
+
+ :param validatecert: If true, will verify the signature and if the cert is valid.
+ :type: bool
+
+ :param debug: Activate the xmlsec debug
+ :type: bool
+
+ :param raise_exceptions: Whether to return false on failure or raise an exception
+ :type raise_exceptions: Boolean
+ """
+ if(certisNoneorcert=='')andfingerprint:
+ x509_certificate_nodes=OneLogin_Saml2_XML.query(signature_node,'//ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate')
+ iflen(x509_certificate_nodes)>0:
+ x509_certificate_node=x509_certificate_nodes[0]
+ x509_cert_value=OneLogin_Saml2_XML.element_text(x509_certificate_node)
+ x509_cert_value_formatted=OneLogin_Saml2_Utils.format_cert(x509_cert_value)
+ x509_fingerprint_value=OneLogin_Saml2_Utils.calculate_x509_fingerprint(x509_cert_value_formatted,fingerprintalg)
+ iffingerprint==x509_fingerprint_value:
+ cert=x509_cert_value_formatted
+
+ ifcertisNoneorcert=='':
+ raiseOneLogin_Saml2_Error(
+ 'Could not validate node signature: No certificate provided.',
+ OneLogin_Saml2_Error.CERT_NOT_FOUND
+ )
+
+ # Check if Reference URI is empty
+ # reference_elem = OneLogin_Saml2_XML.query(signature_node, '//ds:Reference')
+ # if len(reference_elem) > 0:
+ # if reference_elem[0].get('URI') == '':
+ # reference_elem[0].set('URI', '#%s' % signature_node.getparent().get('ID'))
+
+ ifvalidatecert:
+ manager=xmlsec.KeysManager()
+ manager.load_cert_from_memory(cert,xmlsec.KeyFormat.CERT_PEM,xmlsec.KeyDataType.TRUSTED)
+ dsig_ctx=xmlsec.SignatureContext(manager)
+ else:
+ dsig_ctx=xmlsec.SignatureContext()
+ dsig_ctx.key=xmlsec.Key.from_memory(cert,xmlsec.KeyFormat.CERT_PEM,None)
+
+ dsig_ctx.set_enabled_key_data([xmlsec.KeyData.X509])
+
+ try:
+ dsig_ctx.verify(signature_node)
+ exceptExceptionaserr:
+ raiseOneLogin_Saml2_ValidationError(
+ 'Signature validation failed. SAML Response rejected. %s',
+ OneLogin_Saml2_ValidationError.INVALID_SIGNATURE,
+ str(err)
+ )
+
+ returnTrue
+
+
[docs]@staticmethod
+ defsign_binary(msg,key,algorithm=xmlsec.Transform.RSA_SHA256,debug=False):
+"""
+ Sign binary message
+
+ :param msg: The element we should validate
+ :type: bytes
+
+ :param key: The private key
+ :type: string
+
+ :param debug: Activate the xmlsec debug
+ :type: bool
+
+ :return signed message
+ :rtype str
+ """
+
+ ifisinstance(msg,str):
+ msg=msg.encode('utf8')
+
+ xmlsec.enable_debug_trace(debug)
+ dsig_ctx=xmlsec.SignatureContext()
+ dsig_ctx.key=xmlsec.Key.from_memory(key,xmlsec.KeyFormat.PEM,None)
+ returndsig_ctx.sign_binary(compat.to_bytes(msg),algorithm)
+
+
[docs]@staticmethod
+ defvalidate_binary_sign(signed_query,signature,cert=None,algorithm=OneLogin_Saml2_Constants.RSA_SHA256,debug=False):
+"""
+ Validates signed binary data (Used to validate GET Signature).
+
+ :param signed_query: The element we should validate
+ :type: string
+
+
+ :param signature: The signature that will be validate
+ :type: string
+
+ :param cert: The public cert
+ :type: string
+
+ :param algorithm: Signature algorithm
+ :type: string
+
+ :param debug: Activate the xmlsec debug
+ :type: bool
+ """
+ try:
+ xmlsec.enable_debug_trace(debug)
+ dsig_ctx=xmlsec.SignatureContext()
+ dsig_ctx.key=xmlsec.Key.from_memory(cert,xmlsec.KeyFormat.CERT_PEM,None)
+
+ sign_algorithm_transform_map={
+ OneLogin_Saml2_Constants.DSA_SHA1:xmlsec.Transform.DSA_SHA1,
+ OneLogin_Saml2_Constants.RSA_SHA1:xmlsec.Transform.RSA_SHA1,
+ OneLogin_Saml2_Constants.RSA_SHA256:xmlsec.Transform.RSA_SHA256,
+ OneLogin_Saml2_Constants.RSA_SHA384:xmlsec.Transform.RSA_SHA384,
+ OneLogin_Saml2_Constants.RSA_SHA512:xmlsec.Transform.RSA_SHA512
+ }
+ sign_algorithm_transform=sign_algorithm_transform_map.get(algorithm,xmlsec.Transform.RSA_SHA256)
+
+ dsig_ctx.verify_binary(compat.to_bytes(signed_query),
+ sign_algorithm_transform,
+ compat.to_bytes(signature))
+ returnTrue
+ exceptxmlsec.Errorase:
+ ifdebug:
+ print(e)
+ returnFalse
+
+
[docs]@staticmethod
+ defnormalize_url(url):
+"""
+ Returns normalized URL for comparison.
+ This method converts the netloc to lowercase, as it should be case-insensitive (per RFC 4343, RFC 7617)
+ If standardization fails, the original URL is returned
+ Python documentation indicates that URL split also normalizes query strings if empty query fields are present
+
+ :param url: URL
+ :type url: String
+
+ :returns: A normalized URL, or the given URL string if parsing fails
+ :rtype: String
+ """
+ try:
+ scheme,netloc,path,query,fragment=urlsplit(url)
+ normalized_url=urlunsplit((scheme.lower(),netloc.lower(),path,query,fragment))
+ returnnormalized_url
+ exceptException:
+ returnurl
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/saml2/_modules/onelogin/saml2/xml_templates.html b/docs/saml2/_modules/onelogin/saml2/xml_templates.html
new file mode 100644
index 00000000..13dd9b94
--- /dev/null
+++ b/docs/saml2/_modules/onelogin/saml2/xml_templates.html
@@ -0,0 +1,256 @@
+
+
+
+
+
+ onelogin.saml2.xml_templates — SAML Python2/3 Toolkit 1 documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
[docs]@staticmethod
+ defto_string(xml,**kwargs):
+"""
+ Serialize an element to an encoded string representation of its XML tree.
+ :param xml: The root node
+ :type xml: str|bytes|xml.dom.minidom.Document|etree.Element
+ :returns: string representation of xml
+ :rtype: string
+ """
+
+ ifisinstance(xml,OneLogin_Saml2_XML._text_class):
+ returnxml
+
+ ifisinstance(xml,OneLogin_Saml2_XML._element_class):
+ OneLogin_Saml2_XML.cleanup_namespaces(xml)
+ returnOneLogin_Saml2_XML._unparse_etree(xml,**kwargs)
+
+ raiseValueError("unsupported type %r"%type(xml))
+
+
[docs]@staticmethod
+ defto_etree(xml):
+"""
+ Parses an XML document or fragment from a string.
+ :param xml: the string to parse
+ :type xml: str|bytes|xml.dom.minidom.Document|etree.Element
+ :returns: the root node
+ :rtype: OneLogin_Saml2_XML._element_class
+ """
+ ifisinstance(xml,OneLogin_Saml2_XML._element_class):
+ returnxml
+ ifisinstance(xml,OneLogin_Saml2_XML._bytes_class):
+ returnOneLogin_Saml2_XML._parse_etree(xml,forbid_dtd=True,forbid_entities=True)
+ ifisinstance(xml,OneLogin_Saml2_XML._text_class):
+ returnOneLogin_Saml2_XML._parse_etree(compat.to_bytes(xml),forbid_dtd=True,forbid_entities=True)
+
+ raiseValueError('unsupported type %r'%type(xml))
+
+
[docs]@staticmethod
+ defvalidate_xml(xml,schema,debug=False):
+"""
+ Validates a xml against a schema
+ :param xml: The xml that will be validated
+ :type xml: str|bytes|xml.dom.minidom.Document|etree.Element
+ :param schema: The schema
+ :type schema: string
+ :param debug: If debug is active, the parse-errors will be showed
+ :type debug: bool
+ :returns: Error code or the DomDocument of the xml
+ :rtype: xml.dom.minidom.Document
+ """
+
+ assertisinstance(schema,compat.str_type)
+ try:
+ xml=OneLogin_Saml2_XML.to_etree(xml)
+ exceptExceptionase:
+ ifdebug:
+ print(e)
+ return'unloaded_xml'
+
+ schema_file=join(dirname(__file__),'schemas',schema)
+ withopen(schema_file,'r')asf_schema:
+ xmlschema=OneLogin_Saml2_XML._schema_class(etree.parse(f_schema))
+
+ ifnotxmlschema.validate(xml):
+ ifdebug:
+ print('Errors validating the metadata: ')
+ forerrorinxmlschema.error_log:
+ print(error.message)
+ return'invalid_xml'
+ returnxml
+
+
[docs]@staticmethod
+ defquery(dom,query,context=None,tagid=None):
+"""
+ Extracts nodes that match the query from the Element
+
+ :param dom: The root of the lxml objet
+ :type: Element
+
+ :param query: Xpath Expresion
+ :type: string
+
+ :param context: Context Node
+ :type: DOMElement
+
+ :param tagid: Tag ID
+ :type query: String
+
+ :returns: The queried nodes
+ :rtype: list
+ """
+ ifcontextisNone:
+ source=dom
+ else:
+ source=context
+
+ iftagidisNone:
+ returnsource.xpath(query,namespaces=OneLogin_Saml2_Constants.NSMAP)
+ else:
+ returnsource.xpath(query,tagid=tagid,namespaces=OneLogin_Saml2_Constants.NSMAP)
+
+
[docs]@staticmethod
+ defcleanup_namespaces(tree_or_element,top_nsmap=None,keep_ns_prefixes=None):
+"""
+ Keeps the xmlns:xs namespace intact when etree.cleanup_namespaces is invoked.
+ :param tree_or_element: An XML tree or element
+ :type tree_or_element: etree.Element
+ :param top_nsmap: A mapping from namespace prefixes to namespace URIs
+ :type top_nsmap: dict
+ :param keep_ns_prefixes: List of prefixes that should not be removed as part of the cleanup
+ :type keep_ns_prefixes: list
+ :returns: An XML tree or element
+ :rtype: etree.Element
+ """
+ all_prefixes_to_keep=[
+ OneLogin_Saml2_Constants.NS_PREFIX_XS,
+ OneLogin_Saml2_Constants.NS_PREFIX_XSI,
+ OneLogin_Saml2_Constants.NS_PREFIX_XSD
+ ]
+
+ ifkeep_ns_prefixes:
+ all_prefixes_to_keep=list(set(all_prefixes_to_keep.extend(keep_ns_prefixes)))
+
+ returnetree.cleanup_namespaces(tree_or_element,keep_ns_prefixes=all_prefixes_to_keep)
+# -*- coding: utf-8 -*-
+
+# Based on the lxml example from defusedxml
+# DTDForbidden, EntitiesForbidden, NotSupportedError are clones of the classes defined at defusedxml
+#
+# Copyright (c) 2013 by Christian Heimes <christian@python.org>
+# Licensed to PSF under a Contributor Agreement.
+# See https://www.python.org/psf/license for licensing details.
+"""lxml.etree protection"""
+
+from__future__importprint_function,absolute_import
+
+importthreading
+
+fromlxmlimportetreeas_etree
+
+LXML3=_etree.LXML_VERSION[0]>=3
+
+__origin__="lxml.etree"
+
+tostring=_etree.tostring
+
+
+
[docs]defcheck_docinfo(elementtree,forbid_dtd=False,forbid_entities=True):
+"""Check docinfo of an element tree for DTD and entity declarations
+ The check for entity declarations needs lxml 3 or newer. lxml 2.x does
+ not support dtd.iterentities().
+ """
+ docinfo=elementtree.docinfo
+ ifdocinfo.doctype:
+ ifforbid_dtd:
+ raiseDTDForbidden(docinfo.doctype,docinfo.system_url,docinfo.public_id)
+ ifforbid_entitiesandnotLXML3:
+ # lxml < 3 has no iterentities()
+ raiseNotSupportedError("Unable to check for entity declarations ""in lxml 2.x")
+
+ ifforbid_entities:
+ fordtdindocinfo.internalDTD,docinfo.externalDTD:
+ ifdtdisNone:
+ continue
+ forentityindtd.iterentities():
+ raiseEntitiesForbidden(entity.name,entity.content,None,None,None,None)
[docs]defprocess_response(self,request_id=None):
- """
- Process the SAML Response sent by the IdP.
-
- :param request_id: Is an optional argument. Is the ID of the AuthNRequest sent by this SP to the IdP.
- :type request_id: string
-
- :raises: OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND, when a POST with a SAMLResponse is not found
- """
- self.__errors=[]
-
- if'post_data'inself.__request_dataand'SAMLResponse'inself.__request_data['post_data']:
- # AuthnResponse -- HTTP_POST Binding
- response=OneLogin_Saml2_Response(self.__settings,self.__request_data['post_data']['SAMLResponse'])
-
- ifresponse.is_valid(request_id):
- self.__attributes=response.get_attributes()
- self.__nameid=response.get_nameid()
- self.__authenticated=True
- else:
- self.__errors.append('invalid_response')
-
- else:
- self.__errors.append('invalid_binding')
- raiseOneLogin_Saml2_Error(
- 'SAML Response not found, Only supported HTTP_POST Binding',
- OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND
- )
-
-
[docs]defprocess_slo(self,keep_local_session=False,request_id=None,delete_session_cb=None):
- """
- Process the SAML Logout Response / Logout Request sent by the IdP.
-
- :param keep_local_session: When false will destroy the local session, otherwise will destroy it
- :type keep_local_session: bool
-
- :param request_id: The ID of the LogoutRequest sent by this SP to the IdP
- :type request_id: string
-
- :returns: Redirection url
- """
- self.__errors=[]
-
- if'get_data'inself.__request_dataand'SAMLResponse'inself.__request_data['get_data']:
- logout_response=OneLogin_Saml2_Logout_Response(self.__settings,self.__request_data['get_data']['SAMLResponse'])
- ifnotlogout_response.is_valid(self.__request_data,request_id):
- self.__errors.append('invalid_logout_response')
- eliflogout_response.get_status()!=OneLogin_Saml2_Constants.STATUS_SUCCESS:
- self.__errors.append('logout_not_success')
- elifnotkeep_local_session:
- OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
-
- elif'get_data'inself.__request_dataand'SAMLRequest'inself.__request_data['get_data']:
- request=OneLogin_Saml2_Utils.decode_base64_and_inflate(self.__request_data['get_data']['SAMLRequest'])
- ifnotOneLogin_Saml2_Logout_Request.is_valid(self.__settings,request,self.__request_data):
- self.__errors.append('invalid_logout_request')
- else:
- ifnotkeep_local_session:
- OneLogin_Saml2_Utils.delete_local_session(delete_session_cb)
-
- in_response_to=OneLogin_Saml2_Logout_Request.get_id(request)
- response_builder=OneLogin_Saml2_Logout_Response(self.__settings)
- response_builder.build(in_response_to)
- logout_response=response_builder.get_response()
-
- parameters={'SAMLResponse':logout_response}
- if'RelayState'inself.__request_data['get_data']:
- parameters['RelayState']=self.__request_data['get_data']['RelayState']
-
- security=self.__settings.get_security_data()
- if'logoutResponseSigned'insecurityandsecurity['logoutResponseSigned']:
- signature=self.build_response_signature(logout_response,parameters.get('RelayState',None))
- parameters['SigAlg']=OneLogin_Saml2_Constants.RSA_SHA1
- parameters['Signature']=signature
-
- returnself.redirect_to(self.get_slo_url(),parameters)
-
- else:
- self.__errors.append('invalid_binding')
- raiseOneLogin_Saml2_Error(
- 'SAML LogoutRequest/LogoutResponse not found. Only supported HTTP_REDIRECT Binding',
- OneLogin_Saml2_Error.SAML_LOGOUTMESSAGE_NOT_FOUND
- )
-
-
[docs]defredirect_to(self,url=None,parameters={}):
- """
- Redirects the user to the url past by parameter or to the url that we defined in our SSO Request.
-
- :param url: The target URL to redirect the user
- :type url: string
- :param parameters: Extra parameters to be passed as part of the url
- :type parameters: dict
-
- :returns: Redirection url
- """
- ifurlisNoneand'RelayState'inself.__request_data['get_data']:
- url=self.__request_data['get_data']['RelayState']
- returnOneLogin_Saml2_Utils.redirect(url,parameters,request_data=self.__request_data)
-
-
[docs]defis_authenticated(self):
- """
- Checks if the user is authenticated or not.
-
- :returns: True if is authenticated, False if not
- :rtype: bool
- """
- returnself.__authenticated
-
-
[docs]defget_attributes(self):
- """
- Returns the set of SAML attributes.
-
- :returns: SAML attributes
- :rtype: dict
- """
- returnself.__attributes
-
[docs]defget_errors(self):
- """
- Returns a list with code errors if something went wrong
-
- :returns: List of errors
- :rtype: list
- """
- returnself.__errors
-
-
[docs]defget_attribute(self,name):
- """
- Returns the requested SAML attribute.
-
- :param name: Name of the attribute
- :type name: string
-
- :returns: Attribute value if exists or None
- :rtype: string
- """
- assertisinstance(name,basestring)
- value=None
- ifnameinself.__attributes.keys():
- value=self.__attributes[name]
- returnvalue
-
-
[docs]deflogin(self,return_to=None):
- """
- Initiates the SSO process.
-
- :param return_to: Optional argument. The target URL the user should be redirected to after login.
- :type return_to: string
-
- :returns: Redirection url
- """
- authn_request=OneLogin_Saml2_Authn_Request(self.__settings)
-
- saml_request=authn_request.get_request()
- parameters={'SAMLRequest':saml_request}
-
- ifreturn_toisnotNone:
- parameters['RelayState']=return_to
- else:
- parameters['RelayState']=OneLogin_Saml2_Utils.get_self_url_no_query(self.__request_data)
-
- security=self.__settings.get_security_data()
- ifsecurity.get('authnRequestsSigned',False):
- parameters['SigAlg']=OneLogin_Saml2_Constants.RSA_SHA1
- parameters['Signature']=self.build_request_signature(saml_request,parameters['RelayState'])
- returnself.redirect_to(self.get_sso_url(),parameters)
-
-
[docs]deflogout(self,return_to=None,name_id=None,session_index=None):
- """
- Initiates the SLO process.
-
- :param return_to: Optional argument. The target URL the user should be redirected to after logout.
- :type return_to: string
- :param name_id: Optional argument. The NameID that will be set in the LogoutRequest.
- :type name_id: string
- :param session_index: Optional argument. SessionIndex that identifies the session of the user.
- :type session_index: string
- :returns: Redirection url
- """
- slo_url=self.get_slo_url()
- ifslo_urlisNone:
- raiseOneLogin_Saml2_Error(
- 'The IdP does not support Single Log Out',
- OneLogin_Saml2_Error.SAML_SINGLE_LOGOUT_NOT_SUPPORTED
- )
-
- logout_request=OneLogin_Saml2_Logout_Request(self.__settings)
-
- saml_request=logout_request.get_request()
-
- parameters={'SAMLRequest':logout_request.get_request()}
- ifreturn_toisnotNone:
- parameters['RelayState']=return_to
- else:
- parameters['RelayState']=OneLogin_Saml2_Utils.get_self_url_no_query(self.__request_data)
-
- security=self.__settings.get_security_data()
- ifsecurity.get('logoutRequestSigned',False):
- parameters['SigAlg']=OneLogin_Saml2_Constants.RSA_SHA1
- parameters['Signature']=self.build_request_signature(saml_request,parameters['RelayState'])
- returnself.redirect_to(slo_url,parameters)
-
-
[docs]defget_sso_url(self):
- """
- Gets the SSO url.
-
- :returns: An URL, the SSO endpoint of the IdP
- :rtype: string
- """
- idp_data=self.__settings.get_idp_data()
- returnidp_data['singleSignOnService']['url']
-
-
[docs]defget_slo_url(self):
- """
- Gets the SLO url.
-
- :returns: An URL, the SLO endpoint of the IdP
- :rtype: string
- """
- url=None
- idp_data=self.__settings.get_idp_data()
- if'singleLogoutService'inidp_data.keys()and'url'inidp_data['singleLogoutService']:
- url=idp_data['singleLogoutService']['url']
- returnurl
-
-
[docs]defbuild_request_signature(self,saml_request,relay_state):
- """
- Builds the Signature of the SAML Request.
-
- :param saml_request: The SAML Request
- :type saml_request: string
-
- :param relay_state: The target URL the user should be redirected to
- :type relay_state: string
- """
- ifnotself.__settings.check_sp_certs():
- raiseOneLogin_Saml2_Error(
- "Trying to sign the SAML Request but can't load the SP certs",
- OneLogin_Saml2_Error.SP_CERTS_NOT_FOUND
- )
-
- xmlsec.initialize()
-
- # Load the key into the xmlsec context
- key=self.__settings.get_sp_key()
- file_key=OneLogin_Saml2_Utils.write_temp_file(key)# FIXME avoid writing a file
-
- dsig_ctx=xmlsec.DSigCtx()
- dsig_ctx.signKey=xmlsec.Key.load(file_key.name,xmlsec.KeyDataFormatPem,None)
- file_key.close()
-
- data={
- 'SAMLRequest':quote(saml_request),
- 'RelayState':quote(relay_state),
- 'SignAlg':quote(OneLogin_Saml2_Constants.RSA_SHA1),
- }
- msg=urlencode(data)
- signature=dsig_ctx.signBinary(msg,xmlsec.TransformRsaSha1)
- returnb64encode(signature)
-
-
[docs]defbuild_response_signature(self,saml_response,relay_state):
- """
- Builds the Signature of the SAML Response.
- :param saml_request: The SAML Response
- :type saml_request: string
-
- :param relay_state: The target URL the user should be redirected to
- :type relay_state: string
- """
- ifnotself.__settings.check_sp_certs():
- raiseOneLogin_Saml2_Error(
- "Trying to sign the SAML Response but can't load the SP certs",
- OneLogin_Saml2_Error.SP_CERTS_NOT_FOUND
- )
-
- xmlsec.initialize()
-
- # Load the key into the xmlsec context
- key=self.__settings.get_sp_key()
- file_key=OneLogin_Saml2_Utils.write_temp_file(key)# FIXME avoid writing a file
-
- dsig_ctx=xmlsec.DSigCtx()
- dsig_ctx.signKey=xmlsec.Key.load(file_key.name,xmlsec.KeyDataFormatPem,None)
- file_key.close()
-
- data={
- 'SAMLResponse':quote(saml_response),
- 'RelayState':quote(relay_state),
- 'SignAlg':quote(OneLogin_Saml2_Constants.RSA_SHA1),
- }
- msg=urlencode(data)
- importpdb;dbp.set_trace()
- printmsg
- data2={
- 'SAMLResponse':saml_response,
- 'RelayState':relay_state,
- 'SignAlg':OneLogin_Saml2_Constants.RSA_SHA1,
- }
- msg2=urlencode(data2)
- printmsg2
- signature=dsig_ctx.signBinary(msg,xmlsec.TransformRsaSha1)
- returnb64encode(signature)
-
-
-
-
-
-
-
-
-
Quick search
-
-
- Enter search terms or a module, class or function name.
-
[docs]classOneLogin_Saml2_Logout_Response():
-
- def__init__(self,settings,response=None):
- """
- Constructs a Logout Response object (Initialize params from settings
- and if provided load the Logout Response.
-
- Arguments are:
- * (OneLogin_Saml2_Settings) settings. Setting data
- * (string) response. An UUEncoded SAML Logout
- response from the IdP.
- """
- self.__settings=settings
- ifresponseisnotNone:
- self.__logout_response=OneLogin_Saml2_Utils.decode_base64_and_inflate(response)
- self.document=parseString(self.__logout_response)
-
-
[docs]defget_issuer(self):
- """
- Gets the Issuer of the Logout Response Message
- :return: The Issuer
- :rtype: string
- """
- issuer=None
- issuer_nodes=self.__query('/samlp:LogoutResponse/saml:Issuer')
- iflen(issuer_nodes)==1:
- issuer=issuer_nodes[0].text
- returnissuer
-
-
[docs]defget_status(self):
- """
- Gets the Status
- :return: The Status
- :rtype: string
- """
- entries=self.__query('/samlp:LogoutResponse/samlp:Status/samlp:StatusCode')
- iflen(entries)==0:
- returnNone
- status=entries[0].attrib['Value']
- returnstatus
-
-
[docs]defis_valid(self,request_data,request_id=None):
- """
- Determines if the SAML LogoutResponse is valid
- :param request_id: The ID of the LogoutRequest sent by this SP to the IdP
- :type request_id: string
- :return: Returns if the SAML LogoutResponse is or not valid
- :rtype: boolean
- """
- try:
- idp_data=self.__settings.get_idp_data()
- idp_entity_id=idp_data['entityId']
- get_data=request_data['get_data']
-
- ifself.__settings.is_strict():
- res=OneLogin_Saml2_Utils.validate_xml(self.document,'saml-schema-protocol-2.0.xsd',self.__settings.is_debug_active())
- ifnotisinstance(res,Document):
- raiseException('Invalid SAML Logout Request. Not match the saml-schema-protocol-2.0.xsd')
-
- security=self.__settings.get_security_data()
-
- # Check if the InResponseTo of the Logout Response matchs the ID of the Logout Request (requestId) if provided
- ifrequest_idisnotNoneandself.document.documentElement.hasAttribute('InResponseTo'):
- in_response_to=self.document.documentElement.getAttribute('InResponseTo')
- ifrequest_id!=in_response_to:
- raiseException('The InResponseTo of the Logout Response: %s, does not match the ID of the Logout request sent by the SP: %s'%(in_response_to,request_id))
-
- # Check issuer
- issuer=self.get_issuer()
- ifissuerisNoneorissuer!=idp_entity_id:
- raiseException('Invalid issuer in the Logout Request')
-
- current_url=OneLogin_Saml2_Utils.get_self_url_no_query(request_data)
-
- # Check destination
- ifself.document.documentElement.hasAttribute('Destination'):
- destination=self.document.documentElement.getAttribute('Destination')
- ifdestinationisnotNone:
- ifcurrent_urlnotindestination:
- raiseException('The LogoutRequest was received at $currentURL instead of $destination')
-
- ifsecurity['wantMessagesSigned']:
- if'Signature'notinget_data:
- raiseException('The Message of the Logout Response is not signed and the SP require it')
-
- if'Signature'inget_data:
- if'SigAlg'notinget_data:
- sign_alg=OneLogin_Saml2_Constants.RSA_SHA1
- else:
- sign_alg=get_data['SigAlg']
-
- ifsign_alg!=OneLogin_Saml2_Constants.RSA_SHA1:
- raiseException('Invalid signAlg in the recieved Logout Response')
-
- signed_query='SAMLResponse=%s'%quote_plus(get_data['SAMLResponse'])
- if'RelayState'inget_data:
- signed_query='%s&RelayState=%s'%(signed_query,quote_plus(get_data['RelayState']))
- signed_query='%s&SigAlg=%s'%(signed_query,quote_plus(sign_alg))
-
- if'x509cert'notinidp_dataoridp_data['x509cert']isNone:
- raiseException('In order to validate the sign on the Logout Response, the x509cert of the IdP is required')
- cert=idp_data['x509cert']
-
- xmlsec.initialize()
- objkey=xmlsec.Key.load(cert,xmlsec.KeyDataFormatPem,None)# FIXME is this right?
-
- ifnotobjkey.verifySignature(signed_query,b64decode(get_data['Signature'])):
- raiseException('Signature validation failed. Logout Response rejected')
-
- returnTrue
- exceptExceptionase:
- debug=self.__settings.is_debug_active()
- ifdebug:
- print(e.strerror)
- returnFalse
-
- def__query(self,query):
- """
- Extracts a node from the DOMDocument (Logout Response Menssage)
- :param query: Xpath Expresion
- :type query: string
- :return: The queried node
- :rtype: DOMNodeList
- """
- # Switch to lxml for querying
- xml=self.document.toxml()
- returnOneLogin_Saml2_Utils.query(etree.fromstring(xml),query)
-
-
[docs]classOneLogin_Saml2_Response(object):
-
- def__init__(self,settings,response):
- """
- Constructs the response object.
-
- :param settings: The setting info
- :type settings: OneLogin_Saml2_Setting object
-
- :param response: The base64 encoded, XML string containing the samlp:Response
- :type response: string
- """
- self.__settings=settings
- self.response=b64decode(response)
- self.document=etree.fromstring(self.response)
- self.decrypted_document=None
- self.encrypted=None
-
- # Quick check for the presence of EncryptedAssertion
- encrypted_assertion_nodes=self.__query('//saml:EncryptedAssertion')
- ifencrypted_assertion_nodes:
- decrypted_document=deepcopy(self.document)
- self.encrypted=True
- self.decrypted_document=self.__decrypt_assertion(decrypted_document)
-
-
[docs]defis_valid(self,request_data,request_id=None):
- """
- Constructs the response object.
-
- :param request_id: Optional argument. The ID of the AuthNRequest sent by this SP to the IdP
- :type request_id: string
-
- :returns: True if the SAML Response is valid, False if not
- :rtype: bool
- """
- try:
- # Checks SAML version
- ifself.document.get('Version',None)!='2.0':
- raiseException('Unsupported SAML version')
-
- # Checks that ID exists
- ifself.document.get('ID',None)isNone:
- raiseException('Missing ID attribute on SAML Response')
-
- # Checks that the response only has one assertion
- ifnotself.validate_num_assertions():
- raiseException('Multiple assertions are not supported')
-
- # Checks that the response has the SUCCESS status
- self.check_status()
-
- idp_data=self.__settings.get_idp_data()
- idp_entityid=idp_data.get('entityId','')
- sp_data=self.__settings.get_sp_data()
- sp_entityid=sp_data.get('entityId','')
-
- sign_nodes=self.__query('//ds:Signature')
-
- signed_elements=[]
- forsign_nodeinsign_nodes:
- signed_elements.append(sign_node.getparent().tag)
-
- ifself.__settings.is_strict():
- res=OneLogin_Saml2_Utils.validate_xml(etree.tostring(self.document),'saml-schema-protocol-2.0.xsd',self.__settings.is_debug_active())
- ifnotisinstance(res,Document):
- raiseException('Invalid SAML Response. Not match the saml-schema-protocol-2.0.xsd')
-
- security=self.__settings.get_security_data()
- current_url=OneLogin_Saml2_Utils.get_self_url_no_query(request_data)
-
- # Check if the InResponseTo of the Response matchs the ID of the AuthNRequest (requestId) if provided
- in_response_to=self.document.get('InResponseTo',None)
- ifin_response_toandrequest_id:
- ifin_response_to!=request_id:
- raiseException('The InResponseTo of the Response: %s, does not match the ID of the AuthNRequest sent by the SP: %s'%(in_response_to,request_id))
-
- ifnotself.encryptedandsecurity.get('wantAssertionsEncrypted',False):
- raiseException('The assertion of the Response is not encrypted and the SP require it')
-
- ifsecurity.get('wantNameIdEncrypted',False):
- encrypted_nameid_nodes=self.__query_assertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData')
- ifnotencrypted_nameid_nodes:
- raiseException('The NameID of the Response is not encrypted and the SP require it')
-
- # Checks that there is at least one AttributeStatement
- attribute_statement_nodes=self.__query_assertion('/saml:AttributeStatement')
- ifnotattribute_statement_nodes:
- raiseException('There is no AttributeStatement on the Response')
-
- # Validates Asserion timestamps
- ifnotself.validate_timestamps():
- raiseException('Timing issues (please check your clock settings)')
-
- encrypted_attributes_nodes=self.__query_assertion('/saml:AttributeStatement/saml:EncryptedAttribute')
- ifencrypted_attributes_nodes:
- raiseException('There is an EncryptedAttribute in the Response and this SP not support them')
-
- # Checks destination
- destination=self.document.get('Destination',None)
- ifdestination:
- ifdestinationnotincurrent_url:
- raiseException('The response was received at %s instead of %s'%(current_url,destination))
-
- # Checks audience
- valid_audiences=self.get_audiences()
- ifvalid_audiencesandsp_entityidnotinvalid_audiences:
- raiseException('%s is not a valid audience for this Response'%sp_entityid)
-
- # Checks the issuers
- issuers=self.get_issuers()
- forissuerinissuers:
- ifnotissuerorissuer!=idp_entityid:
- raiseException('Invalid issuer in the Assertion/Response')
-
- # Checks the session Expiration
- session_expiration=self.get_session_not_on_or_after()
- ifnotsession_expirationandsession_expiration<=time():
- raiseException('The attributes have expired, based on the SessionNotOnOrAfter of the AttributeStatement of this Response')
-
- # Checks the SubjectConfirmation, at least one SubjectConfirmation must be valid
- any_subject_confirmation=False
- subject_confirmation_nodes=self.__query_assertion('/saml:Subject/saml:SubjectConfirmation')
-
- forscninsubject_confirmation_nodes:
- method=scn.get('Method',None)
- ifmethodandmethod!=OneLogin_Saml2_Constants.CM_BEARER:
- continue
- scData=scn.find('saml:SubjectConfirmationData',namespaces=OneLogin_Saml2_Constants.NSMAP)
- ifscDataisNone:
- continue
- else:
- irt=scData.get('InResponseTo',None)
- ifirt!=in_response_to:
- continue
- recipient=scData.get('Recipient',None)
- ifrecipientnotincurrent_url:
- continue
- nooa=scData.get('NotOnOrAfter',None)
- ifnooa:
- parsed_nooa=OneLogin_Saml2_Utils.parse_SAML_to_time(nooa)
- ifparsed_nooa<=time():
- continue
- nb=scData.get('NotBefore',None)
- ifnb:
- parsed_nb=OneLogin_Saml2_Utils.parse_SAML_to_time(nb)
- if(parsed_nb>time()):
- continue
- any_subject_confirmation=True
- break
-
- ifnotany_subject_confirmation:
- raiseException('A valid SubjectConfirmation was not found on this Response')
-
- ifsecurity.get('wantAssertionsSigned',False)and'saml:Assertion'notinsigned_elements:
- raiseException('The Assertion of the Response is not signed and the SP require it')
-
- ifsecurity.get('wantMessagesSigned',False)and'samlp:Response'notinsigned_elements:
- raiseException('The Message of the Response is not signed and the SP require it')
-
- document_to_validate=None
- iflen(signed_elements)>0:
- cert=idp_data.get('x509cert',None)
- fingerprint=idp_data.get('certFingerprint',None)
-
- # Only validates the first sign found
- if'samlp:Response'insigned_elements:
- document_to_validate=self.document
- else:
- ifself.encrypted:
- document_to_validate=self.decrypted_document
- else:
- document_to_validate=self.document
-
- ifdocument_to_validateisnotNone:
- ifnotOneLogin_Saml2_Utils.validate_sign(document_to_validate,cert,fingerprint):
- raiseException('Signature validation failed. SAML Response rejected')
- returnTrue
- except:
- debug=self.__settings.is_debug_active()
- ifdebug:
- printsys.exc_info()[0]
- returnFalse
-
-
[docs]defcheck_status(self):
- """
- Check if the status of the response is success or not
-
- :raises: Exception. If the status is not success
- """
- status=OneLogin_Saml2_Utils.get_status(self.document)
- code=status.get('code',None)
- ifcodeandcode!=OneLogin_Saml2_Constants.STATUS_SUCCESS:
- splited_code=code.split(':')
- printable_code=splited_code.pop()
- status_exception_msg='The status code of the Response was not Success, was %s'%printable_code
- status_msg=status.get('msg',None)
- ifstatus_msg:
- status_exception_msg+=' -> '+status_msg
- raiseException(status_exception_msg)
-
-
[docs]defget_audiences(self):
- """
- Gets the audiences
-
- :returns: The valid audiences for the SAML Response
- :rtype: list
- """
- audiences=[]
-
- audience_nodes=self.__query_assertion('/saml:Conditions/saml:AudienceRestriction/saml:Audience')
- foraudience_nodeinaudience_nodes:
- audiences.append(audience_node.text)
-
-
[docs]defget_issuers(self):
- """
- Gets the issuers (from message and from assertion)
-
- :returns: The issuers
- :rtype: list
- """
- issuers=[]
-
- message_issuer_nodes=self.__query('/samlp:Response/saml:Issuer')
- ifmessage_issuer_nodes:
- issuers.append(message_issuer_nodes[0].text)
-
- assertion_issuer_nodes=self.__query_assertion('/saml:Issuer')
- ifassertion_issuer_nodes:
- issuers.append(assertion_issuer_nodes[0].text)
-
- returnlist(set(issuers))
-
-
[docs]defget_nameid_data(self):
- """
- Gets the NameID Data provided by the SAML Response from the IdP
-
- :returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
- :rtype: dict
- """
- nameid=None
- encrypted_id_data_nodes=self.__query_assertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData')
- ifencrypted_id_data_nodes:
- encrypted_data=encrypted_id_data_nodes[0]
-
- xmlsec.initialize()
-
- # Load the key into the xmlsec context
- key=self.__settings.get_sp_key()
- file_key=OneLogin_Saml2_Utils.write_temp_file(key)# FIXME avoid writing a file
- enc_key=xmlsec.Key.load(file_key.name,xmlsec.KeyDataFormatPem,None)
- enc_key.name=basename(file_key.name)
- file_key.close()
- enc_ctx=xmlsec.EncCtx()
- enc_ctx.encKey=enc_key
-
- nameid=OneLogin_Saml2_Utils.decrypt_element(encrypted_data,enc_ctx)
- else:
- nameid_nodes=self.__query_assertion('/saml:Subject/saml:NameID')
- ifnameid_nodes:
- nameid=nameid_nodes[0]
- ifnameidisNone:
- raiseException('Not NameID found in the assertion of the Response')
-
- nameid_data={'Value':nameid.text}
- forattrin['Format','SPNameQualifier','NameQualifier']:
- value=nameid.get(attr,None)
- ifvalue:
- nameid_data[attr]=value
- returnnameid_data
-
-
[docs]defget_nameid(self):
- """
- Gets the NameID provided by the SAML Response from the IdP
-
- :returns: NameID (value)
- :rtype: string
- """
- nameid_data=self.get_nameid_data()
- returnnameid_data['Value']
-
-
[docs]defget_session_not_on_or_after(self):
- """
- Gets the SessionNotOnOrAfter from the AuthnStatement
- Could be used to set the local session expiration
-
- :returns: The SessionNotOnOrAfter value
- :rtype: time|None
- """
- not_on_or_after=None
- authn_statement_nodes=self.__query_assertion('/saml:AuthnStatement[@SessionNotOnOrAfter]')
- ifauthn_statement_nodes:
- not_on_or_after=OneLogin_Saml2_Utils.parse_SAML_to_time(authn_statement_nodes[0].get('SessionNotOnOrAfter'))
- returnnot_on_or_after
-
-
[docs]defget_session_index(self):
- """
- Gets the SessionIndex from the AuthnStatement
- Could be used to be stored in the local session in order
- to be used in a future Logout Request that the SP could
- send to the SP, to set what specific session must be deleted
-
- :returns: The SessionIndex value
- :rtype: string|None
- """
- session_index=None
- authn_statement_nodes=self.__query_assertion('/saml:AuthnStatement[@SessionIndex]')
- ifauthn_statement_nodes:
- session_index=authn_statement_nodes[0].get('SessionIndex')
- returnsession_index
-
-
[docs]defget_attributes(self):
- """
- Gets the Attributes from the AttributeStatement element.
- EncryptedAttributes are not supported
- """
- attributes={}
- attribute_nodes=self.__query_assertion('/saml:AttributeStatement/saml:Attribute')
- forattribute_nodeinattribute_nodes:
- attr_name=attribute_node.get('Name')
- values=[]
- forattrinattribute_node.iterchildren('{%s}AttributeValue'%OneLogin_Saml2_Constants.NSMAP['saml']):
- values.append(attr.text)
- attributes[attr_name]=values
- returnattributes
-
-
[docs]defvalidate_num_assertions(self):
- """
- Verifies that the document only contains a single Assertion (encrypted or not)
-
- :returns: True if only 1 assertion encrypted or not
- :rtype: bool
- """
- encrypted_assertion_nodes=self.__query('//saml:EncryptedAssertion')
- assertion_nodes=self.__query('//saml:Assertion')
- return(len(encrypted_assertion_nodes)+len(assertion_nodes))==1
-
-
[docs]defvalidate_timestamps(self):
- """
- Verifies that the document is valid according to Conditions Element
-
- :returns: True if the condition is valid, False otherwise
- :rtype: bool
- """
- conditions_nodes=self.__query('//saml:Conditions')
- forconditions_nodeinconditions_nodes:
- nb_attr=conditions_node.get('NotBefore')
- nooa_attr=conditions_node.get('NotOnOrAfter')
- ifnb_attrandOneLogin_Saml2_Utils.parse_SAML_to_time(nb_attr)>time()+OneLogin_Saml2_Constants.ALOWED_CLOCK_DRIFT:
- returnFalse
- ifnooa_attrandOneLogin_Saml2_Utils.parse_SAML_to_time(nooa_attr)+OneLogin_Saml2_Constants.ALOWED_CLOCK_DRIFT<=time():
- returnFalse
- returnTrue
-
- def__query_assertion(self,xpath_expr):
- """
- Extracts nodes that match the query from the Assertion
-
- :param query: Xpath Expresion
- :type query: String
-
- :returns: The queried nodes
- :rtype: list
- """
- ifself.encrypted:
- assertion_expr='/saml:EncryptedAssertion/saml:Assertion'
- else:
- assertion_expr='/saml:Assertion'
- signature_expr='/ds:Signature/ds:SignedInfo/ds:Reference'
- signed_assertion_query='/samlp:Response'+assertion_expr+signature_expr
- assertion_reference_nodes=self.__query(signed_assertion_query)
-
- ifnotassertion_reference_nodes:
- # Check if the message is signed
- signed_message_query='/samlp:Response'+signature_expr
- message_reference_nodes=self.__query(signed_message_query)
- ifmessage_reference_nodes:
- id=message_reference_nodes[0].get('URI')
- final_query="/samlp:Response[@ID='%s']/"%id[1:]
- else:
- final_query="/samlp:Response/"
- final_query+=assertion_expr
- else:
- id=assertion_reference_nodes[0].get('URI')
- final_query='/samlp:Response'+assertion_expr+"[@ID='%s']"%id[1:]
- final_query+=xpath_expr
- returnself.__query(final_query)
-
- def__query(self,query):
- """
- Extracts nodes that match the query from the Response
-
- :param query: Xpath Expresion
- :type query: String
-
- :returns: The queried nodes
- :rtype: list
- """
- ifself.encrypted:
- document=self.decrypted_document
- else:
- document=self.document
- returnOneLogin_Saml2_Utils.query(document,query)
-
- def__decrypt_assertion(self,dom):
- """
- Decrypts the Assertion
-
- :raises: Exception if no private key available
- :param dom: Encrypted Assertion
- :type dom: Element
- :returns: Decrypted Assertion
- :rtype: Element
- """
- key=self.__settings.get_sp_key()
-
- ifnotkey:
- raiseException('No private key available, check settings')
-
- # TODO Study how decrypt assertion
-
-
-
-
-
-
-
-
-
Quick search
-
-
- Enter search terms or a module, class or function name.
-
[docs]defcheck_sp_certs(self):
- """
- Checks if the x509 certs of the SP exists and are valid.
-
- :returns: If the x509 certs of the SP exists and are valid
- :rtype: boolean
- """
- key=self.get_sp_key()
- cert=self.get_sp_cert()
- returnkeyisnotNoneandcertisnotNone
-
[docs]defget_errors(self):
- """
- Returns an array with the errors, the array is empty when the settings is ok.
-
- :returns: Errors
- :rtype: list
- """
- returnself.__errors
-
[docs]defdecode_base64_and_inflate(value):
- """ base64 decodes and then inflates according to RFC1951
- :param value: a deflated and encoded string
- :return: the string after decoding and inflating
- """
-
- returnzlib.decompress(base64.b64decode(value),-15)
-
- @staticmethod
-
[docs]defdeflate_and_base64_encode(value):
- """
- Deflates and the base64 encodes a string
- :param value: The string to deflate and encode
- :return: The deflated and encoded string
- """
- returnbase64.b64encode(zlib.compress(value)[2:-4])
-
[docs]defformat_cert(cert,heads=True):
- """
- Returns a x509 cert (adding header & footer if required).
-
- :param cert: A x509 unformated cert
- :type: string
-
- :param heads: True if we want to include head and footer
- :type: boolean
-
- :returns: Formated cert
- :rtype: string
- """
- x509_cert=cert.replace('\x0D','')
- x509_cert=x509_cert.replace('\r','')
- x509_cert=x509_cert.replace('\n','')
- iflen(x509_cert)>0:
- x509_cert=x509_cert.replace('-----BEGIN CERTIFICATE-----','')
- x509_cert=x509_cert.replace('-----END CERTIFICATE-----','')
- x509_cert=x509_cert.replace(' ','')
-
- ifheads:
- x509_cert='-----BEGIN CERTIFICATE-----\n'+'\n'.join(wrap(x509_cert,64))+'\n-----END CERTIFICATE-----\n'
-
- returnx509_cert
-
- @staticmethod
-
[docs]defredirect(url,parameters={},request_data={}):
- """
- Executes a redirection to the provided url (or return the target url).
-
- :param url: The target url
- :type: string
-
- :param parameters: Extra parameters to be passed as part of the url
- :type: dict
-
- :param request_data: The request as a dict
- :type: dict
-
- :returns: Url
- :rtype: string
- """
- assertisinstance(url,basestring)
- assertisinstance(parameters,dict)
-
- ifurl.startswith('/'):
- url='%s%s'%(OneLogin_Saml2_Utils.get_self_url_host(request_data),url)
-
- # Verify that the URL is to a http or https site.
- ifre.search('^https?://',url)isNone:
- raiseOneLogin_Saml2_Error(
- 'Redirect to invalid URL: '+url,
- OneLogin_Saml2_Error.REDIRECT_INVALID_URL
- )
-
- # Add encoded parameters
- ifurl.find('?')<0:
- param_prefix='?'
- else:
- param_prefix='&'
-
- forname,valueinparameters.items():
-
- ifvalueisNone:
- param=urlencode(name)
- elifisinstance(value,list):
- param=''
- forvalinvalue:
- param+=quote_plus(name)+'[]='+quote_plus(val)+'&'
- iflen(param)>0:
- param=param[0:-1]
- else:
- param=quote_plus(name)+'='+quote_plus(value)
-
- url+=param_prefix+param
- param_prefix='&'
-
- returnurl
-
- @staticmethod
-
[docs]defget_self_url_host(request_data):
- """
- Returns the protocol + the current host + the port (if different than
- common ports).
-
- :param request_data: The request as a dict
- :type: dict
-
- :return: Url
- :rtype: string
- """
- current_host=OneLogin_Saml2_Utils.get_self_host(request_data)
- port=''
- ifOneLogin_Saml2_Utils.is_https(request_data):
- protocol='https'
- else:
- protocol='http'
-
- if'server_port'inrequest_data:
- port_number=request_data['server_port']
- port=':'+port_number
-
- ifprotocol=='http'andport_number=='80':
- port=''
- elifprotocol=='https'andport_number=='443':
- port=''
-
- return'%s://%s%s'%(protocol,current_host,port)
-
- @staticmethod
-
[docs]defget_self_host(request_data):
- """
- Returns the current host.
-
- :param request_data: The request as a dict
- :type: dict
-
- :return: The current host
- :rtype: string
- """
- if'http_host'inrequest_data:
- current_host=request_data['http_host']
- elif'server_name'inrequest_data:
- current_host=request_data['server_name']
- else:
- raiseException('No hostname defined')
-
- if':'incurrent_host:
- current_host_data=current_host.split(':')
- possible_port=current_host_data[-1]
- try:
- possible_port=float(possible_port)
- current_host=current_host_data[0]
- exceptValueError:
- current_host=':'.join(current_host_data)
-
- returncurrent_host
-
- @staticmethod
-
[docs]defis_https(request_data):
- """
- Checks if https or http.
-
- :param request_data: The request as a dict
- :type: dict
-
- :return: False if https is not active
- :rtype: boolean
- """
- is_https='https'inrequest_dataandrequest_data['https']!='off'
- is_https=is_httpsor('server_port'inrequest_dataandrequest_data['server_port']=='443')
- returnis_https
-
- @staticmethod
-
[docs]defget_self_url_no_query(request_data):
- """
- Returns the URL of the current host + current view.
-
- :param request_data: The request as a dict
- :type: dict
-
- :return: The url of current host + current view
- :rtype: string
- """
- self_url_host=OneLogin_Saml2_Utils.get_self_url_host(request_data)
- script_name=request_data['script_name']
- ifscript_name[0]!='/':
- script_name='/'+script_name
- self_url_host+=script_name
- if'path_info'inrequest_data:
- self_url_host+=request_data['path_info']
-
- returnself_url_host
-
- @staticmethod
-
[docs]defget_self_url(request_data):
- """
- Returns the URL of the current host + current view + query.
-
- :param request_data: The request as a dict
- :type: dict
-
- :return: The url of current host + current view + query
- :rtype: string
- """
- self_url_host=OneLogin_Saml2_Utils.get_self_url_host(request_data)
-
- request_uri=''
- if'request_uri'inrequest_data:
- request_uri=request_data['request_uri']
- ifnotrequest_uri.startswith('/'):
- match=re.search('^https?://[^/]*(/.*)',request_uri)
- ifmatchisnotNone:
- request_uri=match.groups()[0]
-
- returnself_url_host+request_uri
-
- @staticmethod
-
[docs]defgenerate_unique_id():
- """
- Generates an unique string (used for example as ID for assertions).
-
- :return: A unique string
- :rtype: string
- """
- return'ONELOGIN_%s'%sha1(uuid4().hex).hexdigest()
-
- @staticmethod
-
[docs]defparse_time_to_SAML(time):
- """
- Converts a UNIX timestamp to SAML2 timestamp on the form
- yyyy-mm-ddThh:mm:ss(\.s+)?Z.
-
- :param time: The time we should convert (DateTime).
- :type: string
-
- :return: SAML2 timestamp.
- :rtype: string
- """
- data=datetime.utcfromtimestamp(float(time))
- returndata.strftime('%Y-%m-%dT%H:%M:%SZ')
-
- @staticmethod
-
[docs]defparse_SAML_to_time(timestr):
- """
- Converts a SAML2 timestamp on the form yyyy-mm-ddThh:mm:ss(\.s+)?Z
- to a UNIX timestamp. The sub-second part is ignored.
-
- :param time: The time we should convert (SAML Timestamp).
- :type: string
-
- :return: Converted to a unix timestamp.
- :rtype: int
- """
- try:
- data=datetime.strptime(timestr,'%Y-%m-%dT%H:%M:%SZ')
- exceptValueError:
- data=datetime.strptime(timestr,'%Y-%m-%dT%H:%M:%S.%fZ')
- returncalendar.timegm(data.utctimetuple())
-
- @staticmethod
-
[docs]defparse_duration(duration,timestamp=None):
- """
- Interprets a ISO8601 duration value relative to a given timestamp.
-
- :param duration: The duration, as a string.
- :type: string
-
- :param timestamp: The unix timestamp we should apply the duration to.
- Optional, default to the current time.
- :type: string
-
- :return: The new timestamp, after the duration is applied.
- :rtype: int
- """
- assertisinstance(duration,basestring)
- assert(timestampisNoneorisinstance(timestamp,int))
-
- timedelta=duration_parser(duration)
- iftimestampisNone:
- data=datetime.utcnow()+timedelta
- else:
- data=datetime.utcfromtimestamp(timestamp)+timedelta
- returncalendar.timegm(data.utctimetuple())
-
- @staticmethod
-
[docs]defget_expire_time(cache_duration=None,valid_until=None):
- """
- Compares 2 dates and returns the earliest.
-
- :param cache_duration: The duration, as a string.
- :type: string
-
- :param valid_until: The valid until date, as a string or as a timestamp
- :type: string
-
- :return: The expiration time.
- :rtype: int
- """
- expire_time=None
-
- ifcache_durationisnotNone:
- expire_time=OneLogin_Saml2_Utils.parse_duration(cache_duration)
-
- ifvalid_untilisnotNone:
- ifisinstance(valid_until,int):
- valid_until_time=valid_until
- else:
- valid_until_time=OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until)
- ifexpire_timeisNoneorexpire_time>valid_until_time:
- expire_time=valid_until_time
-
- ifexpire_timeisnotNone:
- return'%d'%expire_time
- returnNone
-
- @staticmethod
-
[docs]defquery(dom,query,context=None):
- """
- Extracts nodes that match the query from the Element
-
- :param dom: The root of the lxml objet
- :type: Element
-
- :param query: Xpath Expresion
- :type: string
-
- :param context: Context Node
- :type: DOMElement
-
- :returns: The queried nodes
- :rtype: list
- """
- ifcontextisNone:
- returndom.xpath(query,namespaces=OneLogin_Saml2_Constants.NSMAP)
- else:
- returncontext.xpath(query,namespaces=OneLogin_Saml2_Constants.NSMAP)
-
- @staticmethod
-
[docs]defdelete_local_session(callback=None):
- """
- Deletes the local session.
- """
-
- ifcallbackisnotNone:
- callback()
-
- @staticmethod
-
[docs]defcalculate_x509_fingerprint(x509_cert):
- """
- Calculates the fingerprint of a x509cert.
-
- :param x509_cert: x509 cert
- :type: string
-
- :returns: Formated fingerprint
- :rtype: string
- """
- assertisinstance(x509_cert,basestring)
-
- lines=x509_cert.split('\n')
- data=''
-
- forlineinlines:
- # Remove '\r' from end of line if present.
- line=line.rstrip()
- ifline=='-----BEGIN CERTIFICATE-----':
- # Delete junk from before the certificate.
- data=''
- elifline=='-----END CERTIFICATE-----':
- # Ignore data after the certificate.
- break
- elifline=='-----BEGIN PUBLIC KEY-----'orline=='-----BEGIN RSA PRIVATE KEY-----':
- # This isn't an X509 certificate.
- returnNone
- else:
- # Append the current line to the certificate data.
- data+=line
- # "data" now contains the certificate as a base64-encoded string. The
- # fingerprint of the certificate is the sha1-hash of the certificate.
- returnsha1(base64.b64decode(data)).hexdigest().lower()
-
[docs]defget_status(dom):
- """
- Gets Status from a Response.
-
- :param dom: The Response as XML
- :type: Document
-
- :returns: The Status, an array with the code and a message.
- :rtype: dict
- """
- status={}
-
- status_entry=OneLogin_Saml2_Utils.query(dom,'/samlp:Response/samlp:Status')
- iflen(status_entry)==0:
- raiseException('Missing Status on response')
-
- code_entry=OneLogin_Saml2_Utils.query(dom,'/samlp:Response/samlp:Status/samlp:StatusCode',status_entry[0])
- iflen(code_entry)==0:
- raiseException('Missing Status Code on response')
- code=code_entry[0].values()[0]
- status['code']=code
-
- message_entry=OneLogin_Saml2_Utils.query(dom,'/samlp:Response/samlp:Status/samlp:StatusMessage',status_entry[0])
- iflen(message_entry)==0:
- status['msg']=''
- else:
- status['msg']=message_entry[0].text
-
- returnstatus
-
- @staticmethod
-
[docs]defdecrypt_element(encrypted_data,enc_ctx):
- """
- Decrypts an encrypted element.
-
- :param encrypted_data: The encrypted data.
- :type: DOMElement
-
- :param enc_ctx: The encryption context.
- :type: Encryption Context
-
- :returns: The decrypted element.
- :rtype: DOMElement
- """
- ifisinstance(encrypted_data,Element):
- # Minidom element
- encrypted_data=etree.fromstring(encrypted_data.toxml())
-
- decrypted=enc_ctx.decrypt(encrypted_data)
- ifisinstance(decrypted,ElementBase):
- # lxml element, decrypted xml data
- returntostring(decrypted.getroottree())
- else:
- # decrypted binary data
- returndecrypted
-
- @staticmethod
-
[docs]defwrite_temp_file(content):
- """
- Writes some content into a temporary file and returns it.
-
- :param content: The file content
- :type: string
-
- :returns: The temporary file
- :rtype: file-like object
- """
- f=NamedTemporaryFile(delete=True)
- f.file.write(content)
- f.file.flush()
- returnf
-
- @staticmethod
-
[docs]defadd_sign(xml,key,cert):
- """
- Adds signature key and senders certificate to an element (Message or
- Assertion).
-
- :param xml: The element we should sign
- :type: string | Document
-
- :param key: The private key
- :type: string
-
- :param cert: The public
- :type: string
- """
- ifisinstance(xml,Document):
- dom=xml
- else:
- ifxml=='':
- raiseException('Empty string supplied as input')
-
- try:
- dom=parseString(xml)
- exceptException:
- raiseException('Error parsing xml string')
-
- xmlsec.initialize()
-
- # TODO the key and cert could be file descriptors instead
- # Load the private key.
- file_key=OneLogin_Saml2_Utils.write_temp_file(key)
- sign_key=xmlsec.Key.load(file_key.name,xmlsec.KeyDataFormatPem,None)
- file_key.close()
- # Add the certificate to the signature.
- file_cert=OneLogin_Saml2_Utils.write_temp_file(cert)
- sign_key.loadCert(file_cert.name,xmlsec.KeyDataFormatPem)
- file_cert.close()
-
- # Get the EntityDescriptor node we should sign.
- root_node=dom.firstChild
-
- # Sign the metadata with our private key.
- signature=Signature(xmlsec.TransformExclC14N,xmlsec.TransformRsaSha1)
- ref=signature.addReference(xmlsec.TransformSha1)
- ref.addTransform(xmlsec.TransformEnveloped)
-
- key_info=signature.ensureKeyInfo()
- key_info.addX509Data()
-
- dsig_ctx=xmlsec.DSigCtx()
- dsig_ctx.signKey=sign_key
- dsig_ctx.sign(signature)
-
- signature=tostring(signature).replace('ns0:','ds:').replace(':ns0',':ds')
- signature=parseString(signature).firstChild
-
- insert_before=root_node.getElementsByTagName('saml:Issuer')
- iflen(insert_before)>0:
- insert_before=insert_before[0].nextSibling
- else:
- insert_before=root_node.firstChild.nextSibling.nextSibling
- root_node.insertBefore(signature,insert_before)
-
- returndom.toxml()
-
- @staticmethod
-
[docs]defvalidate_sign(xml,cert=None,fingerprint=None):
- """
- Validates a signature (Message or Assertion).
-
- :param xml: The element we should validate
- :type: string | Document
-
- :param cert: The pubic cert
- :type: string
-
- :param fingerprint: The fingerprint of the public cert
- :type: string
- """
- ifisinstance(xml,Document):
- dom=etree.fromstring(xml.toxml())
- else:
- ifxml=='':
- raiseException('Empty string supplied as input')
-
- try:
- dom=etree.fromstring(xml)
- exceptException:
- raiseException('Error parsing xml string')
-
- xmlsec.initialize()
-
- # Find signature in the dom
- signature_node=OneLogin_Saml2_Utils.query(dom,'ds:Signature')[0]
-
- # Prepare context and load cert into it
- dsig_ctx=xmlsec.DSigCtx()
- sign_cert=X509.load_cert_string(str(cert),X509.FORMAT_PEM)
- pub_key=sign_cert.get_pubkey().get_rsa()
- sign_key=xmlsec.Key.loadMemory(pub_key.as_pem(cipher=None),
- xmlsec.KeyDataFormatPem)
- dsig_ctx.signKey=sign_key
-
- # Verify signature
- dsig_ctx.verify(signature_node)
-
-
-
-
-
-
-
-
-
Quick search
-
-
- Enter search terms or a module, class or function name.
-
')
- .appendTo($('#searchbox'));
- }
+ addTranslations: (catalog) => {
+ Object.assign(Documentation.TRANSLATIONS, catalog.messages);
+ Documentation.PLURAL_EXPR = new Function(
+ "n",
+ `return (${catalog.plural_expr})`
+ );
+ Documentation.LOCALE = catalog.locale;
},
/**
- * init the domain index toggle buttons
+ * helper function to focus on search bar
*/
- initIndexTable : function() {
- var togglers = $('img.toggler').click(function() {
- var src = $(this).attr('src');
- var idnum = $(this).attr('id').substr(7);
- $('tr.cg-' + idnum).toggle();
- if (src.substr(-9) == 'minus.png')
- $(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
- else
- $(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
- }).css('display', '');
- if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
- togglers.click();
- }
+ focusSearchBar: () => {
+ document.querySelectorAll("input[name=q]")[0]?.focus();
},
/**
- * helper function to hide the search marks again
+ * Initialise the domain index toggle buttons
*/
- hideSearchWords : function() {
- $('#searchbox .highlight-link').fadeOut(300);
- $('span.highlighted').removeMethod('highlighted');
+ initDomainIndexTable: () => {
+ const toggler = (el) => {
+ const idNumber = el.id.substr(7);
+ const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`);
+ if (el.src.substr(-9) === "minus.png") {
+ el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`;
+ toggledRows.forEach((el) => (el.style.display = "none"));
+ } else {
+ el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`;
+ toggledRows.forEach((el) => (el.style.display = ""));
+ }
+ };
+
+ const togglerElements = document.querySelectorAll("img.toggler");
+ togglerElements.forEach((el) =>
+ el.addEventListener("click", (event) => toggler(event.currentTarget))
+ );
+ togglerElements.forEach((el) => (el.style.display = ""));
+ if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler);
},
- /**
- * make the url absolute
- */
- makeURL : function(relativeURL) {
- return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
- },
+ initOnKeyListeners: () => {
+ // only install a listener if it is really needed
+ if (
+ !DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS &&
+ !DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS
+ )
+ return;
+
+ document.addEventListener("keydown", (event) => {
+ // bail for input elements
+ if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return;
+ // bail with special keys
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
+
+ if (!event.shiftKey) {
+ switch (event.key) {
+ case "ArrowLeft":
+ if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break;
+
+ const prevLink = document.querySelector('link[rel="prev"]');
+ if (prevLink && prevLink.href) {
+ window.location.href = prevLink.href;
+ event.preventDefault();
+ }
+ break;
+ case "ArrowRight":
+ if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break;
+
+ const nextLink = document.querySelector('link[rel="next"]');
+ if (nextLink && nextLink.href) {
+ window.location.href = nextLink.href;
+ event.preventDefault();
+ }
+ break;
+ }
+ }
- /**
- * get the current relative url
- */
- getCurrentURL : function() {
- var path = document.location.pathname;
- var parts = path.split(/\//);
- $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
- if (this == '..')
- parts.pop();
+ // some keyboard layouts may need Shift to get /
+ switch (event.key) {
+ case "/":
+ if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break;
+ Documentation.focusSearchBar();
+ event.preventDefault();
+ }
});
- var url = parts.join('/');
- return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
- }
+ },
};
// quick alias for translations
-_ = Documentation.gettext;
+const _ = Documentation.gettext;
-$(document).ready(function() {
- Documentation.init();
-});
+_ready(Documentation.init);
diff --git a/docs/saml2/_static/documentation_options.js b/docs/saml2/_static/documentation_options.js
new file mode 100644
index 00000000..2db8a09e
--- /dev/null
+++ b/docs/saml2/_static/documentation_options.js
@@ -0,0 +1,14 @@
+var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'),
+ VERSION: '1',
+ LANGUAGE: 'en',
+ COLLAPSE_INDEX: false,
+ BUILDER: 'html',
+ FILE_SUFFIX: '.html',
+ LINK_SUFFIX: '.html',
+ HAS_SOURCE: true,
+ SOURCELINK_SUFFIX: '.txt',
+ NAVIGATION_WITH_KEYS: false,
+ SHOW_SEARCH_SUMMARY: true,
+ ENABLE_SEARCH_SHORTCUTS: true,
+};
\ No newline at end of file
diff --git a/docs/saml2/_static/down-pressed.png b/docs/saml2/_static/down-pressed.png
deleted file mode 100644
index 6f7ad782..00000000
Binary files a/docs/saml2/_static/down-pressed.png and /dev/null differ
diff --git a/docs/saml2/_static/down.png b/docs/saml2/_static/down.png
deleted file mode 100644
index 3003a887..00000000
Binary files a/docs/saml2/_static/down.png and /dev/null differ
diff --git a/docs/saml2/_static/file.png b/docs/saml2/_static/file.png
index d18082e3..a858a410 100644
Binary files a/docs/saml2/_static/file.png and b/docs/saml2/_static/file.png differ
diff --git a/docs/saml2/_static/jquery.js b/docs/saml2/_static/jquery.js
index dc2f3dac..c4c6022f 100644
--- a/docs/saml2/_static/jquery.js
+++ b/docs/saml2/_static/jquery.js
@@ -1,9404 +1,2 @@
-/*!
- * jQuery JavaScript Library v1.7.2
- * http://jquery.com/
- *
- * Copyright 2011, John Resig
- * Dual licensed under the MIT or GPL Version 2 licenses.
- * http://jquery.org/license
- *
- * Includes Sizzle.js
- * http://sizzlejs.com/
- * Copyright 2011, The Dojo Foundation
- * Released under the MIT, BSD, and GPL Licenses.
- *
- * Date: Fri Jul 5 14:07:58 UTC 2013
- */
-(function( window, undefined ) {
-
-// Use the correct document accordingly with window argument (sandbox)
-var document = window.document,
- navigator = window.navigator,
- location = window.location;
-var jQuery = (function() {
-
-// Define a local copy of jQuery
-var jQuery = function( selector, context ) {
- // The jQuery object is actually just the init constructor 'enhanced'
- return new jQuery.fn.init( selector, context, rootjQuery );
- },
-
- // Map over jQuery in case of overwrite
- _jQuery = window.jQuery,
-
- // Map over the $ in case of overwrite
- _$ = window.$,
-
- // A central reference to the root jQuery(document)
- rootjQuery,
-
- // A simple way to check for HTML strings or ID strings
- // Prioritize #id over to avoid XSS via location.hash (#9521)
- quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
-
- // Check if a string has a non-whitespace character in it
- rnotwhite = /\S/,
-
- // Used for trimming whitespace
- trimLeft = /^\s+/,
- trimRight = /\s+$/,
-
- // Match a standalone tag
- rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
-
- // JSON RegExp
- rvalidchars = /^[\],:{}\s]*$/,
- rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
- rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
- rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
-
- // Useragent RegExp
- rwebkit = /(webkit)[ \/]([\w.]+)/,
- ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
- rmsie = /(msie) ([\w.]+)/,
- rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
-
- // Matches dashed string for camelizing
- rdashAlpha = /-([a-z]|[0-9])/ig,
- rmsPrefix = /^-ms-/,
-
- // Used by jQuery.camelCase as callback to replace()
- fcamelCase = function( all, letter ) {
- return ( letter + "" ).toUpperCase();
- },
-
- // Keep a UserAgent string for use with jQuery.browser
- userAgent = navigator.userAgent,
-
- // For matching the engine and version of the browser
- browserMatch,
-
- // The deferred used on DOM ready
- readyList,
-
- // The ready event handler
- DOMContentLoaded,
-
- // Save a reference to some core methods
- toString = Object.prototype.toString,
- hasOwn = Object.prototype.hasOwnProperty,
- push = Array.prototype.push,
- slice = Array.prototype.slice,
- trim = String.prototype.trim,
- indexOf = Array.prototype.indexOf,
-
- // [[Method]] -> type pairs
- class2type = {};
-
-jQuery.fn = jQuery.prototype = {
- constructor: jQuery,
- init: function( selector, context, rootjQuery ) {
- var match, elem, ret, doc;
-
- // Handle $(""), $(null), or $(undefined)
- if ( !selector ) {
- return this;
- }
-
- // Handle $(DOMElement)
- if ( selector.nodeType ) {
- this.context = this[0] = selector;
- this.length = 1;
- return this;
- }
-
- // The body element only exists once, optimize finding it
- if ( selector === "body" && !context && document.body ) {
- this.context = document;
- this[0] = document.body;
- this.selector = selector;
- this.length = 1;
- return this;
- }
-
- // Handle HTML strings
- if ( typeof selector === "string" ) {
- // Are we dealing with HTML string or an ID?
- if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
- // Assume that strings that start and end with <> are HTML and skip the regex check
- match = [ null, selector, null ];
-
- } else {
- match = quickExpr.exec( selector );
- }
-
- // Verify a match, and that no context was specified for #id
- if ( match && (match[1] || !context) ) {
-
- // HANDLE: $(html) -> $(array)
- if ( match[1] ) {
- context = context instanceof jQuery ? context[0] : context;
- doc = ( context ? context.ownerDocument || context : document );
-
- // If a single string is passed in and it's a single tag
- // just do a createElement and skip the rest
- ret = rsingleTag.exec( selector );
-
- if ( ret ) {
- if ( jQuery.isPlainObject( context ) ) {
- selector = [ document.createElement( ret[1] ) ];
- jQuery.fn.attr.call( selector, context, true );
-
- } else {
- selector = [ doc.createElement( ret[1] ) ];
- }
-
- } else {
- ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
- selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
- }
-
- return jQuery.merge( this, selector );
-
- // HANDLE: $("#id")
- } else {
- elem = document.getElementById( match[2] );
-
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- if ( elem && elem.parentNode ) {
- // Handle the case where IE and Opera return items
- // by name instead of ID
- if ( elem.id !== match[2] ) {
- return rootjQuery.find( selector );
- }
-
- // Otherwise, we inject the element directly into the jQuery object
- this.length = 1;
- this[0] = elem;
- }
-
- this.context = document;
- this.selector = selector;
- return this;
- }
-
- // HANDLE: $(expr, $(...))
- } else if ( !context || context.jquery ) {
- return ( context || rootjQuery ).find( selector );
-
- // HANDLE: $(expr, context)
- // (which is just equivalent to: $(context).find(expr)
- } else {
- return this.constructor( context ).find( selector );
- }
-
- // HANDLE: $(function)
- // Shortcut for document ready
- } else if ( jQuery.isFunction( selector ) ) {
- return rootjQuery.ready( selector );
- }
-
- if ( selector.selector !== undefined ) {
- this.selector = selector.selector;
- this.context = selector.context;
- }
-
- return jQuery.makeArray( selector, this );
- },
-
- // Start with an empty selector
- selector: "",
-
- // The current version of jQuery being used
- jquery: "1.7.2",
-
- // The default length of a jQuery object is 0
- length: 0,
-
- // The number of elements contained in the matched element set
- size: function() {
- return this.length;
- },
-
- toArray: function() {
- return slice.call( this, 0 );
- },
-
- // Get the Nth element in the matched element set OR
- // Get the whole matched element set as a clean array
- get: function( num ) {
- return num == null ?
-
- // Return a 'clean' array
- this.toArray() :
-
- // Return just the object
- ( num < 0 ? this[ this.length + num ] : this[ num ] );
- },
-
- // Take an array of elements and push it onto the stack
- // (returning the new matched element set)
- pushStack: function( elems, name, selector ) {
- // Build a new jQuery matched element set
- var ret = this.constructor();
-
- if ( jQuery.isArray( elems ) ) {
- push.apply( ret, elems );
-
- } else {
- jQuery.merge( ret, elems );
- }
-
- // Add the old object onto the stack (as a reference)
- ret.prevObject = this;
-
- ret.context = this.context;
-
- if ( name === "find" ) {
- ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
- } else if ( name ) {
- ret.selector = this.selector + "." + name + "(" + selector + ")";
- }
-
- // Return the newly-formed element set
- return ret;
- },
-
- // Execute a callback for every element in the matched set.
- // (You can seed the arguments with an array of args, but this is
- // only used internally.)
- each: function( callback, args ) {
- return jQuery.each( this, callback, args );
- },
-
- ready: function( fn ) {
- // Attach the listeners
- jQuery.bindReady();
-
- // Add the callback
- readyList.add( fn );
-
- return this;
- },
-
- eq: function( i ) {
- i = +i;
- return i === -1 ?
- this.slice( i ) :
- this.slice( i, i + 1 );
- },
-
- first: function() {
- return this.eq( 0 );
- },
-
- last: function() {
- return this.eq( -1 );
- },
-
- slice: function() {
- return this.pushStack( slice.apply( this, arguments ),
- "slice", slice.call(arguments).join(",") );
- },
-
- map: function( callback ) {
- return this.pushStack( jQuery.map(this, function( elem, i ) {
- return callback.call( elem, i, elem );
- }));
- },
-
- end: function() {
- return this.prevObject || this.constructor(null);
- },
-
- // For internal use only.
- // Behaves like an Array's method, not like a jQuery method.
- push: push,
- sort: [].sort,
- splice: [].splice
-};
-
-// Give the init function the jQuery prototype for later instantiation
-jQuery.fn.init.prototype = jQuery.fn;
-
-jQuery.extend = jQuery.fn.extend = function() {
- var options, name, src, copy, copyIsArray, clone,
- target = arguments[0] || {},
- i = 1,
- length = arguments.length,
- deep = false;
-
- // Handle a deep copy situation
- if ( typeof target === "boolean" ) {
- deep = target;
- target = arguments[1] || {};
- // skip the boolean and the target
- i = 2;
- }
-
- // Handle case when target is a string or something (possible in deep copy)
- if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
- target = {};
- }
-
- // extend jQuery itself if only one argument is passed
- if ( length === i ) {
- target = this;
- --i;
- }
-
- for ( ; i < length; i++ ) {
- // Only deal with non-null/undefined values
- if ( (options = arguments[ i ]) != null ) {
- // Extend the base object
- for ( name in options ) {
- src = target[ name ];
- copy = options[ name ];
-
- // Prevent never-ending loop
- if ( target === copy ) {
- continue;
- }
-
- // Recurse if we're merging plain objects or arrays
- if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
- if ( copyIsArray ) {
- copyIsArray = false;
- clone = src && jQuery.isArray(src) ? src : [];
-
- } else {
- clone = src && jQuery.isPlainObject(src) ? src : {};
- }
-
- // Never move original objects, clone them
- target[ name ] = jQuery.extend( deep, clone, copy );
-
- // Don't bring in undefined values
- } else if ( copy !== undefined ) {
- target[ name ] = copy;
- }
- }
- }
- }
-
- // Return the modified object
- return target;
-};
-
-jQuery.extend({
- noConflict: function( deep ) {
- if ( window.$ === jQuery ) {
- window.$ = _$;
- }
-
- if ( deep && window.jQuery === jQuery ) {
- window.jQuery = _jQuery;
- }
-
- return jQuery;
- },
-
- // Is the DOM ready to be used? Set to true once it occurs.
- isReady: false,
-
- // A counter to track how many items to wait for before
- // the ready event fires. See #6781
- readyWait: 1,
-
- // Hold (or release) the ready event
- holdReady: function( hold ) {
- if ( hold ) {
- jQuery.readyWait++;
- } else {
- jQuery.ready( true );
- }
- },
-
- // Handle when the DOM is ready
- ready: function( wait ) {
- // Either a released hold or an DOMready/load event and not yet ready
- if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
- // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
- if ( !document.body ) {
- return setTimeout( jQuery.ready, 1 );
- }
-
- // Remember that the DOM is ready
- jQuery.isReady = true;
-
- // If a normal DOM Ready event fired, decrement, and wait if need be
- if ( wait !== true && --jQuery.readyWait > 0 ) {
- return;
- }
-
- // If there are functions bound, to execute
- readyList.fireWith( document, [ jQuery ] );
-
- // Trigger any bound ready events
- if ( jQuery.fn.trigger ) {
- jQuery( document ).trigger( "ready" ).off( "ready" );
- }
- }
- },
-
- bindReady: function() {
- if ( readyList ) {
- return;
- }
-
- readyList = jQuery.Callbacks( "once memory" );
-
- // Catch cases where $(document).ready() is called after the
- // browser event has already occurred.
- if ( document.readyState === "complete" ) {
- // Handle it asynchronously to allow scripts the opportunity to delay ready
- return setTimeout( jQuery.ready, 1 );
- }
-
- // Mozilla, Opera and webkit nightlies currently support this event
- if ( document.addEventListener ) {
- // Use the handy event callback
- document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
-
- // A fallback to window.onload, that will always work
- window.addEventListener( "load", jQuery.ready, false );
-
- // If IE event model is used
- } else if ( document.attachEvent ) {
- // ensure firing before onload,
- // maybe late but safe also for iframes
- document.attachEvent( "onreadystatechange", DOMContentLoaded );
-
- // A fallback to window.onload, that will always work
- window.attachEvent( "onload", jQuery.ready );
-
- // If IE and not a frame
- // continually check to see if the document is ready
- var toplevel = false;
-
- try {
- toplevel = window.frameElement == null;
- } catch(e) {}
-
- if ( document.documentElement.doScroll && toplevel ) {
- doScrollCheck();
- }
- }
- },
-
- // See test/unit/core.js for details concerning isFunction.
- // Since version 1.3, DOM methods and functions like alert
- // aren't supported. They return false on IE (#2968).
- isFunction: function( obj ) {
- return jQuery.type(obj) === "function";
- },
-
- isArray: Array.isArray || function( obj ) {
- return jQuery.type(obj) === "array";
- },
-
- isWindow: function( obj ) {
- return obj != null && obj == obj.window;
- },
-
- isNumeric: function( obj ) {
- return !isNaN( parseFloat(obj) ) && isFinite( obj );
- },
-
- type: function( obj ) {
- return obj == null ?
- String( obj ) :
- class2type[ toString.call(obj) ] || "object";
- },
-
- isPlainObject: function( obj ) {
- // Must be an Object.
- // Because of IE, we also have to check the presence of the constructor property.
- // Make sure that DOM nodes and window objects don't pass through, as well
- if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
- return false;
- }
-
- try {
- // Not own constructor property must be Object
- if ( obj.constructor &&
- !hasOwn.call(obj, "constructor") &&
- !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
- return false;
- }
- } catch ( e ) {
- // IE8,9 Will throw exceptions on certain host objects #9897
- return false;
- }
-
- // Own properties are enumerated firstly, so to speed up,
- // if last one is own, then all properties are own.
-
- var key;
- for ( key in obj ) {}
-
- return key === undefined || hasOwn.call( obj, key );
- },
-
- isEmptyObject: function( obj ) {
- for ( var name in obj ) {
- return false;
- }
- return true;
- },
-
- error: function( msg ) {
- throw new Error( msg );
- },
-
- parseJSON: function( data ) {
- if ( typeof data !== "string" || !data ) {
- return null;
- }
-
- // Make sure leading/trailing whitespace is removed (IE can't handle it)
- data = jQuery.trim( data );
-
- // Attempt to parse using the native JSON parser first
- if ( window.JSON && window.JSON.parse ) {
- return window.JSON.parse( data );
- }
-
- // Make sure the incoming data is actual JSON
- // Logic borrowed from http://json.org/json2.js
- if ( rvalidchars.test( data.replace( rvalidescape, "@" )
- .replace( rvalidtokens, "]" )
- .replace( rvalidbraces, "")) ) {
-
- return ( new Function( "return " + data ) )();
-
- }
- jQuery.error( "Invalid JSON: " + data );
- },
-
- // Cross-browser xml parsing
- parseXML: function( data ) {
- if ( typeof data !== "string" || !data ) {
- return null;
- }
- var xml, tmp;
- try {
- if ( window.DOMParser ) { // Standard
- tmp = new DOMParser();
- xml = tmp.parseFromString( data , "text/xml" );
- } else { // IE
- xml = new ActiveXObject( "Microsoft.XMLDOM" );
- xml.async = "false";
- xml.loadXML( data );
- }
- } catch( e ) {
- xml = undefined;
- }
- if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
- jQuery.error( "Invalid XML: " + data );
- }
- return xml;
- },
-
- noop: function() {},
-
- // Evaluates a script in a global context
- // Workarounds based on findings by Jim Driscoll
- // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
- globalEval: function( data ) {
- if ( data && rnotwhite.test( data ) ) {
- // We use execScript on Internet Explorer
- // We use an anonymous function so that context is window
- // rather than jQuery in Firefox
- ( window.execScript || function( data ) {
- window[ "eval" ].call( window, data );
- } )( data );
- }
- },
-
- // Convert dashed to camelCase; used by the css and data modules
- // Microsoft forgot to hump their vendor prefix (#9572)
- camelCase: function( string ) {
- return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
- },
-
- nodeName: function( elem, name ) {
- return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
- },
-
- // args is for internal usage only
- each: function( object, callback, args ) {
- var name, i = 0,
- length = object.length,
- isObj = length === undefined || jQuery.isFunction( object );
-
- if ( args ) {
- if ( isObj ) {
- for ( name in object ) {
- if ( callback.apply( object[ name ], args ) === false ) {
- break;
- }
- }
- } else {
- for ( ; i < length; ) {
- if ( callback.apply( object[ i++ ], args ) === false ) {
- break;
- }
- }
- }
-
- // A special, fast, case for the most common use of each
- } else {
- if ( isObj ) {
- for ( name in object ) {
- if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
- break;
- }
- }
- } else {
- for ( ; i < length; ) {
- if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
- break;
- }
- }
- }
- }
-
- return object;
- },
-
- // Use native String.trim function wherever possible
- trim: trim ?
- function( text ) {
- return text == null ?
- "" :
- trim.call( text );
- } :
-
- // Otherwise use our own trimming functionality
- function( text ) {
- return text == null ?
- "" :
- text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
- },
-
- // results is for internal usage only
- makeArray: function( array, results ) {
- var ret = results || [];
-
- if ( array != null ) {
- // The window, strings (and functions) also have 'length'
- // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
- var type = jQuery.type( array );
-
- if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
- push.call( ret, array );
- } else {
- jQuery.merge( ret, array );
- }
- }
-
- return ret;
- },
-
- inArray: function( elem, array, i ) {
- var len;
-
- if ( array ) {
- if ( indexOf ) {
- return indexOf.call( array, elem, i );
- }
-
- len = array.length;
- i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
-
- for ( ; i < len; i++ ) {
- // Skip accessing in sparse arrays
- if ( i in array && array[ i ] === elem ) {
- return i;
- }
- }
- }
-
- return -1;
- },
-
- merge: function( first, second ) {
- var i = first.length,
- j = 0;
-
- if ( typeof second.length === "number" ) {
- for ( var l = second.length; j < l; j++ ) {
- first[ i++ ] = second[ j ];
- }
-
- } else {
- while ( second[j] !== undefined ) {
- first[ i++ ] = second[ j++ ];
- }
- }
-
- first.length = i;
-
- return first;
- },
-
- grep: function( elems, callback, inv ) {
- var ret = [], retVal;
- inv = !!inv;
-
- // Go through the array, only saving the items
- // that pass the validator function
- for ( var i = 0, length = elems.length; i < length; i++ ) {
- retVal = !!callback( elems[ i ], i );
- if ( inv !== retVal ) {
- ret.push( elems[ i ] );
- }
- }
-
- return ret;
- },
-
- // arg is for internal usage only
- map: function( elems, callback, arg ) {
- var value, key, ret = [],
- i = 0,
- length = elems.length,
- // jquery objects are treated as arrays
- isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
-
- // Go through the array, translating each of the items to their
- if ( isArray ) {
- for ( ; i < length; i++ ) {
- value = callback( elems[ i ], i, arg );
-
- if ( value != null ) {
- ret[ ret.length ] = value;
- }
- }
-
- // Go through every key on the object,
- } else {
- for ( key in elems ) {
- value = callback( elems[ key ], key, arg );
-
- if ( value != null ) {
- ret[ ret.length ] = value;
- }
- }
- }
-
- // Flatten any nested arrays
- return ret.concat.apply( [], ret );
- },
-
- // A global GUID counter for objects
- guid: 1,
-
- // Bind a function to a context, optionally partially applying any
- // arguments.
- proxy: function( fn, context ) {
- if ( typeof context === "string" ) {
- var tmp = fn[ context ];
- context = fn;
- fn = tmp;
- }
-
- // Quick check to determine if target is callable, in the spec
- // this throws a TypeError, but we will just return undefined.
- if ( !jQuery.isFunction( fn ) ) {
- return undefined;
- }
-
- // Simulated bind
- var args = slice.call( arguments, 2 ),
- proxy = function() {
- return fn.apply( context, args.concat( slice.call( arguments ) ) );
- };
-
- // Set the guid of unique handler to the same of original handler, so it can be removed
- proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
-
- return proxy;
- },
-
- // Mutifunctional method to get and set values to a collection
- // The value/s can optionally be executed if it's a function
- access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
- var exec,
- bulk = key == null,
- i = 0,
- length = elems.length;
-
- // Sets many values
- if ( key && typeof key === "object" ) {
- for ( i in key ) {
- jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
- }
- chainable = 1;
-
- // Sets one value
- } else if ( value !== undefined ) {
- // Optionally, function values get executed if exec is true
- exec = pass === undefined && jQuery.isFunction( value );
-
- if ( bulk ) {
- // Bulk operations only iterate when executing function values
- if ( exec ) {
- exec = fn;
- fn = function( elem, key, value ) {
- return exec.call( jQuery( elem ), value );
- };
-
- // Otherwise they run against the entire set
- } else {
- fn.call( elems, value );
- fn = null;
- }
- }
-
- if ( fn ) {
- for (; i < length; i++ ) {
- fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
- }
- }
-
- chainable = 1;
- }
-
- return chainable ?
- elems :
-
- // Gets
- bulk ?
- fn.call( elems ) :
- length ? fn( elems[0], key ) : emptyGet;
- },
-
- now: function() {
- return ( new Date() ).getTime();
- },
-
- // Use of jQuery.browser is frowned upon.
- // More details: http://docs.jquery.com/Utilities/jQuery.browser
- uaMatch: function( ua ) {
- ua = ua.toLowerCase();
-
- var match = rwebkit.exec( ua ) ||
- ropera.exec( ua ) ||
- rmsie.exec( ua ) ||
- ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
- [];
-
- return { browser: match[1] || "", version: match[2] || "0" };
- },
-
- sub: function() {
- function jQuerySub( selector, context ) {
- return new jQuerySub.fn.init( selector, context );
- }
- jQuery.extend( true, jQuerySub, this );
- jQuerySub.superclass = this;
- jQuerySub.fn = jQuerySub.prototype = this();
- jQuerySub.fn.constructor = jQuerySub;
- jQuerySub.sub = this.sub;
- jQuerySub.fn.init = function init( selector, context ) {
- if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
- context = jQuerySub( context );
- }
-
- return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
- };
- jQuerySub.fn.init.prototype = jQuerySub.fn;
- var rootjQuerySub = jQuerySub(document);
- return jQuerySub;
- },
-
- browser: {}
-});
-
-// Populate the class2type map
-jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
- class2type[ "[object " + name + "]" ] = name.toLowerCase();
-});
-
-browserMatch = jQuery.uaMatch( userAgent );
-if ( browserMatch.browser ) {
- jQuery.browser[ browserMatch.browser ] = true;
- jQuery.browser.version = browserMatch.version;
-}
-
-// Deprecated, use jQuery.browser.webkit instead
-if ( jQuery.browser.webkit ) {
- jQuery.browser.safari = true;
-}
-
-// IE doesn't match non-breaking spaces with \s
-if ( rnotwhite.test( "\xA0" ) ) {
- trimLeft = /^[\s\xA0]+/;
- trimRight = /[\s\xA0]+$/;
-}
-
-// All jQuery objects should point back to these
-rootjQuery = jQuery(document);
-
-// Cleanup functions for the document ready method
-if ( document.addEventListener ) {
- DOMContentLoaded = function() {
- document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
- jQuery.ready();
- };
-
-} else if ( document.attachEvent ) {
- DOMContentLoaded = function() {
- // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
- if ( document.readyState === "complete" ) {
- document.detachEvent( "onreadystatechange", DOMContentLoaded );
- jQuery.ready();
- }
- };
-}
-
-// The DOM ready check for Internet Explorer
-function doScrollCheck() {
- if ( jQuery.isReady ) {
- return;
- }
-
- try {
- // If IE is used, use the trick by Diego Perini
- // http://javascript.nwbox.com/IEContentLoaded/
- document.documentElement.doScroll("left");
- } catch(e) {
- setTimeout( doScrollCheck, 1 );
- return;
- }
-
- // and execute any waiting functions
- jQuery.ready();
-}
-
-return jQuery;
-
-})();
-
-
-// String to Object flags format cache
-var flagsCache = {};
-
-// Convert String-formatted flags into Object-formatted ones and store in cache
-function createFlags( flags ) {
- var object = flagsCache[ flags ] = {},
- i, length;
- flags = flags.split( /\s+/ );
- for ( i = 0, length = flags.length; i < length; i++ ) {
- object[ flags[i] ] = true;
- }
- return object;
-}
-
-/*
- * Create a callback list using the following parameters:
- *
- * flags: an optional list of space-separated flags that will change how
- * the callback list behaves
- *
- * By default a callback list will act like an event callback list and can be
- * "fired" multiple times.
- *
- * Possible flags:
- *
- * once: will ensure the callback list can only be fired once (like a Deferred)
- *
- * memory: will keep track of previous values and will call any callback added
- * after the list has been fired right away with the latest "memorized"
- * values (like a Deferred)
- *
- * unique: will ensure a callback can only be added once (no duplicate in the list)
- *
- * stopOnFalse: interrupt callings when a callback returns false
- *
- */
-jQuery.Callbacks = function( flags ) {
-
- // Convert flags from String-formatted to Object-formatted
- // (we check in cache first)
- flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
-
- var // Actual callback list
- list = [],
- // Stack of fire calls for repeatable lists
- stack = [],
- // Last fire value (for non-forgettable lists)
- memory,
- // Flag to know if list was already fired
- fired,
- // Flag to know if list is currently firing
- firing,
- // First callback to fire (used internally by add and fireWith)
- firingStart,
- // End of the loop when firing
- firingLength,
- // Index of currently firing callback (modified by remove if needed)
- firingIndex,
- // Add one or several callbacks to the list
- add = function( args ) {
- var i,
- length,
- elem,
- type,
- actual;
- for ( i = 0, length = args.length; i < length; i++ ) {
- elem = args[ i ];
- type = jQuery.type( elem );
- if ( type === "array" ) {
- // Inspect recursively
- add( elem );
- } else if ( type === "function" ) {
- // Add if not in unique mode and callback is not in
- if ( !flags.unique || !self.has( elem ) ) {
- list.push( elem );
- }
- }
- }
- },
- // Fire callbacks
- fire = function( context, args ) {
- args = args || [];
- memory = !flags.memory || [ context, args ];
- fired = true;
- firing = true;
- firingIndex = firingStart || 0;
- firingStart = 0;
- firingLength = list.length;
- for ( ; list && firingIndex < firingLength; firingIndex++ ) {
- if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
- memory = true; // Mark as halted
- break;
- }
- }
- firing = false;
- if ( list ) {
- if ( !flags.once ) {
- if ( stack && stack.length ) {
- memory = stack.shift();
- self.fireWith( memory[ 0 ], memory[ 1 ] );
- }
- } else if ( memory === true ) {
- self.disable();
- } else {
- list = [];
- }
- }
- },
- // Actual Callbacks object
- self = {
- // Add a callback or a collection of callbacks to the list
- add: function() {
- if ( list ) {
- var length = list.length;
- add( arguments );
- // Do we need to add the callbacks to the
- // current firing batch?
- if ( firing ) {
- firingLength = list.length;
- // With memory, if we're not firing then
- // we should call right away, unless previous
- // firing was halted (stopOnFalse)
- } else if ( memory && memory !== true ) {
- firingStart = length;
- fire( memory[ 0 ], memory[ 1 ] );
- }
- }
- return this;
- },
- // Remove a callback from the list
- remove: function() {
- if ( list ) {
- var args = arguments,
- argIndex = 0,
- argLength = args.length;
- for ( ; argIndex < argLength ; argIndex++ ) {
- for ( var i = 0; i < list.length; i++ ) {
- if ( args[ argIndex ] === list[ i ] ) {
- // Handle firingIndex and firingLength
- if ( firing ) {
- if ( i <= firingLength ) {
- firingLength--;
- if ( i <= firingIndex ) {
- firingIndex--;
- }
- }
- }
- // Remove the element
- list.splice( i--, 1 );
- // If we have some unicity property then
- // we only need to do this once
- if ( flags.unique ) {
- break;
- }
- }
- }
- }
- }
- return this;
- },
- // Control if a given callback is in the list
- has: function( fn ) {
- if ( list ) {
- var i = 0,
- length = list.length;
- for ( ; i < length; i++ ) {
- if ( fn === list[ i ] ) {
- return true;
- }
- }
- }
- return false;
- },
- // Remove all callbacks from the list
- empty: function() {
- list = [];
- return this;
- },
- // Have the list do nothing anymore
- disable: function() {
- list = stack = memory = undefined;
- return this;
- },
- // Is it disabled?
- disabled: function() {
- return !list;
- },
- // Lock the list in its current state
- lock: function() {
- stack = undefined;
- if ( !memory || memory === true ) {
- self.disable();
- }
- return this;
- },
- // Is it locked?
- locked: function() {
- return !stack;
- },
- // Call all callbacks with the given context and arguments
- fireWith: function( context, args ) {
- if ( stack ) {
- if ( firing ) {
- if ( !flags.once ) {
- stack.push( [ context, args ] );
- }
- } else if ( !( flags.once && memory ) ) {
- fire( context, args );
- }
- }
- return this;
- },
- // Call all the callbacks with the given arguments
- fire: function() {
- self.fireWith( this, arguments );
- return this;
- },
- // To know if the callbacks have already been called at least once
- fired: function() {
- return !!fired;
- }
- };
-
- return self;
-};
-
-
-
-
-var // Static reference to slice
- sliceDeferred = [].slice;
-
-jQuery.extend({
-
- Deferred: function( func ) {
- var doneList = jQuery.Callbacks( "once memory" ),
- failList = jQuery.Callbacks( "once memory" ),
- progressList = jQuery.Callbacks( "memory" ),
- state = "pending",
- lists = {
- resolve: doneList,
- reject: failList,
- notify: progressList
- },
- promise = {
- done: doneList.add,
- fail: failList.add,
- progress: progressList.add,
-
- state: function() {
- return state;
- },
-
- // Deprecated
- isResolved: doneList.fired,
- isRejected: failList.fired,
-
- then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
- deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
- return this;
- },
- always: function() {
- deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
- return this;
- },
- pipe: function( fnDone, fnFail, fnProgress ) {
- return jQuery.Deferred(function( newDefer ) {
- jQuery.each( {
- done: [ fnDone, "resolve" ],
- fail: [ fnFail, "reject" ],
- progress: [ fnProgress, "notify" ]
- }, function( handler, data ) {
- var fn = data[ 0 ],
- action = data[ 1 ],
- returned;
- if ( jQuery.isFunction( fn ) ) {
- deferred[ handler ](function() {
- returned = fn.apply( this, arguments );
- if ( returned && jQuery.isFunction( returned.promise ) ) {
- returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
- } else {
- newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
- }
- });
- } else {
- deferred[ handler ]( newDefer[ action ] );
- }
- });
- }).promise();
- },
- // Get a promise for this deferred
- // If obj is provided, the promise aspect is added to the object
- promise: function( obj ) {
- if ( obj == null ) {
- obj = promise;
- } else {
- for ( var key in promise ) {
- obj[ key ] = promise[ key ];
- }
- }
- return obj;
- }
- },
- deferred = promise.promise({}),
- key;
-
- for ( key in lists ) {
- deferred[ key ] = lists[ key ].fire;
- deferred[ key + "With" ] = lists[ key ].fireWith;
- }
-
- // Handle state
- deferred.done( function() {
- state = "resolved";
- }, failList.disable, progressList.lock ).fail( function() {
- state = "rejected";
- }, doneList.disable, progressList.lock );
-
- // Call given func if any
- if ( func ) {
- func.call( deferred, deferred );
- }
-
- // All done!
- return deferred;
- },
-
- // Deferred helper
- when: function( firstParam ) {
- var args = sliceDeferred.call( arguments, 0 ),
- i = 0,
- length = args.length,
- pValues = new Array( length ),
- count = length,
- pCount = length,
- deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
- firstParam :
- jQuery.Deferred(),
- promise = deferred.promise();
- function resolveFunc( i ) {
- return function( value ) {
- args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
- if ( !( --count ) ) {
- deferred.resolveWith( deferred, args );
- }
- };
- }
- function progressFunc( i ) {
- return function( value ) {
- pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
- deferred.notifyWith( promise, pValues );
- };
- }
- if ( length > 1 ) {
- for ( ; i < length; i++ ) {
- if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
- args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
- } else {
- --count;
- }
- }
- if ( !count ) {
- deferred.resolveWith( deferred, args );
- }
- } else if ( deferred !== firstParam ) {
- deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
- }
- return promise;
- }
-});
-
-
-
-
-jQuery.support = (function() {
-
- var support,
- all,
- a,
- select,
- opt,
- input,
- fragment,
- tds,
- events,
- eventName,
- i,
- isSupported,
- div = document.createElement( "div" ),
- documentElement = document.documentElement;
-
- // Preliminary tests
- div.setAttribute("className", "t");
- div.innerHTML = "
a";
-
- all = div.getElementsByTagName( "*" );
- a = div.getElementsByTagName( "a" )[ 0 ];
-
- // Can't get basic test support
- if ( !all || !all.length || !a ) {
- return {};
- }
-
- // First batch of supports tests
- select = document.createElement( "select" );
- opt = select.appendChild( document.createElement("option") );
- input = div.getElementsByTagName( "input" )[ 0 ];
-
- support = {
- // IE strips leading whitespace when .innerHTML is used
- leadingWhitespace: ( div.firstChild.nodeType === 3 ),
-
- // Make sure that tbody elements aren't automatically inserted
- // IE will insert them into empty tables
- tbody: !div.getElementsByTagName("tbody").length,
-
- // Make sure that link elements get serialized correctly by innerHTML
- // This requires a wrapper element in IE
- htmlSerialize: !!div.getElementsByTagName("link").length,
-
- // Get the style information from getAttribute
- // (IE uses .cssText instead)
- style: /top/.test( a.getAttribute("style") ),
-
- // Make sure that URLs aren't manipulated
- // (IE normalizes it by default)
- hrefNormalized: ( a.getAttribute("href") === "/a" ),
-
- // Make sure that element opacity exists
- // (IE uses filter instead)
- // Use a regex to work around a WebKit issue. See #5145
- opacity: /^0.55/.test( a.style.opacity ),
-
- // Verify style float existence
- // (IE uses styleFloat instead of cssFloat)
- cssFloat: !!a.style.cssFloat,
-
- // Make sure that if no value is specified for a checkbox
- // that it defaults to "on".
- // (WebKit defaults to "" instead)
- checkOn: ( input.value === "on" ),
-
- // Make sure that a selected-by-default option has a working selected property.
- // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
- optSelected: opt.selected,
-
- // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
- getSetAttribute: div.className !== "t",
-
- // Tests for enctype support on a form(#6743)
- enctype: !!document.createElement("form").enctype,
-
- // Makes sure cloning an html5 element does not cause problems
- // Where outerHTML is undefined, this still works
- html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>",
-
- // Will be defined later
- submitBubbles: true,
- changeBubbles: true,
- focusinBubbles: false,
- deleteExpando: true,
- noCloneEvent: true,
- inlineBlockNeedsLayout: false,
- shrinkWrapBlocks: false,
- reliableMarginRight: true,
- pixelMargin: true
- };
-
- // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
- jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
-
- // Make sure checked status is properly cloned
- input.checked = true;
- support.noCloneChecked = input.cloneNode( true ).checked;
-
- // Make sure that the options inside disabled selects aren't marked as disabled
- // (WebKit marks them as disabled)
- select.disabled = true;
- support.optDisabled = !opt.disabled;
-
- // Test to see if it's possible to delete an expando from an element
- // Fails in Internet Explorer
- try {
- delete div.test;
- } catch( e ) {
- support.deleteExpando = false;
- }
-
- if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
- div.attachEvent( "onclick", function() {
- // Cloning a node shouldn't copy over any
- // bound event handlers (IE does this)
- support.noCloneEvent = false;
- });
- div.cloneNode( true ).fireEvent( "onclick" );
- }
-
- // Check if a radio maintains its value
- // after being appended to the DOM
- input = document.createElement("input");
- input.value = "t";
- input.setAttribute("type", "radio");
- support.radioValue = input.value === "t";
-
- input.setAttribute("checked", "checked");
-
- // #11217 - WebKit loses check when the name is after the checked attribute
- input.setAttribute( "name", "t" );
-
- div.appendChild( input );
- fragment = document.createDocumentFragment();
- fragment.appendChild( div.lastChild );
-
- // WebKit doesn't clone checked state correctly in fragments
- support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
-
- // Check if a disconnected checkbox will retain its checked
- // value of true after appended to the DOM (IE6/7)
- support.appendChecked = input.checked;
-
- fragment.removeChild( input );
- fragment.appendChild( div );
-
- // Technique from Juriy Zaytsev
- // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
- // We only care about the case where non-standard event systems
- // are used, namely in IE. Short-circuiting here helps us to
- // avoid an eval call (in setAttribute) which can cause CSP
- // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
- if ( div.attachEvent ) {
- for ( i in {
- submit: 1,
- change: 1,
- focusin: 1
- }) {
- eventName = "on" + i;
- isSupported = ( eventName in div );
- if ( !isSupported ) {
- div.setAttribute( eventName, "return;" );
- isSupported = ( typeof div[ eventName ] === "function" );
- }
- support[ i + "Bubbles" ] = isSupported;
- }
- }
-
- fragment.removeChild( div );
-
- // Null elements to avoid leaks in IE
- fragment = select = opt = div = input = null;
-
- // Run tests that need a body at doc ready
- jQuery(function() {
- var container, outer, inner, table, td, offsetSupport,
- marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
- paddingMarginBorderVisibility, paddingMarginBorder,
- body = document.getElementsByTagName("body")[0];
-
- if ( !body ) {
- // Return for frameset docs that don't have a body
- return;
- }
-
- conMarginTop = 1;
- paddingMarginBorder = "padding:0;margin:0;border:";
- positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
- paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
- style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
- html = "
" +
- "
" +
- "
";
-
- container = document.createElement("div");
- container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
- body.insertBefore( container, body.firstChild );
-
- // Construct the test element
- div = document.createElement("div");
- container.appendChild( div );
-
- // Check if table cells still have offsetWidth/Height when they are set
- // to display:none and there are still other visible table cells in a
- // table row; if so, offsetWidth/Height are not reliable for use when
- // determining if an element has been hidden directly using
- // display:none (it is still safe to use offsets if a parent element is
- // hidden; don safety goggles and see bug #4512 for more information).
- // (only IE 8 fails this test)
- div.innerHTML = "
t
";
- tds = div.getElementsByTagName( "td" );
- isSupported = ( tds[ 0 ].offsetHeight === 0 );
-
- tds[ 0 ].style.display = "";
- tds[ 1 ].style.display = "none";
-
- // Check if empty table cells still have offsetWidth/Height
- // (IE <= 8 fail this test)
- support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
-
- // Check if div with explicit width and no margin-right incorrectly
- // gets computed margin-right based on width of container. For more
- // info see bug #3333
- // Fails in WebKit before Feb 2011 nightlies
- // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
- if ( window.getComputedStyle ) {
- div.innerHTML = "";
- marginDiv = document.createElement( "div" );
- marginDiv.style.width = "0";
- marginDiv.style.marginRight = "0";
- div.style.width = "2px";
- div.appendChild( marginDiv );
- support.reliableMarginRight =
- ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
- }
-
- if ( typeof div.style.zoom !== "undefined" ) {
- // Check if natively block-level elements act like inline-block
- // elements when setting their display to 'inline' and giving
- // them layout
- // (IE < 8 does this)
- div.innerHTML = "";
- div.style.width = div.style.padding = "1px";
- div.style.border = 0;
- div.style.overflow = "hidden";
- div.style.display = "inline";
- div.style.zoom = 1;
- support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
-
- // Check if elements with layout shrink-wrap their children
- // (IE 6 does this)
- div.style.display = "block";
- div.style.overflow = "visible";
- div.innerHTML = "";
- support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
- }
-
- div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
- div.innerHTML = html;
-
- outer = div.firstChild;
- inner = outer.firstChild;
- td = outer.nextSibling.firstChild.firstChild;
-
- offsetSupport = {
- doesNotAddBorder: ( inner.offsetTop !== 5 ),
- doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
- };
-
- inner.style.position = "fixed";
- inner.style.top = "20px";
-
- // safari subtracts parent border width here which is 5px
- offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
- inner.style.position = inner.style.top = "";
-
- outer.style.overflow = "hidden";
- outer.style.position = "relative";
-
- offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
- offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
-
- if ( window.getComputedStyle ) {
- div.style.marginTop = "1%";
- support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
- }
-
- if ( typeof container.style.zoom !== "undefined" ) {
- container.style.zoom = 1;
- }
-
- body.removeChild( container );
- marginDiv = div = container = null;
-
- jQuery.extend( support, offsetSupport );
- });
-
- return support;
-})();
-
-
-
-
-var rbrace = /^(?:\{.*\}|\[.*\])$/,
- rmultiDash = /([A-Z])/g;
-
-jQuery.extend({
- cache: {},
-
- // Please use with caution
- uuid: 0,
-
- // Unique for each copy of jQuery on the page
- // Non-digits removed to match rinlinejQuery
- expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
-
- // The following elements throw uncatchable exceptions if you
- // attempt to add expando properties to them.
- noData: {
- "embed": true,
- // Ban all objects except for Flash (which handle expandos)
- "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
- "applet": true
- },
-
- hasData: function( elem ) {
- elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
- return !!elem && !isEmptyDataObject( elem );
- },
-
- data: function( elem, name, data, pvt /* Internal Use Only */ ) {
- if ( !jQuery.acceptData( elem ) ) {
- return;
- }
-
- var privateCache, thisCache, ret,
- internalKey = jQuery.expando,
- getByName = typeof name === "string",
-
- // We have to handle DOM nodes and JS objects differently because IE6-7
- // can't GC object references properly across the DOM-JS boundary
- isNode = elem.nodeType,
-
- // Only DOM nodes need the global jQuery cache; JS object data is
- // attached directly to the object so GC can occur automatically
- cache = isNode ? jQuery.cache : elem,
-
- // Only defining an ID for JS objects if its cache already exists allows
- // the code to shortcut on the same path as a DOM node with no cache
- id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
- isEvents = name === "events";
-
- // Avoid doing any more work than we need to when trying to get data on an
- // object that has no data at all
- if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
- return;
- }
-
- if ( !id ) {
- // Only DOM nodes need a new unique ID for each element since their data
- // ends up in the global cache
- if ( isNode ) {
- elem[ internalKey ] = id = ++jQuery.uuid;
- } else {
- id = internalKey;
- }
- }
-
- if ( !cache[ id ] ) {
- cache[ id ] = {};
-
- // Avoids exposing jQuery metadata on plain JS objects when the object
- // is serialized using JSON.stringify
- if ( !isNode ) {
- cache[ id ].toJSON = jQuery.noop;
- }
- }
-
- // An object can be passed to jQuery.data instead of a key/value pair; this gets
- // shallow copied over onto the existing cache
- if ( typeof name === "object" || typeof name === "function" ) {
- if ( pvt ) {
- cache[ id ] = jQuery.extend( cache[ id ], name );
- } else {
- cache[ id ].data = jQuery.extend( cache[ id ].data, name );
- }
- }
-
- privateCache = thisCache = cache[ id ];
-
- // jQuery data() is stored in a separate object inside the object's internal data
- // cache in order to avoid key collisions between internal data and user-defined
- // data.
- if ( !pvt ) {
- if ( !thisCache.data ) {
- thisCache.data = {};
- }
-
- thisCache = thisCache.data;
- }
-
- if ( data !== undefined ) {
- thisCache[ jQuery.camelCase( name ) ] = data;
- }
-
- // Users should not attempt to inspect the internal events object using jQuery.data,
- // it is undocumented and subject to change. But does anyone listen? No.
- if ( isEvents && !thisCache[ name ] ) {
- return privateCache.events;
- }
-
- // Check for both converted-to-camel and non-converted data property names
- // If a data property was specified
- if ( getByName ) {
-
- // First Try to find as-is property data
- ret = thisCache[ name ];
-
- // Test for null|undefined property data
- if ( ret == null ) {
-
- // Try to find the camelCased property
- ret = thisCache[ jQuery.camelCase( name ) ];
- }
- } else {
- ret = thisCache;
- }
-
- return ret;
- },
-
- removeData: function( elem, name, pvt /* Internal Use Only */ ) {
- if ( !jQuery.acceptData( elem ) ) {
- return;
- }
-
- var thisCache, i, l,
-
- // Reference to internal data cache key
- internalKey = jQuery.expando,
-
- isNode = elem.nodeType,
-
- // See jQuery.data for more information
- cache = isNode ? jQuery.cache : elem,
-
- // See jQuery.data for more information
- id = isNode ? elem[ internalKey ] : internalKey;
-
- // If there is already no cache entry for this object, there is no
- // purpose in continuing
- if ( !cache[ id ] ) {
- return;
- }
-
- if ( name ) {
-
- thisCache = pvt ? cache[ id ] : cache[ id ].data;
-
- if ( thisCache ) {
-
- // Support array or space separated string names for data keys
- if ( !jQuery.isArray( name ) ) {
-
- // try the string as a key before any manipulation
- if ( name in thisCache ) {
- name = [ name ];
- } else {
-
- // split the camel cased version by spaces unless a key with the spaces exists
- name = jQuery.camelCase( name );
- if ( name in thisCache ) {
- name = [ name ];
- } else {
- name = name.split( " " );
- }
- }
- }
-
- for ( i = 0, l = name.length; i < l; i++ ) {
- delete thisCache[ name[i] ];
- }
-
- // If there is no data left in the cache, we want to continue
- // and let the cache object itself get destroyed
- if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
- return;
- }
- }
- }
-
- // See jQuery.data for more information
- if ( !pvt ) {
- delete cache[ id ].data;
-
- // Don't destroy the parent cache unless the internal data object
- // had been the only thing left in it
- if ( !isEmptyDataObject(cache[ id ]) ) {
- return;
- }
- }
-
- // Browsers that fail expando deletion also refuse to delete expandos on
- // the window, but it will allow it on all other JS objects; other browsers
- // don't care
- // Ensure that `cache` is not a window object #10080
- if ( jQuery.support.deleteExpando || !cache.setInterval ) {
- delete cache[ id ];
- } else {
- cache[ id ] = null;
- }
-
- // We destroyed the cache and need to eliminate the expando on the node to avoid
- // false lookups in the cache for entries that no longer exist
- if ( isNode ) {
- // IE does not allow us to delete expando properties from nodes,
- // nor does it have a removeAttribute function on Document nodes;
- // we must handle all of these cases
- if ( jQuery.support.deleteExpando ) {
- delete elem[ internalKey ];
- } else if ( elem.removeAttribute ) {
- elem.removeAttribute( internalKey );
- } else {
- elem[ internalKey ] = null;
- }
- }
- },
-
- // For internal use only.
- _data: function( elem, name, data ) {
- return jQuery.data( elem, name, data, true );
- },
-
- // A method for determining if a DOM node can handle the data expando
- acceptData: function( elem ) {
- if ( elem.nodeName ) {
- var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
-
- if ( match ) {
- return !(match === true || elem.getAttribute("classid") !== match);
- }
- }
-
- return true;
- }
-});
-
-jQuery.fn.extend({
- data: function( key, value ) {
- var parts, part, attr, name, l,
- elem = this[0],
- i = 0,
- data = null;
-
- // Gets all values
- if ( key === undefined ) {
- if ( this.length ) {
- data = jQuery.data( elem );
-
- if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
- attr = elem.attributes;
- for ( l = attr.length; i < l; i++ ) {
- name = attr[i].name;
-
- if ( name.indexOf( "data-" ) === 0 ) {
- name = jQuery.camelCase( name.substring(5) );
-
- dataAttr( elem, name, data[ name ] );
- }
- }
- jQuery._data( elem, "parsedAttrs", true );
- }
- }
-
- return data;
- }
-
- // Sets multiple values
- if ( typeof key === "object" ) {
- return this.each(function() {
- jQuery.data( this, key );
- });
- }
-
- parts = key.split( ".", 2 );
- parts[1] = parts[1] ? "." + parts[1] : "";
- part = parts[1] + "!";
-
- return jQuery.access( this, function( value ) {
-
- if ( value === undefined ) {
- data = this.triggerHandler( "getData" + part, [ parts[0] ] );
-
- // Try to fetch any internally stored data first
- if ( data === undefined && elem ) {
- data = jQuery.data( elem, key );
- data = dataAttr( elem, key, data );
- }
-
- return data === undefined && parts[1] ?
- this.data( parts[0] ) :
- data;
- }
-
- parts[1] = value;
- this.each(function() {
- var self = jQuery( this );
-
- self.triggerHandler( "setData" + part, parts );
- jQuery.data( this, key, value );
- self.triggerHandler( "changeData" + part, parts );
- });
- }, null, value, arguments.length > 1, null, false );
- },
-
- removeData: function( key ) {
- return this.each(function() {
- jQuery.removeData( this, key );
- });
- }
-});
-
-function dataAttr( elem, key, data ) {
- // If nothing was found internally, try to fetch any
- // data from the HTML5 data-* attribute
- if ( data === undefined && elem.nodeType === 1 ) {
-
- var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
-
- data = elem.getAttribute( name );
-
- if ( typeof data === "string" ) {
- try {
- data = data === "true" ? true :
- data === "false" ? false :
- data === "null" ? null :
- jQuery.isNumeric( data ) ? +data :
- rbrace.test( data ) ? jQuery.parseJSON( data ) :
- data;
- } catch( e ) {}
-
- // Make sure we set the data so it isn't changed later
- jQuery.data( elem, key, data );
-
- } else {
- data = undefined;
- }
- }
-
- return data;
-}
-
-// checks a cache object for emptiness
-function isEmptyDataObject( obj ) {
- for ( var name in obj ) {
-
- // if the public data object is empty, the private is still empty
- if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
- continue;
- }
- if ( name !== "toJSON" ) {
- return false;
- }
- }
-
- return true;
-}
-
-
-
-
-function handleQueueMarkDefer( elem, type, src ) {
- var deferDataKey = type + "defer",
- queueDataKey = type + "queue",
- markDataKey = type + "mark",
- defer = jQuery._data( elem, deferDataKey );
- if ( defer &&
- ( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
- ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
- // Give room for hard-coded callbacks to fire first
- // and eventually mark/queue something else on the element
- setTimeout( function() {
- if ( !jQuery._data( elem, queueDataKey ) &&
- !jQuery._data( elem, markDataKey ) ) {
- jQuery.removeData( elem, deferDataKey, true );
- defer.fire();
- }
- }, 0 );
- }
-}
-
-jQuery.extend({
-
- _mark: function( elem, type ) {
- if ( elem ) {
- type = ( type || "fx" ) + "mark";
- jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
- }
- },
-
- _unmark: function( force, elem, type ) {
- if ( force !== true ) {
- type = elem;
- elem = force;
- force = false;
- }
- if ( elem ) {
- type = type || "fx";
- var key = type + "mark",
- count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
- if ( count ) {
- jQuery._data( elem, key, count );
- } else {
- jQuery.removeData( elem, key, true );
- handleQueueMarkDefer( elem, type, "mark" );
- }
- }
- },
-
- queue: function( elem, type, data ) {
- var q;
- if ( elem ) {
- type = ( type || "fx" ) + "queue";
- q = jQuery._data( elem, type );
-
- // Speed up dequeue by getting out quickly if this is just a lookup
- if ( data ) {
- if ( !q || jQuery.isArray(data) ) {
- q = jQuery._data( elem, type, jQuery.makeArray(data) );
- } else {
- q.push( data );
- }
- }
- return q || [];
- }
- },
-
- dequeue: function( elem, type ) {
- type = type || "fx";
-
- var queue = jQuery.queue( elem, type ),
- fn = queue.shift(),
- hooks = {};
-
- // If the fx queue is dequeued, always remove the progress sentinel
- if ( fn === "inprogress" ) {
- fn = queue.shift();
- }
-
- if ( fn ) {
- // Add a progress sentinel to prevent the fx queue from being
- // automatically dequeued
- if ( type === "fx" ) {
- queue.unshift( "inprogress" );
- }
-
- jQuery._data( elem, type + ".run", hooks );
- fn.call( elem, function() {
- jQuery.dequeue( elem, type );
- }, hooks );
- }
-
- if ( !queue.length ) {
- jQuery.removeData( elem, type + "queue " + type + ".run", true );
- handleQueueMarkDefer( elem, type, "queue" );
- }
- }
-});
-
-jQuery.fn.extend({
- queue: function( type, data ) {
- var setter = 2;
-
- if ( typeof type !== "string" ) {
- data = type;
- type = "fx";
- setter--;
- }
-
- if ( arguments.length < setter ) {
- return jQuery.queue( this[0], type );
- }
-
- return data === undefined ?
- this :
- this.each(function() {
- var queue = jQuery.queue( this, type, data );
-
- if ( type === "fx" && queue[0] !== "inprogress" ) {
- jQuery.dequeue( this, type );
- }
- });
- },
- dequeue: function( type ) {
- return this.each(function() {
- jQuery.dequeue( this, type );
- });
- },
- // Based off of the plugin by Clint Helfers, with permission.
- // http://blindsignals.com/index.php/2009/07/jquery-delay/
- delay: function( time, type ) {
- time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
- type = type || "fx";
-
- return this.queue( type, function( next, hooks ) {
- var timeout = setTimeout( next, time );
- hooks.stop = function() {
- clearTimeout( timeout );
- };
- });
- },
- clearQueue: function( type ) {
- return this.queue( type || "fx", [] );
- },
- // Get a promise resolved when queues of a certain type
- // are emptied (fx is the type by default)
- promise: function( type, object ) {
- if ( typeof type !== "string" ) {
- object = type;
- type = undefined;
- }
- type = type || "fx";
- var defer = jQuery.Deferred(),
- elements = this,
- i = elements.length,
- count = 1,
- deferDataKey = type + "defer",
- queueDataKey = type + "queue",
- markDataKey = type + "mark",
- tmp;
- function resolve() {
- if ( !( --count ) ) {
- defer.resolveWith( elements, [ elements ] );
- }
- }
- while( i-- ) {
- if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
- ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
- jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
- jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
- count++;
- tmp.add( resolve );
- }
- }
- resolve();
- return defer.promise( object );
- }
-});
-
-
-
-
-var rclass = /[\n\t\r]/g,
- rspace = /\s+/,
- rreturn = /\r/g,
- rtype = /^(?:button|input)$/i,
- rfocusable = /^(?:button|input|object|select|textarea)$/i,
- rclickable = /^a(?:rea)?$/i,
- rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
- getSetAttribute = jQuery.support.getSetAttribute,
- nodeHook, boolHook, fixSpecified;
-
-jQuery.fn.extend({
- attr: function( name, value ) {
- return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
- },
-
- removeAttr: function( name ) {
- return this.each(function() {
- jQuery.removeAttr( this, name );
- });
- },
-
- prop: function( name, value ) {
- return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
- },
-
- removeProp: function( name ) {
- name = jQuery.propFix[ name ] || name;
- return this.each(function() {
- // try/catch handles cases where IE balks (such as removing a property on window)
- try {
- this[ name ] = undefined;
- delete this[ name ];
- } catch( e ) {}
- });
- },
-
- addMethod: function( value ) {
- var classNames, i, l, elem,
- setMethod, c, cl;
-
- if ( jQuery.isFunction( value ) ) {
- return this.each(function( j ) {
- jQuery( this ).addMethod( value.call(this, j, this.className) );
- });
- }
-
- if ( value && typeof value === "string" ) {
- classNames = value.split( rspace );
-
- for ( i = 0, l = this.length; i < l; i++ ) {
- elem = this[ i ];
-
- if ( elem.nodeType === 1 ) {
- if ( !elem.className && classNames.length === 1 ) {
- elem.className = value;
-
- } else {
- setMethod = " " + elem.className + " ";
-
- for ( c = 0, cl = classNames.length; c < cl; c++ ) {
- if ( !~setMethod.indexOf( " " + classNames[ c ] + " " ) ) {
- setMethod += classNames[ c ] + " ";
- }
- }
- elem.className = jQuery.trim( setMethod );
- }
- }
- }
- }
-
- return this;
- },
-
- removeMethod: function( value ) {
- var classNames, i, l, elem, className, c, cl;
-
- if ( jQuery.isFunction( value ) ) {
- return this.each(function( j ) {
- jQuery( this ).removeMethod( value.call(this, j, this.className) );
- });
- }
-
- if ( (value && typeof value === "string") || value === undefined ) {
- classNames = ( value || "" ).split( rspace );
-
- for ( i = 0, l = this.length; i < l; i++ ) {
- elem = this[ i ];
-
- if ( elem.nodeType === 1 && elem.className ) {
- if ( value ) {
- className = (" " + elem.className + " ").replace( rclass, " " );
- for ( c = 0, cl = classNames.length; c < cl; c++ ) {
- className = className.replace(" " + classNames[ c ] + " ", " ");
- }
- elem.className = jQuery.trim( className );
-
- } else {
- elem.className = "";
- }
- }
- }
- }
-
- return this;
- },
-
- toggleMethod: function( value, stateVal ) {
- var type = typeof value,
- isBool = typeof stateVal === "boolean";
-
- if ( jQuery.isFunction( value ) ) {
- return this.each(function( i ) {
- jQuery( this ).toggleMethod( value.call(this, i, this.className, stateVal), stateVal );
- });
- }
-
- return this.each(function() {
- if ( type === "string" ) {
- // toggle individual class names
- var className,
- i = 0,
- self = jQuery( this ),
- state = stateVal,
- classNames = value.split( rspace );
-
- while ( (className = classNames[ i++ ]) ) {
- // check each className given, space seperated list
- state = isBool ? state : !self.hasMethod( className );
- self[ state ? "addMethod" : "removeMethod" ]( className );
- }
-
- } else if ( type === "undefined" || type === "boolean" ) {
- if ( this.className ) {
- // store className if set
- jQuery._data( this, "__className__", this.className );
- }
-
- // toggle whole className
- this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
- }
- });
- },
-
- hasMethod: function( selector ) {
- var className = " " + selector + " ",
- i = 0,
- l = this.length;
- for ( ; i < l; i++ ) {
- if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
- return true;
- }
- }
-
- return false;
- },
-
- val: function( value ) {
- var hooks, ret, isFunction,
- elem = this[0];
-
- if ( !arguments.length ) {
- if ( elem ) {
- hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
-
- if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
- return ret;
- }
-
- ret = elem.value;
-
- return typeof ret === "string" ?
- // handle most common string cases
- ret.replace(rreturn, "") :
- // handle cases where value is null/undef or number
- ret == null ? "" : ret;
- }
-
- return;
- }
-
- isFunction = jQuery.isFunction( value );
-
- return this.each(function( i ) {
- var self = jQuery(this), val;
-
- if ( this.nodeType !== 1 ) {
- return;
- }
-
- if ( isFunction ) {
- val = value.call( this, i, self.val() );
- } else {
- val = value;
- }
-
- // Treat null/undefined as ""; convert numbers to string
- if ( val == null ) {
- val = "";
- } else if ( typeof val === "number" ) {
- val += "";
- } else if ( jQuery.isArray( val ) ) {
- val = jQuery.map(val, function ( value ) {
- return value == null ? "" : value + "";
- });
- }
-
- hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
-
- // If set returns undefined, fall back to normal setting
- if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
- this.value = val;
- }
- });
- }
-});
-
-jQuery.extend({
- valHooks: {
- option: {
- get: function( elem ) {
- // attributes.value is undefined in Blackberry 4.7 but
- // uses .value. See #6932
- var val = elem.attributes.value;
- return !val || val.specified ? elem.value : elem.text;
- }
- },
- select: {
- get: function( elem ) {
- var value, i, max, option,
- index = elem.selectedIndex,
- values = [],
- options = elem.options,
- one = elem.type === "select-one";
-
- // Nothing was selected
- if ( index < 0 ) {
- return null;
- }
-
- // Loop through all the selected options
- i = one ? index : 0;
- max = one ? index + 1 : options.length;
- for ( ; i < max; i++ ) {
- option = options[ i ];
-
- // Don't return options that are disabled or in a disabled optgroup
- if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
- (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
-
- // Get the specific value for the option
- value = jQuery( option ).val();
-
- // We don't need an array for one selects
- if ( one ) {
- return value;
- }
-
- // Multi-Selects return an array
- values.push( value );
- }
- }
-
- // Fixes Bug #2551 -- select.val() broken in IE after form.reset()
- if ( one && !values.length && options.length ) {
- return jQuery( options[ index ] ).val();
- }
-
- return values;
- },
-
- set: function( elem, value ) {
- var values = jQuery.makeArray( value );
-
- jQuery(elem).find("option").each(function() {
- this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
- });
-
- if ( !values.length ) {
- elem.selectedIndex = -1;
- }
- return values;
- }
- }
- },
-
- attrFn: {
- val: true,
- css: true,
- html: true,
- text: true,
- data: true,
- width: true,
- height: true,
- offset: true
- },
-
- attr: function( elem, name, value, pass ) {
- var ret, hooks, notxml,
- nType = elem.nodeType;
-
- // don't get/set attributes on text, comment and attribute nodes
- if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
- return;
- }
-
- if ( pass && name in jQuery.attrFn ) {
- return jQuery( elem )[ name ]( value );
- }
-
- // Fallback to prop when attributes are not supported
- if ( typeof elem.getAttribute === "undefined" ) {
- return jQuery.prop( elem, name, value );
- }
-
- notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
-
- // All attributes are lowercase
- // Grab necessary hook if one is defined
- if ( notxml ) {
- name = name.toLowerCase();
- hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
- }
-
- if ( value !== undefined ) {
-
- if ( value === null ) {
- jQuery.removeAttr( elem, name );
- return;
-
- } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
- return ret;
-
- } else {
- elem.setAttribute( name, "" + value );
- return value;
- }
-
- } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
- return ret;
-
- } else {
-
- ret = elem.getAttribute( name );
-
- // Non-existent attributes return null, we normalize to undefined
- return ret === null ?
- undefined :
- ret;
- }
- },
-
- removeAttr: function( elem, value ) {
- var propName, attrNames, name, l, isBool,
- i = 0;
-
- if ( value && elem.nodeType === 1 ) {
- attrNames = value.toLowerCase().split( rspace );
- l = attrNames.length;
-
- for ( ; i < l; i++ ) {
- name = attrNames[ i ];
-
- if ( name ) {
- propName = jQuery.propFix[ name ] || name;
- isBool = rboolean.test( name );
-
- // See #9699 for explanation of this approach (setting first, then removal)
- // Do not do this for boolean attributes (see #10870)
- if ( !isBool ) {
- jQuery.attr( elem, name, "" );
- }
- elem.removeAttribute( getSetAttribute ? name : propName );
-
- // Set corresponding property to false for boolean attributes
- if ( isBool && propName in elem ) {
- elem[ propName ] = false;
- }
- }
- }
- }
- },
-
- attrHooks: {
- type: {
- set: function( elem, value ) {
- // We can't allow the type property to be changed (since it causes problems in IE)
- if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
- jQuery.error( "type property can't be changed" );
- } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
- // Setting the type on a radio button after the value resets the value in IE6-9
- // Reset value to it's default in case type is set after value
- // This is for element creation
- var val = elem.value;
- elem.setAttribute( "type", value );
- if ( val ) {
- elem.value = val;
- }
- return value;
- }
- }
- },
- // Use the value property for back compat
- // Use the nodeHook for button elements in IE6/7 (#1954)
- value: {
- get: function( elem, name ) {
- if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
- return nodeHook.get( elem, name );
- }
- return name in elem ?
- elem.value :
- null;
- },
- set: function( elem, value, name ) {
- if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
- return nodeHook.set( elem, value, name );
- }
- // Does not return so that setAttribute is also used
- elem.value = value;
- }
- }
- },
-
- propFix: {
- tabindex: "tabIndex",
- readonly: "readOnly",
- "for": "htmlFor",
- "class": "className",
- maxlength: "maxLength",
- cellspacing: "cellSpacing",
- cellpadding: "cellPadding",
- rowspan: "rowSpan",
- colspan: "colSpan",
- usemap: "useMap",
- frameborder: "frameBorder",
- contenteditable: "contentEditable"
- },
-
- prop: function( elem, name, value ) {
- var ret, hooks, notxml,
- nType = elem.nodeType;
-
- // don't get/set properties on text, comment and attribute nodes
- if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
- return;
- }
-
- notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
-
- if ( notxml ) {
- // Fix name and attach hooks
- name = jQuery.propFix[ name ] || name;
- hooks = jQuery.propHooks[ name ];
- }
-
- if ( value !== undefined ) {
- if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
- return ret;
-
- } else {
- return ( elem[ name ] = value );
- }
-
- } else {
- if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
- return ret;
-
- } else {
- return elem[ name ];
- }
- }
- },
-
- propHooks: {
- tabIndex: {
- get: function( elem ) {
- // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
- // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
- var attributeNode = elem.getAttributeNode("tabindex");
-
- return attributeNode && attributeNode.specified ?
- parseInt( attributeNode.value, 10 ) :
- rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
- 0 :
- undefined;
- }
- }
- }
-});
-
-// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
-jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
-
-// Hook for boolean attributes
-boolHook = {
- get: function( elem, name ) {
- // Align boolean attributes with corresponding properties
- // Fall back to attribute presence where some booleans are not supported
- var attrNode,
- property = jQuery.prop( elem, name );
- return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
- name.toLowerCase() :
- undefined;
- },
- set: function( elem, value, name ) {
- var propName;
- if ( value === false ) {
- // Remove boolean attributes when set to false
- jQuery.removeAttr( elem, name );
- } else {
- // value is true since we know at this point it's type boolean and not false
- // Set boolean attributes to the same name and set the DOM property
- propName = jQuery.propFix[ name ] || name;
- if ( propName in elem ) {
- // Only set the IDL specifically if it already exists on the element
- elem[ propName ] = true;
- }
-
- elem.setAttribute( name, name.toLowerCase() );
- }
- return name;
- }
-};
-
-// IE6/7 do not support getting/setting some attributes with get/setAttribute
-if ( !getSetAttribute ) {
-
- fixSpecified = {
- name: true,
- id: true,
- coords: true
- };
-
- // Use this for any attribute in IE6/7
- // This fixes almost every IE6/7 issue
- nodeHook = jQuery.valHooks.button = {
- get: function( elem, name ) {
- var ret;
- ret = elem.getAttributeNode( name );
- return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
- ret.nodeValue :
- undefined;
- },
- set: function( elem, value, name ) {
- // Set the existing or create a new attribute node
- var ret = elem.getAttributeNode( name );
- if ( !ret ) {
- ret = document.createAttribute( name );
- elem.setAttributeNode( ret );
- }
- return ( ret.nodeValue = value + "" );
- }
- };
-
- // Apply the nodeHook to tabindex
- jQuery.attrHooks.tabindex.set = nodeHook.set;
-
- // Set width and height to auto instead of 0 on empty string( Bug #8150 )
- // This is for removals
- jQuery.each([ "width", "height" ], function( i, name ) {
- jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
- set: function( elem, value ) {
- if ( value === "" ) {
- elem.setAttribute( name, "auto" );
- return value;
- }
- }
- });
- });
-
- // Set contenteditable to false on removals(#10429)
- // Setting to empty string throws an error as an invalid value
- jQuery.attrHooks.contenteditable = {
- get: nodeHook.get,
- set: function( elem, value, name ) {
- if ( value === "" ) {
- value = "false";
- }
- nodeHook.set( elem, value, name );
- }
- };
-}
-
-
-// Some attributes require a special call on IE
-if ( !jQuery.support.hrefNormalized ) {
- jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
- jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
- get: function( elem ) {
- var ret = elem.getAttribute( name, 2 );
- return ret === null ? undefined : ret;
- }
- });
- });
-}
-
-if ( !jQuery.support.style ) {
- jQuery.attrHooks.style = {
- get: function( elem ) {
- // Return undefined in the case of empty string
- // Normalize to lowercase since IE uppercases css property names
- return elem.style.cssText.toLowerCase() || undefined;
- },
- set: function( elem, value ) {
- return ( elem.style.cssText = "" + value );
- }
- };
-}
-
-// Safari mis-reports the default selected property of an option
-// Accessing the parent's selectedIndex property fixes it
-if ( !jQuery.support.optSelected ) {
- jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
- get: function( elem ) {
- var parent = elem.parentNode;
-
- if ( parent ) {
- parent.selectedIndex;
-
- // Make sure that it also works with optgroups, see #5701
- if ( parent.parentNode ) {
- parent.parentNode.selectedIndex;
- }
- }
- return null;
- }
- });
-}
-
-// IE6/7 call enctype encoding
-if ( !jQuery.support.enctype ) {
- jQuery.propFix.enctype = "encoding";
-}
-
-// Radios and checkboxes getter/setter
-if ( !jQuery.support.checkOn ) {
- jQuery.each([ "radio", "checkbox" ], function() {
- jQuery.valHooks[ this ] = {
- get: function( elem ) {
- // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
- return elem.getAttribute("value") === null ? "on" : elem.value;
- }
- };
- });
-}
-jQuery.each([ "radio", "checkbox" ], function() {
- jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
- set: function( elem, value ) {
- if ( jQuery.isArray( value ) ) {
- return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
- }
- }
- });
-});
-
-
-
-
-var rformElems = /^(?:textarea|input|select)$/i,
- rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
- rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
- rkeyEvent = /^key/,
- rmouseEvent = /^(?:mouse|contextmenu)|click/,
- rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
- rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
- quickParse = function( selector ) {
- var quick = rquickIs.exec( selector );
- if ( quick ) {
- // 0 1 2 3
- // [ _, tag, id, class ]
- quick[1] = ( quick[1] || "" ).toLowerCase();
- quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
- }
- return quick;
- },
- quickIs = function( elem, m ) {
- var attrs = elem.attributes || {};
- return (
- (!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
- (!m[2] || (attrs.id || {}).value === m[2]) &&
- (!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
- );
- },
- hoverHack = function( events ) {
- return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
- };
-
-/*
- * Helper functions for managing events -- not part of the public interface.
- * Props to Dean Edwards' addEvent library for many of the ideas.
- */
-jQuery.event = {
-
- add: function( elem, types, handler, data, selector ) {
-
- var elemData, eventHandle, events,
- t, tns, type, namespaces, handleObj,
- handleObjIn, quick, handlers, special;
-
- // Don't attach events to noData or text/comment nodes (allow plain objects tho)
- if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
- return;
- }
-
- // Caller can pass in an object of custom data in lieu of the handler
- if ( handler.handler ) {
- handleObjIn = handler;
- handler = handleObjIn.handler;
- selector = handleObjIn.selector;
- }
-
- // Make sure that the handler has a unique ID, used to find/remove it later
- if ( !handler.guid ) {
- handler.guid = jQuery.guid++;
- }
-
- // Init the element's event structure and main handler, if this is the first
- events = elemData.events;
- if ( !events ) {
- elemData.events = events = {};
- }
- eventHandle = elemData.handle;
- if ( !eventHandle ) {
- elemData.handle = eventHandle = function( e ) {
- // Discard the second event of a jQuery.event.trigger() and
- // when an event is called after a page has unloaded
- return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
- jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
- undefined;
- };
- // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
- eventHandle.elem = elem;
- }
-
- // Handle multiple events separated by a space
- // jQuery(...).bind("mouseover mouseout", fn);
- types = jQuery.trim( hoverHack(types) ).split( " " );
- for ( t = 0; t < types.length; t++ ) {
-
- tns = rtypenamespace.exec( types[t] ) || [];
- type = tns[1];
- namespaces = ( tns[2] || "" ).split( "." ).sort();
-
- // If event changes its type, use the special event handlers for the changed type
- special = jQuery.event.special[ type ] || {};
-
- // If selector defined, determine special event api type, otherwise given type
- type = ( selector ? special.delegateType : special.bindType ) || type;
-
- // Update special based on newly reset type
- special = jQuery.event.special[ type ] || {};
-
- // handleObj is passed to all event handlers
- handleObj = jQuery.extend({
- type: type,
- origType: tns[1],
- data: data,
- handler: handler,
- guid: handler.guid,
- selector: selector,
- quick: selector && quickParse( selector ),
- namespace: namespaces.join(".")
- }, handleObjIn );
-
- // Init the event handler queue if we're the first
- handlers = events[ type ];
- if ( !handlers ) {
- handlers = events[ type ] = [];
- handlers.delegateCount = 0;
-
- // Only use addEventListener/attachEvent if the special events handler returns false
- if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
- // Bind the global event handler to the element
- if ( elem.addEventListener ) {
- elem.addEventListener( type, eventHandle, false );
-
- } else if ( elem.attachEvent ) {
- elem.attachEvent( "on" + type, eventHandle );
- }
- }
- }
-
- if ( special.add ) {
- special.add.call( elem, handleObj );
-
- if ( !handleObj.handler.guid ) {
- handleObj.handler.guid = handler.guid;
- }
- }
-
- // Add to the element's handler list, delegates in front
- if ( selector ) {
- handlers.splice( handlers.delegateCount++, 0, handleObj );
- } else {
- handlers.push( handleObj );
- }
-
- // Keep track of which events have ever been used, for event optimization
- jQuery.event.global[ type ] = true;
- }
-
- // Nullify elem to prevent memory leaks in IE
- elem = null;
- },
-
- global: {},
-
- // Detach an event or set of events from an element
- remove: function( elem, types, handler, selector, mappedTypes ) {
-
- var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
- t, tns, type, origType, namespaces, origCount,
- j, events, special, handle, eventType, handleObj;
-
- if ( !elemData || !(events = elemData.events) ) {
- return;
- }
-
- // Once for each type.namespace in types; type may be omitted
- types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
- for ( t = 0; t < types.length; t++ ) {
- tns = rtypenamespace.exec( types[t] ) || [];
- type = origType = tns[1];
- namespaces = tns[2];
-
- // Unbind all events (on this namespace, if provided) for the element
- if ( !type ) {
- for ( type in events ) {
- jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
- }
- continue;
- }
-
- special = jQuery.event.special[ type ] || {};
- type = ( selector? special.delegateType : special.bindType ) || type;
- eventType = events[ type ] || [];
- origCount = eventType.length;
- namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
-
- // Remove matching events
- for ( j = 0; j < eventType.length; j++ ) {
- handleObj = eventType[ j ];
-
- if ( ( mappedTypes || origType === handleObj.origType ) &&
- ( !handler || handler.guid === handleObj.guid ) &&
- ( !namespaces || namespaces.test( handleObj.namespace ) ) &&
- ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
- eventType.splice( j--, 1 );
-
- if ( handleObj.selector ) {
- eventType.delegateCount--;
- }
- if ( special.remove ) {
- special.remove.call( elem, handleObj );
- }
- }
- }
-
- // Remove generic event handler if we removed something and no more handlers exist
- // (avoids potential for endless recursion during removal of special event handlers)
- if ( eventType.length === 0 && origCount !== eventType.length ) {
- if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
- jQuery.removeEvent( elem, type, elemData.handle );
- }
-
- delete events[ type ];
- }
- }
-
- // Remove the expando if it's no longer used
- if ( jQuery.isEmptyObject( events ) ) {
- handle = elemData.handle;
- if ( handle ) {
- handle.elem = null;
- }
-
- // removeData also checks for emptiness and clears the expando if empty
- // so use it instead of delete
- jQuery.removeData( elem, [ "events", "handle" ], true );
- }
- },
-
- // Events that are safe to short-circuit if no handlers are attached.
- // Native DOM events should not be added, they may have inline handlers.
- customEvent: {
- "getData": true,
- "setData": true,
- "changeData": true
- },
-
- trigger: function( event, data, elem, onlyHandlers ) {
- // Don't do events on text and comment nodes
- if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
- return;
- }
-
- // Event object or event type
- var type = event.type || event,
- namespaces = [],
- cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
-
- // focus/blur morphs to focusin/out; ensure we're not firing them right now
- if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
- return;
- }
-
- if ( type.indexOf( "!" ) >= 0 ) {
- // Exclusive events trigger only for the exact event (no namespaces)
- type = type.slice(0, -1);
- exclusive = true;
- }
-
- if ( type.indexOf( "." ) >= 0 ) {
- // Namespaced trigger; create a regexp to match event type in handle()
- namespaces = type.split(".");
- type = namespaces.shift();
- namespaces.sort();
- }
-
- if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
- // No jQuery handlers for this event type, and it can't have inline handlers
- return;
- }
-
- // Caller can pass in an Event, Object, or just an event type string
- event = typeof event === "object" ?
- // jQuery.Event object
- event[ jQuery.expando ] ? event :
- // Object literal
- new jQuery.Event( type, event ) :
- // Just the event type (string)
- new jQuery.Event( type );
-
- event.type = type;
- event.isTrigger = true;
- event.exclusive = exclusive;
- event.namespace = namespaces.join( "." );
- event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
- ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
-
- // Handle a global trigger
- if ( !elem ) {
-
- // TODO: Stop taunting the data cache; remove global events and always attach to document
- cache = jQuery.cache;
- for ( i in cache ) {
- if ( cache[ i ].events && cache[ i ].events[ type ] ) {
- jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
- }
- }
- return;
- }
-
- // Clean up the event in case it is being reused
- event.result = undefined;
- if ( !event.target ) {
- event.target = elem;
- }
-
- // Clone any incoming data and prepend the event, creating the handler arg list
- data = data != null ? jQuery.makeArray( data ) : [];
- data.unshift( event );
-
- // Allow special events to draw outside the lines
- special = jQuery.event.special[ type ] || {};
- if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
- return;
- }
-
- // Determine event propagation path in advance, per W3C events spec (#9951)
- // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
- eventPath = [[ elem, special.bindType || type ]];
- if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
-
- bubbleType = special.delegateType || type;
- cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
- old = null;
- for ( ; cur; cur = cur.parentNode ) {
- eventPath.push([ cur, bubbleType ]);
- old = cur;
- }
-
- // Only add window if we got to document (e.g., not plain obj or detached DOM)
- if ( old && old === elem.ownerDocument ) {
- eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
- }
- }
-
- // Fire handlers on the event path
- for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
-
- cur = eventPath[i][0];
- event.type = eventPath[i][1];
-
- handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
- if ( handle ) {
- handle.apply( cur, data );
- }
- // Note that this is a bare JS function and not a jQuery handler
- handle = ontype && cur[ ontype ];
- if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
- event.preventDefault();
- }
- }
- event.type = type;
-
- // If nobody prevented the default action, do it now
- if ( !onlyHandlers && !event.isDefaultPrevented() ) {
-
- if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
- !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
-
- // Call a native DOM method on the target with the same name name as the event.
- // Can't use an .isFunction() check here because IE6/7 fails that test.
- // Don't do default actions on window, that's where global variables be (#6170)
- // IE<9 dies on focus/blur to hidden element (#1486)
- if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
-
- // Don't re-trigger an onFOO event when we call its FOO() method
- old = elem[ ontype ];
-
- if ( old ) {
- elem[ ontype ] = null;
- }
-
- // Prevent re-triggering of the same event, since we already bubbled it above
- jQuery.event.triggered = type;
- elem[ type ]();
- jQuery.event.triggered = undefined;
-
- if ( old ) {
- elem[ ontype ] = old;
- }
- }
- }
- }
-
- return event.result;
- },
-
- dispatch: function( event ) {
-
- // Make a writable jQuery.Event from the native event object
- event = jQuery.event.fix( event || window.event );
-
- var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
- delegateCount = handlers.delegateCount,
- args = [].slice.call( arguments, 0 ),
- run_all = !event.exclusive && !event.namespace,
- special = jQuery.event.special[ event.type ] || {},
- handlerQueue = [],
- i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
-
- // Use the fix-ed jQuery.Event rather than the (read-only) native event
- args[0] = event;
- event.delegateTarget = this;
-
- // Call the preDispatch hook for the mapped type, and let it bail if desired
- if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
- return;
- }
-
- // Determine handlers that should run if there are delegated events
- // Avoid non-left-click bubbling in Firefox (#3861)
- if ( delegateCount && !(event.button && event.type === "click") ) {
-
- // Pregenerate a single jQuery object for reuse with .is()
- jqcur = jQuery(this);
- jqcur.context = this.ownerDocument || this;
-
- for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
-
- // Don't process events on disabled elements (#6911, #8165)
- if ( cur.disabled !== true ) {
- selMatch = {};
- matches = [];
- jqcur[0] = cur;
- for ( i = 0; i < delegateCount; i++ ) {
- handleObj = handlers[ i ];
- sel = handleObj.selector;
-
- if ( selMatch[ sel ] === undefined ) {
- selMatch[ sel ] = (
- handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
- );
- }
- if ( selMatch[ sel ] ) {
- matches.push( handleObj );
- }
- }
- if ( matches.length ) {
- handlerQueue.push({ elem: cur, matches: matches });
- }
- }
- }
- }
-
- // Add the remaining (directly-bound) handlers
- if ( handlers.length > delegateCount ) {
- handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
- }
-
- // Run delegates first; they may want to stop propagation beneath us
- for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
- matched = handlerQueue[ i ];
- event.currentTarget = matched.elem;
-
- for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
- handleObj = matched.matches[ j ];
-
- // Triggered event must either 1) be non-exclusive and have no namespace, or
- // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
- if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
-
- event.data = handleObj.data;
- event.handleObj = handleObj;
-
- ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
- .apply( matched.elem, args );
-
- if ( ret !== undefined ) {
- event.result = ret;
- if ( ret === false ) {
- event.preventDefault();
- event.stopPropagation();
- }
- }
- }
- }
- }
-
- // Call the postDispatch hook for the mapped type
- if ( special.postDispatch ) {
- special.postDispatch.call( this, event );
- }
-
- return event.result;
- },
-
- // Includes some event props shared by KeyEvent and MouseEvent
- // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
- props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
-
- fixHooks: {},
-
- keyHooks: {
- props: "char charCode key keyCode".split(" "),
- filter: function( event, original ) {
-
- // Add which for key events
- if ( event.which == null ) {
- event.which = original.charCode != null ? original.charCode : original.keyCode;
- }
-
- return event;
- }
- },
-
- mouseHooks: {
- props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
- filter: function( event, original ) {
- var eventDoc, doc, body,
- button = original.button,
- fromElement = original.fromElement;
-
- // Calculate pageX/Y if missing and clientX/Y available
- if ( event.pageX == null && original.clientX != null ) {
- eventDoc = event.target.ownerDocument || document;
- doc = eventDoc.documentElement;
- body = eventDoc.body;
-
- event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
- event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
- }
-
- // Add relatedTarget, if necessary
- if ( !event.relatedTarget && fromElement ) {
- event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
- }
-
- // Add which for click: 1 === left; 2 === middle; 3 === right
- // Note: button is not normalized, so don't use it
- if ( !event.which && button !== undefined ) {
- event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
- }
-
- return event;
- }
- },
-
- fix: function( event ) {
- if ( event[ jQuery.expando ] ) {
- return event;
- }
-
- // Create a writable copy of the event object and normalize some properties
- var i, prop,
- originalEvent = event,
- fixHook = jQuery.event.fixHooks[ event.type ] || {},
- copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
-
- event = jQuery.Event( originalEvent );
-
- for ( i = copy.length; i; ) {
- prop = copy[ --i ];
- event[ prop ] = originalEvent[ prop ];
- }
-
- // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
- if ( !event.target ) {
- event.target = originalEvent.srcElement || document;
- }
-
- // Target should not be a text node (#504, Safari)
- if ( event.target.nodeType === 3 ) {
- event.target = event.target.parentNode;
- }
-
- // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
- if ( event.metaKey === undefined ) {
- event.metaKey = event.ctrlKey;
- }
-
- return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
- },
-
- special: {
- ready: {
- // Make sure the ready event is setup
- setup: jQuery.bindReady
- },
-
- load: {
- // Prevent triggered image.load events from bubbling to window.load
- noBubble: true
- },
-
- focus: {
- delegateType: "focusin"
- },
- blur: {
- delegateType: "focusout"
- },
-
- beforeunload: {
- setup: function( data, namespaces, eventHandle ) {
- // We only want to do this special case on windows
- if ( jQuery.isWindow( this ) ) {
- this.onbeforeunload = eventHandle;
- }
- },
-
- teardown: function( namespaces, eventHandle ) {
- if ( this.onbeforeunload === eventHandle ) {
- this.onbeforeunload = null;
- }
- }
- }
- },
-
- simulate: function( type, elem, event, bubble ) {
- // Piggyback on a donor event to simulate a different one.
- // Fake originalEvent to avoid donor's stopPropagation, but if the
- // simulated event prevents default then we do the same on the donor.
- var e = jQuery.extend(
- new jQuery.Event(),
- event,
- { type: type,
- isSimulated: true,
- originalEvent: {}
- }
- );
- if ( bubble ) {
- jQuery.event.trigger( e, null, elem );
- } else {
- jQuery.event.dispatch.call( elem, e );
- }
- if ( e.isDefaultPrevented() ) {
- event.preventDefault();
- }
- }
-};
-
-// Some plugins are using, but it's undocumented/deprecated and will be removed.
-// The 1.7 special event interface should provide all the hooks needed now.
-jQuery.event.handle = jQuery.event.dispatch;
-
-jQuery.removeEvent = document.removeEventListener ?
- function( elem, type, handle ) {
- if ( elem.removeEventListener ) {
- elem.removeEventListener( type, handle, false );
- }
- } :
- function( elem, type, handle ) {
- if ( elem.detachEvent ) {
- elem.detachEvent( "on" + type, handle );
- }
- };
-
-jQuery.Event = function( src, props ) {
- // Allow instantiation without the 'new' keyword
- if ( !(this instanceof jQuery.Event) ) {
- return new jQuery.Event( src, props );
- }
-
- // Event object
- if ( src && src.type ) {
- this.originalEvent = src;
- this.type = src.type;
-
- // Events bubbling up the document may have been marked as prevented
- // by a handler lower down the tree; reflect the correct value.
- this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
- src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
-
- // Event type
- } else {
- this.type = src;
- }
-
- // Put explicitly provided properties onto the event object
- if ( props ) {
- jQuery.extend( this, props );
- }
-
- // Create a timestamp if incoming event doesn't have one
- this.timeStamp = src && src.timeStamp || jQuery.now();
-
- // Mark it as fixed
- this[ jQuery.expando ] = true;
-};
-
-function returnFalse() {
- return false;
-}
-function returnTrue() {
- return true;
-}
-
-// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
-// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
-jQuery.Event.prototype = {
- preventDefault: function() {
- this.isDefaultPrevented = returnTrue;
-
- var e = this.originalEvent;
- if ( !e ) {
- return;
- }
-
- // if preventDefault exists run it on the original event
- if ( e.preventDefault ) {
- e.preventDefault();
-
- // otherwise set the returnValue property of the original event to false (IE)
- } else {
- e.returnValue = false;
- }
- },
- stopPropagation: function() {
- this.isPropagationStopped = returnTrue;
-
- var e = this.originalEvent;
- if ( !e ) {
- return;
- }
- // if stopPropagation exists run it on the original event
- if ( e.stopPropagation ) {
- e.stopPropagation();
- }
- // otherwise set the cancelBubble property of the original event to true (IE)
- e.cancelBubble = true;
- },
- stopImmediatePropagation: function() {
- this.isImmediatePropagationStopped = returnTrue;
- this.stopPropagation();
- },
- isDefaultPrevented: returnFalse,
- isPropagationStopped: returnFalse,
- isImmediatePropagationStopped: returnFalse
-};
-
-// Create mouseenter/leave events using mouseover/out and event-time checks
-jQuery.each({
- mouseenter: "mouseover",
- mouseleave: "mouseout"
-}, function( orig, fix ) {
- jQuery.event.special[ orig ] = {
- delegateType: fix,
- bindType: fix,
-
- handle: function( event ) {
- var target = this,
- related = event.relatedTarget,
- handleObj = event.handleObj,
- selector = handleObj.selector,
- ret;
-
- // For mousenter/leave call the handler if related is outside the target.
- // NB: No relatedTarget if the mouse left/entered the browser window
- if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
- event.type = handleObj.origType;
- ret = handleObj.handler.apply( this, arguments );
- event.type = fix;
- }
- return ret;
- }
- };
-});
-
-// IE submit delegation
-if ( !jQuery.support.submitBubbles ) {
-
- jQuery.event.special.submit = {
- setup: function() {
- // Only need this for delegated form submit events
- if ( jQuery.nodeName( this, "form" ) ) {
- return false;
- }
-
- // Lazy-add a submit handler when a descendant form may potentially be submitted
- jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
- // Node name check avoids a VML-related crash in IE (#9807)
- var elem = e.target,
- form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
- if ( form && !form._submit_attached ) {
- jQuery.event.add( form, "submit._submit", function( event ) {
- event._submit_bubble = true;
- });
- form._submit_attached = true;
- }
- });
- // return undefined since we don't need an event listener
- },
-
- postDispatch: function( event ) {
- // If form was submitted by the user, bubble the event up the tree
- if ( event._submit_bubble ) {
- delete event._submit_bubble;
- if ( this.parentNode && !event.isTrigger ) {
- jQuery.event.simulate( "submit", this.parentNode, event, true );
- }
- }
- },
-
- teardown: function() {
- // Only need this for delegated form submit events
- if ( jQuery.nodeName( this, "form" ) ) {
- return false;
- }
-
- // Remove delegated handlers; cleanData eventually reaps submit handlers attached above
- jQuery.event.remove( this, "._submit" );
- }
- };
-}
-
-// IE change delegation and checkbox/radio fix
-if ( !jQuery.support.changeBubbles ) {
-
- jQuery.event.special.change = {
-
- setup: function() {
-
- if ( rformElems.test( this.nodeName ) ) {
- // IE doesn't fire change on a check/radio until blur; trigger it on click
- // after a propertychange. Eat the blur-change in special.change.handle.
- // This still fires onchange a second time for check/radio after blur.
- if ( this.type === "checkbox" || this.type === "radio" ) {
- jQuery.event.add( this, "propertychange._change", function( event ) {
- if ( event.originalEvent.propertyName === "checked" ) {
- this._just_changed = true;
- }
- });
- jQuery.event.add( this, "click._change", function( event ) {
- if ( this._just_changed && !event.isTrigger ) {
- this._just_changed = false;
- jQuery.event.simulate( "change", this, event, true );
- }
- });
- }
- return false;
- }
- // Delegated event; lazy-add a change handler on descendant inputs
- jQuery.event.add( this, "beforeactivate._change", function( e ) {
- var elem = e.target;
-
- if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
- jQuery.event.add( elem, "change._change", function( event ) {
- if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
- jQuery.event.simulate( "change", this.parentNode, event, true );
- }
- });
- elem._change_attached = true;
- }
- });
- },
-
- handle: function( event ) {
- var elem = event.target;
-
- // Swallow native change events from checkbox/radio, we already triggered them above
- if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
- return event.handleObj.handler.apply( this, arguments );
- }
- },
-
- teardown: function() {
- jQuery.event.remove( this, "._change" );
-
- return rformElems.test( this.nodeName );
- }
- };
-}
-
-// Create "bubbling" focus and blur events
-if ( !jQuery.support.focusinBubbles ) {
- jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
-
- // Attach a single capturing handler while someone wants focusin/focusout
- var attaches = 0,
- handler = function( event ) {
- jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
- };
-
- jQuery.event.special[ fix ] = {
- setup: function() {
- if ( attaches++ === 0 ) {
- document.addEventListener( orig, handler, true );
- }
- },
- teardown: function() {
- if ( --attaches === 0 ) {
- document.removeEventListener( orig, handler, true );
- }
- }
- };
- });
-}
-
-jQuery.fn.extend({
-
- on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
- var origFn, type;
-
- // Types can be a map of types/handlers
- if ( typeof types === "object" ) {
- // ( types-Object, selector, data )
- if ( typeof selector !== "string" ) { // && selector != null
- // ( types-Object, data )
- data = data || selector;
- selector = undefined;
- }
- for ( type in types ) {
- this.on( type, selector, data, types[ type ], one );
- }
- return this;
- }
-
- if ( data == null && fn == null ) {
- // ( types, fn )
- fn = selector;
- data = selector = undefined;
- } else if ( fn == null ) {
- if ( typeof selector === "string" ) {
- // ( types, selector, fn )
- fn = data;
- data = undefined;
- } else {
- // ( types, data, fn )
- fn = data;
- data = selector;
- selector = undefined;
- }
- }
- if ( fn === false ) {
- fn = returnFalse;
- } else if ( !fn ) {
- return this;
- }
-
- if ( one === 1 ) {
- origFn = fn;
- fn = function( event ) {
- // Can use an empty set, since event contains the info
- jQuery().off( event );
- return origFn.apply( this, arguments );
- };
- // Use same guid so caller can remove using origFn
- fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
- }
- return this.each( function() {
- jQuery.event.add( this, types, fn, data, selector );
- });
- },
- one: function( types, selector, data, fn ) {
- return this.on( types, selector, data, fn, 1 );
- },
- off: function( types, selector, fn ) {
- if ( types && types.preventDefault && types.handleObj ) {
- // ( event ) dispatched jQuery.Event
- var handleObj = types.handleObj;
- jQuery( types.delegateTarget ).off(
- handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
- handleObj.selector,
- handleObj.handler
- );
- return this;
- }
- if ( typeof types === "object" ) {
- // ( types-object [, selector] )
- for ( var type in types ) {
- this.off( type, selector, types[ type ] );
- }
- return this;
- }
- if ( selector === false || typeof selector === "function" ) {
- // ( types [, fn] )
- fn = selector;
- selector = undefined;
- }
- if ( fn === false ) {
- fn = returnFalse;
- }
- return this.each(function() {
- jQuery.event.remove( this, types, fn, selector );
- });
- },
-
- bind: function( types, data, fn ) {
- return this.on( types, null, data, fn );
- },
- unbind: function( types, fn ) {
- return this.off( types, null, fn );
- },
-
- live: function( types, data, fn ) {
- jQuery( this.context ).on( types, this.selector, data, fn );
- return this;
- },
- die: function( types, fn ) {
- jQuery( this.context ).off( types, this.selector || "**", fn );
- return this;
- },
-
- delegate: function( selector, types, data, fn ) {
- return this.on( types, selector, data, fn );
- },
- undelegate: function( selector, types, fn ) {
- // ( namespace ) or ( selector, types [, fn] )
- return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
- },
-
- trigger: function( type, data ) {
- return this.each(function() {
- jQuery.event.trigger( type, data, this );
- });
- },
- triggerHandler: function( type, data ) {
- if ( this[0] ) {
- return jQuery.event.trigger( type, data, this[0], true );
- }
- },
-
- toggle: function( fn ) {
- // Save reference to arguments for access in closure
- var args = arguments,
- guid = fn.guid || jQuery.guid++,
- i = 0,
- toggler = function( event ) {
- // Figure out which function to execute
- var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
- jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
-
- // Make sure that clicks stop
- event.preventDefault();
-
- // and execute the function
- return args[ lastToggle ].apply( this, arguments ) || false;
- };
-
- // link all the functions, so any of them can unbind this click handler
- toggler.guid = guid;
- while ( i < args.length ) {
- args[ i++ ].guid = guid;
- }
-
- return this.click( toggler );
- },
-
- hover: function( fnOver, fnOut ) {
- return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
- }
-});
-
-jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
- "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
- "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
-
- // Handle event binding
- jQuery.fn[ name ] = function( data, fn ) {
- if ( fn == null ) {
- fn = data;
- data = null;
- }
-
- return arguments.length > 0 ?
- this.on( name, null, data, fn ) :
- this.trigger( name );
- };
-
- if ( jQuery.attrFn ) {
- jQuery.attrFn[ name ] = true;
- }
-
- if ( rkeyEvent.test( name ) ) {
- jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
- }
-
- if ( rmouseEvent.test( name ) ) {
- jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
- }
-});
-
-
-
-/*!
- * Sizzle CSS Selector Engine
- * Copyright 2011, The Dojo Foundation
- * Released under the MIT, BSD, and GPL Licenses.
- * More information: http://sizzlejs.com/
- */
-(function(){
-
-var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
- expando = "sizcache" + (Math.random() + '').replace('.', ''),
- done = 0,
- toString = Object.prototype.toString,
- hasDuplicate = false,
- baseHasDuplicate = true,
- rBackslash = /\\/g,
- rReturn = /\r\n/g,
- rNonWord = /\W/;
-
-// Here we check if the JavaScript engine is using some sort of
-// optimization where it does not always call our comparision
-// function. If that is the case, discard the hasDuplicate value.
-// Thus far that includes Google Chrome.
-[0, 0].sort(function() {
- baseHasDuplicate = false;
- return 0;
-});
-
-var Sizzle = function( selector, context, results, seed ) {
- results = results || [];
- context = context || document;
-
- var origContext = context;
-
- if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
- return [];
- }
-
- if ( !selector || typeof selector !== "string" ) {
- return results;
- }
-
- var m, set, checkSet, extra, ret, cur, pop, i,
- prune = true,
- contextXML = Sizzle.isXML( context ),
- parts = [],
- soFar = selector;
-
- // Reset the position of the chunker regexp (start from head)
- do {
- chunker.exec( "" );
- m = chunker.exec( soFar );
-
- if ( m ) {
- soFar = m[3];
-
- parts.push( m[1] );
-
- if ( m[2] ) {
- extra = m[3];
- break;
- }
- }
- } while ( m );
-
- if ( parts.length > 1 && origPOS.exec( selector ) ) {
-
- if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
- set = posProcess( parts[0] + parts[1], context, seed );
-
- } else {
- set = Expr.relative[ parts[0] ] ?
- [ context ] :
- Sizzle( parts.shift(), context );
-
- while ( parts.length ) {
- selector = parts.shift();
-
- if ( Expr.relative[ selector ] ) {
- selector += parts.shift();
- }
-
- set = posProcess( selector, set, seed );
- }
- }
-
- } else {
- // Take a shortcut and set the context if the root selector is an ID
- // (but not if it'll be faster if the inner selector is an ID)
- if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
- Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
-
- ret = Sizzle.find( parts.shift(), context, contextXML );
- context = ret.expr ?
- Sizzle.filter( ret.expr, ret.set )[0] :
- ret.set[0];
- }
-
- if ( context ) {
- ret = seed ?
- { expr: parts.pop(), set: makeArray(seed) } :
- Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
-
- set = ret.expr ?
- Sizzle.filter( ret.expr, ret.set ) :
- ret.set;
-
- if ( parts.length > 0 ) {
- checkSet = makeArray( set );
-
- } else {
- prune = false;
- }
-
- while ( parts.length ) {
- cur = parts.pop();
- pop = cur;
-
- if ( !Expr.relative[ cur ] ) {
- cur = "";
- } else {
- pop = parts.pop();
- }
-
- if ( pop == null ) {
- pop = context;
- }
-
- Expr.relative[ cur ]( checkSet, pop, contextXML );
- }
-
- } else {
- checkSet = parts = [];
- }
- }
-
- if ( !checkSet ) {
- checkSet = set;
- }
-
- if ( !checkSet ) {
- Sizzle.error( cur || selector );
- }
-
- if ( toString.call(checkSet) === "[object Array]" ) {
- if ( !prune ) {
- results.push.apply( results, checkSet );
-
- } else if ( context && context.nodeType === 1 ) {
- for ( i = 0; checkSet[i] != null; i++ ) {
- if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
- results.push( set[i] );
- }
- }
-
- } else {
- for ( i = 0; checkSet[i] != null; i++ ) {
- if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
- results.push( set[i] );
- }
- }
- }
-
- } else {
- makeArray( checkSet, results );
- }
-
- if ( extra ) {
- Sizzle( extra, origContext, results, seed );
- Sizzle.uniqueSort( results );
- }
-
- return results;
-};
-
-Sizzle.uniqueSort = function( results ) {
- if ( sortOrder ) {
- hasDuplicate = baseHasDuplicate;
- results.sort( sortOrder );
-
- if ( hasDuplicate ) {
- for ( var i = 1; i < results.length; i++ ) {
- if ( results[i] === results[ i - 1 ] ) {
- results.splice( i--, 1 );
- }
- }
- }
- }
-
- return results;
-};
-
-Sizzle.matches = function( expr, set ) {
- return Sizzle( expr, null, null, set );
-};
-
-Sizzle.matchesSelector = function( node, expr ) {
- return Sizzle( expr, null, null, [node] ).length > 0;
-};
-
-Sizzle.find = function( expr, context, isXML ) {
- var set, i, len, match, type, left;
-
- if ( !expr ) {
- return [];
- }
-
- for ( i = 0, len = Expr.order.length; i < len; i++ ) {
- type = Expr.order[i];
-
- if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
- left = match[1];
- match.splice( 1, 1 );
-
- if ( left.substr( left.length - 1 ) !== "\\" ) {
- match[1] = (match[1] || "").replace( rBackslash, "" );
- set = Expr.find[ type ]( match, context, isXML );
-
- if ( set != null ) {
- expr = expr.replace( Expr.match[ type ], "" );
- break;
- }
- }
- }
- }
-
- if ( !set ) {
- set = typeof context.getElementsByTagName !== "undefined" ?
- context.getElementsByTagName( "*" ) :
- [];
- }
-
- return { set: set, expr: expr };
-};
-
-Sizzle.filter = function( expr, set, inplace, not ) {
- var match, anyFound,
- type, found, item, filter, left,
- i, pass,
- old = expr,
- result = [],
- curLoop = set,
- isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
-
- while ( expr && set.length ) {
- for ( type in Expr.filter ) {
- if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
- filter = Expr.filter[ type ];
- left = match[1];
-
- anyFound = false;
-
- match.splice(1,1);
-
- if ( left.substr( left.length - 1 ) === "\\" ) {
- continue;
- }
-
- if ( curLoop === result ) {
- result = [];
- }
-
- if ( Expr.preFilter[ type ] ) {
- match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
-
- if ( !match ) {
- anyFound = found = true;
-
- } else if ( match === true ) {
- continue;
- }
- }
-
- if ( match ) {
- for ( i = 0; (item = curLoop[i]) != null; i++ ) {
- if ( item ) {
- found = filter( item, match, i, curLoop );
- pass = not ^ found;
-
- if ( inplace && found != null ) {
- if ( pass ) {
- anyFound = true;
-
- } else {
- curLoop[i] = false;
- }
-
- } else if ( pass ) {
- result.push( item );
- anyFound = true;
- }
- }
- }
- }
-
- if ( found !== undefined ) {
- if ( !inplace ) {
- curLoop = result;
- }
-
- expr = expr.replace( Expr.match[ type ], "" );
-
- if ( !anyFound ) {
- return [];
- }
-
- break;
- }
- }
- }
-
- // Improper expression
- if ( expr === old ) {
- if ( anyFound == null ) {
- Sizzle.error( expr );
-
- } else {
- break;
- }
- }
-
- old = expr;
- }
-
- return curLoop;
-};
-
-Sizzle.error = function( msg ) {
- throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-/**
- * Utility function for retreiving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-var getText = Sizzle.getText = function( elem ) {
- var i, node,
- nodeType = elem.nodeType,
- ret = "";
-
- if ( nodeType ) {
- if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
- // Use textContent || innerText for elements
- if ( typeof elem.textContent === 'string' ) {
- return elem.textContent;
- } else if ( typeof elem.innerText === 'string' ) {
- // Replace IE's carriage returns
- return elem.innerText.replace( rReturn, '' );
- } else {
- // Traverse it's children
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
- ret += getText( elem );
- }
- }
- } else if ( nodeType === 3 || nodeType === 4 ) {
- return elem.nodeValue;
- }
- } else {
-
- // If no nodeType, this is expected to be an array
- for ( i = 0; (node = elem[i]); i++ ) {
- // Do not traverse comment nodes
- if ( node.nodeType !== 8 ) {
- ret += getText( node );
- }
- }
- }
- return ret;
-};
-
-var Expr = Sizzle.selectors = {
- order: [ "ID", "NAME", "TAG" ],
-
- match: {
- ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
- CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
- NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
- ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
- TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
- CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
- POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
- PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
- },
-
- leftMatch: {},
-
- attrMap: {
- "class": "className",
- "for": "htmlFor"
- },
-
- attrHandle: {
- href: function( elem ) {
- return elem.getAttribute( "href" );
- },
- type: function( elem ) {
- return elem.getAttribute( "type" );
- }
- },
-
- relative: {
- "+": function(checkSet, part){
- var isPartStr = typeof part === "string",
- isTag = isPartStr && !rNonWord.test( part ),
- isPartStrNotTag = isPartStr && !isTag;
-
- if ( isTag ) {
- part = part.toLowerCase();
- }
-
- for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
- if ( (elem = checkSet[i]) ) {
- while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
-
- checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
- elem || false :
- elem === part;
- }
- }
-
- if ( isPartStrNotTag ) {
- Sizzle.filter( part, checkSet, true );
- }
- },
-
- ">": function( checkSet, part ) {
- var elem,
- isPartStr = typeof part === "string",
- i = 0,
- l = checkSet.length;
-
- if ( isPartStr && !rNonWord.test( part ) ) {
- part = part.toLowerCase();
-
- for ( ; i < l; i++ ) {
- elem = checkSet[i];
-
- if ( elem ) {
- var parent = elem.parentNode;
- checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
- }
- }
-
- } else {
- for ( ; i < l; i++ ) {
- elem = checkSet[i];
-
- if ( elem ) {
- checkSet[i] = isPartStr ?
- elem.parentNode :
- elem.parentNode === part;
- }
- }
-
- if ( isPartStr ) {
- Sizzle.filter( part, checkSet, true );
- }
- }
- },
-
- "": function(checkSet, part, isXML){
- var nodeCheck,
- doneName = done++,
- checkFn = dirCheck;
-
- if ( typeof part === "string" && !rNonWord.test( part ) ) {
- part = part.toLowerCase();
- nodeCheck = part;
- checkFn = dirNodeCheck;
- }
-
- checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
- },
-
- "~": function( checkSet, part, isXML ) {
- var nodeCheck,
- doneName = done++,
- checkFn = dirCheck;
-
- if ( typeof part === "string" && !rNonWord.test( part ) ) {
- part = part.toLowerCase();
- nodeCheck = part;
- checkFn = dirNodeCheck;
- }
-
- checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
- }
- },
-
- find: {
- ID: function( match, context, isXML ) {
- if ( typeof context.getElementById !== "undefined" && !isXML ) {
- var m = context.getElementById(match[1]);
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- return m && m.parentNode ? [m] : [];
- }
- },
-
- NAME: function( match, context ) {
- if ( typeof context.getElementsByName !== "undefined" ) {
- var ret = [],
- results = context.getElementsByName( match[1] );
-
- for ( var i = 0, l = results.length; i < l; i++ ) {
- if ( results[i].getAttribute("name") === match[1] ) {
- ret.push( results[i] );
- }
- }
-
- return ret.length === 0 ? null : ret;
- }
- },
-
- TAG: function( match, context ) {
- if ( typeof context.getElementsByTagName !== "undefined" ) {
- return context.getElementsByTagName( match[1] );
- }
- }
- },
- preFilter: {
- CLASS: function( match, curLoop, inplace, result, not, isXML ) {
- match = " " + match[1].replace( rBackslash, "" ) + " ";
-
- if ( isXML ) {
- return match;
- }
-
- for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
- if ( elem ) {
- if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
- if ( !inplace ) {
- result.push( elem );
- }
-
- } else if ( inplace ) {
- curLoop[i] = false;
- }
- }
- }
-
- return false;
- },
-
- ID: function( match ) {
- return match[1].replace( rBackslash, "" );
- },
-
- TAG: function( match, curLoop ) {
- return match[1].replace( rBackslash, "" ).toLowerCase();
- },
-
- CHILD: function( match ) {
- if ( match[1] === "nth" ) {
- if ( !match[2] ) {
- Sizzle.error( match[0] );
- }
-
- match[2] = match[2].replace(/^\+|\s*/g, '');
-
- // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
- var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
- match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
- !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
-
- // calculate the numbers (first)n+(last) including if they are negative
- match[2] = (test[1] + (test[2] || 1)) - 0;
- match[3] = test[3] - 0;
- }
- else if ( match[2] ) {
- Sizzle.error( match[0] );
- }
-
- // TODO: Move to normal caching system
- match[0] = done++;
-
- return match;
- },
-
- ATTR: function( match, curLoop, inplace, result, not, isXML ) {
- var name = match[1] = match[1].replace( rBackslash, "" );
-
- if ( !isXML && Expr.attrMap[name] ) {
- match[1] = Expr.attrMap[name];
- }
-
- // Handle if an un-quoted value was used
- match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
-
- if ( match[2] === "~=" ) {
- match[4] = " " + match[4] + " ";
- }
-
- return match;
- },
-
- PSEUDO: function( match, curLoop, inplace, result, not ) {
- if ( match[1] === "not" ) {
- // If we're dealing with a complex expression, or a simple one
- if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
- match[3] = Sizzle(match[3], null, null, curLoop);
-
- } else {
- var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
-
- if ( !inplace ) {
- result.push.apply( result, ret );
- }
-
- return false;
- }
-
- } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
- return true;
- }
-
- return match;
- },
-
- POS: function( match ) {
- match.unshift( true );
-
- return match;
- }
- },
-
- filters: {
- enabled: function( elem ) {
- return elem.disabled === false && elem.type !== "hidden";
- },
-
- disabled: function( elem ) {
- return elem.disabled === true;
- },
-
- checked: function( elem ) {
- return elem.checked === true;
- },
-
- selected: function( elem ) {
- // Accessing this property makes selected-by-default
- // options in Safari work properly
- if ( elem.parentNode ) {
- elem.parentNode.selectedIndex;
- }
-
- return elem.selected === true;
- },
-
- parent: function( elem ) {
- return !!elem.firstChild;
- },
-
- empty: function( elem ) {
- return !elem.firstChild;
- },
-
- has: function( elem, i, match ) {
- return !!Sizzle( match[3], elem ).length;
- },
-
- header: function( elem ) {
- return (/h\d/i).test( elem.nodeName );
- },
-
- text: function( elem ) {
- var attr = elem.getAttribute( "type" ), type = elem.type;
- // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
- // use getAttribute instead to test this case
- return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
- },
-
- radio: function( elem ) {
- return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
- },
-
- checkbox: function( elem ) {
- return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
- },
-
- file: function( elem ) {
- return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
- },
-
- password: function( elem ) {
- return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
- },
-
- submit: function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return (name === "input" || name === "button") && "submit" === elem.type;
- },
-
- image: function( elem ) {
- return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
- },
-
- reset: function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return (name === "input" || name === "button") && "reset" === elem.type;
- },
-
- button: function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && "button" === elem.type || name === "button";
- },
-
- input: function( elem ) {
- return (/input|select|textarea|button/i).test( elem.nodeName );
- },
-
- focus: function( elem ) {
- return elem === elem.ownerDocument.activeElement;
- }
- },
- setFilters: {
- first: function( elem, i ) {
- return i === 0;
- },
-
- last: function( elem, i, match, array ) {
- return i === array.length - 1;
- },
-
- even: function( elem, i ) {
- return i % 2 === 0;
- },
-
- odd: function( elem, i ) {
- return i % 2 === 1;
- },
-
- lt: function( elem, i, match ) {
- return i < match[3] - 0;
- },
-
- gt: function( elem, i, match ) {
- return i > match[3] - 0;
- },
-
- nth: function( elem, i, match ) {
- return match[3] - 0 === i;
- },
-
- eq: function( elem, i, match ) {
- return match[3] - 0 === i;
- }
- },
- filter: {
- PSEUDO: function( elem, match, i, array ) {
- var name = match[1],
- filter = Expr.filters[ name ];
-
- if ( filter ) {
- return filter( elem, i, match, array );
-
- } else if ( name === "contains" ) {
- return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
-
- } else if ( name === "not" ) {
- var not = match[3];
-
- for ( var j = 0, l = not.length; j < l; j++ ) {
- if ( not[j] === elem ) {
- return false;
- }
- }
-
- return true;
-
- } else {
- Sizzle.error( name );
- }
- },
-
- CHILD: function( elem, match ) {
- var first, last,
- doneName, parent, cache,
- count, diff,
- type = match[1],
- node = elem;
-
- switch ( type ) {
- case "only":
- case "first":
- while ( (node = node.previousSibling) ) {
- if ( node.nodeType === 1 ) {
- return false;
- }
- }
-
- if ( type === "first" ) {
- return true;
- }
-
- node = elem;
-
- /* falls through */
- case "last":
- while ( (node = node.nextSibling) ) {
- if ( node.nodeType === 1 ) {
- return false;
- }
- }
-
- return true;
-
- case "nth":
- first = match[2];
- last = match[3];
-
- if ( first === 1 && last === 0 ) {
- return true;
- }
-
- doneName = match[0];
- parent = elem.parentNode;
-
- if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
- count = 0;
-
- for ( node = parent.firstChild; node; node = node.nextSibling ) {
- if ( node.nodeType === 1 ) {
- node.nodeIndex = ++count;
- }
- }
-
- parent[ expando ] = doneName;
- }
-
- diff = elem.nodeIndex - last;
-
- if ( first === 0 ) {
- return diff === 0;
-
- } else {
- return ( diff % first === 0 && diff / first >= 0 );
- }
- }
- },
-
- ID: function( elem, match ) {
- return elem.nodeType === 1 && elem.getAttribute("id") === match;
- },
-
- TAG: function( elem, match ) {
- return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
- },
-
- CLASS: function( elem, match ) {
- return (" " + (elem.className || elem.getAttribute("class")) + " ")
- .indexOf( match ) > -1;
- },
-
- ATTR: function( elem, match ) {
- var name = match[1],
- result = Sizzle.attr ?
- Sizzle.attr( elem, name ) :
- Expr.attrHandle[ name ] ?
- Expr.attrHandle[ name ]( elem ) :
- elem[ name ] != null ?
- elem[ name ] :
- elem.getAttribute( name ),
- value = result + "",
- type = match[2],
- check = match[4];
-
- return result == null ?
- type === "!=" :
- !type && Sizzle.attr ?
- result != null :
- type === "=" ?
- value === check :
- type === "*=" ?
- value.indexOf(check) >= 0 :
- type === "~=" ?
- (" " + value + " ").indexOf(check) >= 0 :
- !check ?
- value && result !== false :
- type === "!=" ?
- value !== check :
- type === "^=" ?
- value.indexOf(check) === 0 :
- type === "$=" ?
- value.substr(value.length - check.length) === check :
- type === "|=" ?
- value === check || value.substr(0, check.length + 1) === check + "-" :
- false;
- },
-
- POS: function( elem, match, i, array ) {
- var name = match[2],
- filter = Expr.setFilters[ name ];
-
- if ( filter ) {
- return filter( elem, i, match, array );
- }
- }
- }
-};
-
-var origPOS = Expr.match.POS,
- fescape = function(all, num){
- return "\\" + (num - 0 + 1);
- };
-
-for ( var type in Expr.match ) {
- Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
- Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
-}
-// Expose origPOS
-// "global" as in regardless of relation to brackets/parens
-Expr.match.globalPOS = origPOS;
-
-var makeArray = function( array, results ) {
- array = Array.prototype.slice.call( array, 0 );
-
- if ( results ) {
- results.push.apply( results, array );
- return results;
- }
-
- return array;
-};
-
-// Perform a simple check to determine if the browser is capable of
-// converting a NodeList to an array using builtin methods.
-// Also verifies that the returned array holds DOM nodes
-// (which is not the case in the Blackberry browser)
-try {
- Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
-
-// Provide a fallback method if it does not work
-} catch( e ) {
- makeArray = function( array, results ) {
- var i = 0,
- ret = results || [];
-
- if ( toString.call(array) === "[object Array]" ) {
- Array.prototype.push.apply( ret, array );
-
- } else {
- if ( typeof array.length === "number" ) {
- for ( var l = array.length; i < l; i++ ) {
- ret.push( array[i] );
- }
-
- } else {
- for ( ; array[i]; i++ ) {
- ret.push( array[i] );
- }
- }
- }
-
- return ret;
- };
-}
-
-var sortOrder, siblingCheck;
-
-if ( document.documentElement.compareDocumentPosition ) {
- sortOrder = function( a, b ) {
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
- }
-
- if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
- return a.compareDocumentPosition ? -1 : 1;
- }
-
- return a.compareDocumentPosition(b) & 4 ? -1 : 1;
- };
-
-} else {
- sortOrder = function( a, b ) {
- // The nodes are identical, we can exit early
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
-
- // Fallback to using sourceIndex (in IE) if it's available on both nodes
- } else if ( a.sourceIndex && b.sourceIndex ) {
- return a.sourceIndex - b.sourceIndex;
- }
-
- var al, bl,
- ap = [],
- bp = [],
- aup = a.parentNode,
- bup = b.parentNode,
- cur = aup;
-
- // If the nodes are siblings (or identical) we can do a quick check
- if ( aup === bup ) {
- return siblingCheck( a, b );
-
- // If no parents were found then the nodes are disconnected
- } else if ( !aup ) {
- return -1;
-
- } else if ( !bup ) {
- return 1;
- }
-
- // Otherwise they're somewhere else in the tree so we need
- // to build up a full list of the parentNodes for comparison
- while ( cur ) {
- ap.unshift( cur );
- cur = cur.parentNode;
- }
-
- cur = bup;
-
- while ( cur ) {
- bp.unshift( cur );
- cur = cur.parentNode;
- }
-
- al = ap.length;
- bl = bp.length;
-
- // Start walking down the tree looking for a discrepancy
- for ( var i = 0; i < al && i < bl; i++ ) {
- if ( ap[i] !== bp[i] ) {
- return siblingCheck( ap[i], bp[i] );
- }
- }
-
- // We ended someplace up the tree so do a sibling check
- return i === al ?
- siblingCheck( a, bp[i], -1 ) :
- siblingCheck( ap[i], b, 1 );
- };
-
- siblingCheck = function( a, b, ret ) {
- if ( a === b ) {
- return ret;
- }
-
- var cur = a.nextSibling;
-
- while ( cur ) {
- if ( cur === b ) {
- return -1;
- }
-
- cur = cur.nextSibling;
- }
-
- return 1;
- };
-}
-
-// Check to see if the browser returns elements by name when
-// querying by getElementById (and provide a workaround)
-(function(){
- // We're going to inject a fake input element with a specified name
- var form = document.createElement("div"),
- id = "script" + (new Date()).getTime(),
- root = document.documentElement;
-
- form.innerHTML = "";
-
- // Inject it into the root element, check its status, and remove it quickly
- root.insertBefore( form, root.firstChild );
-
- // The workaround has to do additional checks after a getElementById
- // Which slows things down for other browsers (hence the branching)
- if ( document.getElementById( id ) ) {
- Expr.find.ID = function( match, context, isXML ) {
- if ( typeof context.getElementById !== "undefined" && !isXML ) {
- var m = context.getElementById(match[1]);
-
- return m ?
- m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
- [m] :
- undefined :
- [];
- }
- };
-
- Expr.filter.ID = function( elem, match ) {
- var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
-
- return elem.nodeType === 1 && node && node.nodeValue === match;
- };
- }
-
- root.removeChild( form );
-
- // release memory in IE
- root = form = null;
-})();
-
-(function(){
- // Check to see if the browser returns only elements
- // when doing getElementsByTagName("*")
-
- // Create a fake element
- var div = document.createElement("div");
- div.appendChild( document.createComment("") );
-
- // Make sure no comments are found
- if ( div.getElementsByTagName("*").length > 0 ) {
- Expr.find.TAG = function( match, context ) {
- var results = context.getElementsByTagName( match[1] );
-
- // Filter out possible comments
- if ( match[1] === "*" ) {
- var tmp = [];
-
- for ( var i = 0; results[i]; i++ ) {
- if ( results[i].nodeType === 1 ) {
- tmp.push( results[i] );
- }
- }
-
- results = tmp;
- }
-
- return results;
- };
- }
-
- // Check to see if an attribute returns normalized href attributes
- div.innerHTML = "";
-
- if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
- div.firstChild.getAttribute("href") !== "#" ) {
-
- Expr.attrHandle.href = function( elem ) {
- return elem.getAttribute( "href", 2 );
- };
- }
-
- // release memory in IE
- div = null;
-})();
-
-if ( document.querySelectorAll ) {
- (function(){
- var oldSizzle = Sizzle,
- div = document.createElement("div"),
- id = "__sizzle__";
-
- div.innerHTML = "";
-
- // Safari can't handle uppercase or unicode characters when
- // in quirks mode.
- if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
- return;
- }
-
- Sizzle = function( query, context, extra, seed ) {
- context = context || document;
-
- // Only use querySelectorAll on non-XML documents
- // (ID selectors don't work in non-HTML documents)
- if ( !seed && !Sizzle.isXML(context) ) {
- // See if we find a selector to speed up
- var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
-
- if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
- // Speed-up: Sizzle("TAG")
- if ( match[1] ) {
- return makeArray( context.getElementsByTagName( query ), extra );
-
- // Speed-up: Sizzle(".CLASS")
- } else if ( match[2] && Expr.find.CLASS && context.getElementsByMethodName ) {
- return makeArray( context.getElementsByMethodName( match[2] ), extra );
- }
- }
-
- if ( context.nodeType === 9 ) {
- // Speed-up: Sizzle("body")
- // The body element only exists once, optimize finding it
- if ( query === "body" && context.body ) {
- return makeArray( [ context.body ], extra );
-
- // Speed-up: Sizzle("#ID")
- } else if ( match && match[3] ) {
- var elem = context.getElementById( match[3] );
-
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- if ( elem && elem.parentNode ) {
- // Handle the case where IE and Opera return items
- // by name instead of ID
- if ( elem.id === match[3] ) {
- return makeArray( [ elem ], extra );
- }
-
- } else {
- return makeArray( [], extra );
- }
- }
-
- try {
- return makeArray( context.querySelectorAll(query), extra );
- } catch(qsaError) {}
-
- // qSA works strangely on Element-rooted queries
- // We can work around this by specifying an extra ID on the root
- // and working up from there (Thanks to Andrew Dupont for the technique)
- // IE 8 doesn't work on object elements
- } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
- var oldContext = context,
- old = context.getAttribute( "id" ),
- nid = old || id,
- hasParent = context.parentNode,
- relativeHierarchySelector = /^\s*[+~]/.test( query );
-
- if ( !old ) {
- context.setAttribute( "id", nid );
- } else {
- nid = nid.replace( /'/g, "\\$&" );
- }
- if ( relativeHierarchySelector && hasParent ) {
- context = context.parentNode;
- }
-
- try {
- if ( !relativeHierarchySelector || hasParent ) {
- return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
- }
-
- } catch(pseudoError) {
- } finally {
- if ( !old ) {
- oldContext.removeAttribute( "id" );
- }
- }
- }
- }
-
- return oldSizzle(query, context, extra, seed);
- };
-
- for ( var prop in oldSizzle ) {
- Sizzle[ prop ] = oldSizzle[ prop ];
- }
-
- // release memory in IE
- div = null;
- })();
-}
-
-(function(){
- var html = document.documentElement,
- matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
-
- if ( matches ) {
- // Check to see if it's possible to do matchesSelector
- // on a disconnected node (IE 9 fails this)
- var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
- pseudoWorks = false;
-
- try {
- // This should fail with an exception
- // Gecko does not error, returns false instead
- matches.call( document.documentElement, "[test!='']:sizzle" );
-
- } catch( pseudoError ) {
- pseudoWorks = true;
- }
-
- Sizzle.matchesSelector = function( node, expr ) {
- // Make sure that attribute selectors are quoted
- expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
-
- if ( !Sizzle.isXML( node ) ) {
- try {
- if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
- var ret = matches.call( node, expr );
-
- // IE 9's matchesSelector returns false on disconnected nodes
- if ( ret || !disconnectedMatch ||
- // As well, disconnected nodes are said to be in a document
- // fragment in IE 9, so check for that
- node.document && node.document.nodeType !== 11 ) {
- return ret;
- }
- }
- } catch(e) {}
- }
-
- return Sizzle(expr, null, null, [node]).length > 0;
- };
- }
-})();
-
-(function(){
- var div = document.createElement("div");
-
- div.innerHTML = "";
-
- // Opera can't find a second classname (in 9.6)
- // Also, make sure that getElementsByMethodName actually exists
- if ( !div.getElementsByMethodName || div.getElementsByMethodName("e").length === 0 ) {
- return;
- }
-
- // Safari caches class attributes, doesn't catch changes (in 3.2)
- div.lastChild.className = "e";
-
- if ( div.getElementsByMethodName("e").length === 1 ) {
- return;
- }
-
- Expr.order.splice(1, 0, "CLASS");
- Expr.find.CLASS = function( match, context, isXML ) {
- if ( typeof context.getElementsByMethodName !== "undefined" && !isXML ) {
- return context.getElementsByMethodName(match[1]);
- }
- };
-
- // release memory in IE
- div = null;
-})();
-
-function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
- for ( var i = 0, l = checkSet.length; i < l; i++ ) {
- var elem = checkSet[i];
-
- if ( elem ) {
- var match = false;
-
- elem = elem[dir];
-
- while ( elem ) {
- if ( elem[ expando ] === doneName ) {
- match = checkSet[elem.sizset];
- break;
- }
-
- if ( elem.nodeType === 1 && !isXML ){
- elem[ expando ] = doneName;
- elem.sizset = i;
- }
-
- if ( elem.nodeName.toLowerCase() === cur ) {
- match = elem;
- break;
- }
-
- elem = elem[dir];
- }
-
- checkSet[i] = match;
- }
- }
-}
-
-function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
- for ( var i = 0, l = checkSet.length; i < l; i++ ) {
- var elem = checkSet[i];
-
- if ( elem ) {
- var match = false;
-
- elem = elem[dir];
-
- while ( elem ) {
- if ( elem[ expando ] === doneName ) {
- match = checkSet[elem.sizset];
- break;
- }
-
- if ( elem.nodeType === 1 ) {
- if ( !isXML ) {
- elem[ expando ] = doneName;
- elem.sizset = i;
- }
-
- if ( typeof cur !== "string" ) {
- if ( elem === cur ) {
- match = true;
- break;
- }
-
- } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
- match = elem;
- break;
- }
- }
-
- elem = elem[dir];
- }
-
- checkSet[i] = match;
- }
- }
-}
-
-if ( document.documentElement.contains ) {
- Sizzle.contains = function( a, b ) {
- return a !== b && (a.contains ? a.contains(b) : true);
- };
-
-} else if ( document.documentElement.compareDocumentPosition ) {
- Sizzle.contains = function( a, b ) {
- return !!(a.compareDocumentPosition(b) & 16);
- };
-
-} else {
- Sizzle.contains = function() {
- return false;
- };
-}
-
-Sizzle.isXML = function( elem ) {
- // documentElement is verified for cases where it doesn't yet exist
- // (such as loading iframes in IE - #4833)
- var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
-
- return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-var posProcess = function( selector, context, seed ) {
- var match,
- tmpSet = [],
- later = "",
- root = context.nodeType ? [context] : context;
-
- // Position selectors must be done after the filter
- // And so must :not(positional) so we move all PSEUDOs to the end
- while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
- later += match[0];
- selector = selector.replace( Expr.match.PSEUDO, "" );
- }
-
- selector = Expr.relative[selector] ? selector + "*" : selector;
-
- for ( var i = 0, l = root.length; i < l; i++ ) {
- Sizzle( selector, root[i], tmpSet, seed );
- }
-
- return Sizzle.filter( later, tmpSet );
-};
-
-// EXPOSE
-// Override sizzle attribute retrieval
-Sizzle.attr = jQuery.attr;
-Sizzle.selectors.attrMap = {};
-jQuery.find = Sizzle;
-jQuery.expr = Sizzle.selectors;
-jQuery.expr[":"] = jQuery.expr.filters;
-jQuery.unique = Sizzle.uniqueSort;
-jQuery.text = Sizzle.getText;
-jQuery.isXMLDoc = Sizzle.isXML;
-jQuery.contains = Sizzle.contains;
-
-
-})();
-
-
-var runtil = /Until$/,
- rparentsprev = /^(?:parents|prevUntil|prevAll)/,
- // Note: This RegExp should be improved, or likely pulled from Sizzle
- rmultiselector = /,/,
- isSimple = /^.[^:#\[\.,]*$/,
- slice = Array.prototype.slice,
- POS = jQuery.expr.match.globalPOS,
- // methods guaranteed to produce a unique set when starting from a unique set
- guaranteedUnique = {
- children: true,
- contents: true,
- next: true,
- prev: true
- };
-
-jQuery.fn.extend({
- find: function( selector ) {
- var self = this,
- i, l;
-
- if ( typeof selector !== "string" ) {
- return jQuery( selector ).filter(function() {
- for ( i = 0, l = self.length; i < l; i++ ) {
- if ( jQuery.contains( self[ i ], this ) ) {
- return true;
- }
- }
- });
- }
-
- var ret = this.pushStack( "", "find", selector ),
- length, n, r;
-
- for ( i = 0, l = this.length; i < l; i++ ) {
- length = ret.length;
- jQuery.find( selector, this[i], ret );
-
- if ( i > 0 ) {
- // Make sure that the results are unique
- for ( n = length; n < ret.length; n++ ) {
- for ( r = 0; r < length; r++ ) {
- if ( ret[r] === ret[n] ) {
- ret.splice(n--, 1);
- break;
- }
- }
- }
- }
- }
-
- return ret;
- },
-
- has: function( target ) {
- var targets = jQuery( target );
- return this.filter(function() {
- for ( var i = 0, l = targets.length; i < l; i++ ) {
- if ( jQuery.contains( this, targets[i] ) ) {
- return true;
- }
- }
- });
- },
-
- not: function( selector ) {
- return this.pushStack( winnow(this, selector, false), "not", selector);
- },
-
- filter: function( selector ) {
- return this.pushStack( winnow(this, selector, true), "filter", selector );
- },
-
- is: function( selector ) {
- return !!selector && (
- typeof selector === "string" ?
- // If this is a positional selector, check membership in the returned set
- // so $("p:first").is("p:last") won't return true for a doc with two "p".
- POS.test( selector ) ?
- jQuery( selector, this.context ).index( this[0] ) >= 0 :
- jQuery.filter( selector, this ).length > 0 :
- this.filter( selector ).length > 0 );
- },
-
- closest: function( selectors, context ) {
- var ret = [], i, l, cur = this[0];
-
- // Array (deprecated as of jQuery 1.7)
- if ( jQuery.isArray( selectors ) ) {
- var level = 1;
-
- while ( cur && cur.ownerDocument && cur !== context ) {
- for ( i = 0; i < selectors.length; i++ ) {
-
- if ( jQuery( cur ).is( selectors[ i ] ) ) {
- ret.push({ selector: selectors[ i ], elem: cur, level: level });
- }
- }
-
- cur = cur.parentNode;
- level++;
- }
-
- return ret;
- }
-
- // String
- var pos = POS.test( selectors ) || typeof selectors !== "string" ?
- jQuery( selectors, context || this.context ) :
- 0;
-
- for ( i = 0, l = this.length; i < l; i++ ) {
- cur = this[i];
-
- while ( cur ) {
- if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
- ret.push( cur );
- break;
-
- } else {
- cur = cur.parentNode;
- if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
- break;
- }
- }
- }
- }
-
- ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
-
- return this.pushStack( ret, "closest", selectors );
- },
-
- // Determine the position of an element within
- // the matched set of elements
- index: function( elem ) {
-
- // No argument, return index in parent
- if ( !elem ) {
- return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
- }
-
- // index in selector
- if ( typeof elem === "string" ) {
- return jQuery.inArray( this[0], jQuery( elem ) );
- }
-
- // Locate the position of the desired element
- return jQuery.inArray(
- // If it receives a jQuery object, the first element is used
- elem.jquery ? elem[0] : elem, this );
- },
-
- add: function( selector, context ) {
- var set = typeof selector === "string" ?
- jQuery( selector, context ) :
- jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
- all = jQuery.merge( this.get(), set );
-
- return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
- all :
- jQuery.unique( all ) );
- },
-
- andSelf: function() {
- return this.add( this.prevObject );
- }
-});
-
-// A painfully simple check to see if an element is disconnected
-// from a document (should be improved, where feasible).
-function isDisconnected( node ) {
- return !node || !node.parentNode || node.parentNode.nodeType === 11;
-}
-
-jQuery.each({
- parent: function( elem ) {
- var parent = elem.parentNode;
- return parent && parent.nodeType !== 11 ? parent : null;
- },
- parents: function( elem ) {
- return jQuery.dir( elem, "parentNode" );
- },
- parentsUntil: function( elem, i, until ) {
- return jQuery.dir( elem, "parentNode", until );
- },
- next: function( elem ) {
- return jQuery.nth( elem, 2, "nextSibling" );
- },
- prev: function( elem ) {
- return jQuery.nth( elem, 2, "previousSibling" );
- },
- nextAll: function( elem ) {
- return jQuery.dir( elem, "nextSibling" );
- },
- prevAll: function( elem ) {
- return jQuery.dir( elem, "previousSibling" );
- },
- nextUntil: function( elem, i, until ) {
- return jQuery.dir( elem, "nextSibling", until );
- },
- prevUntil: function( elem, i, until ) {
- return jQuery.dir( elem, "previousSibling", until );
- },
- siblings: function( elem ) {
- return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
- },
- children: function( elem ) {
- return jQuery.sibling( elem.firstChild );
- },
- contents: function( elem ) {
- return jQuery.nodeName( elem, "iframe" ) ?
- elem.contentDocument || elem.contentWindow.document :
- jQuery.makeArray( elem.childNodes );
- }
-}, function( name, fn ) {
- jQuery.fn[ name ] = function( until, selector ) {
- var ret = jQuery.map( this, fn, until );
-
- if ( !runtil.test( name ) ) {
- selector = until;
- }
-
- if ( selector && typeof selector === "string" ) {
- ret = jQuery.filter( selector, ret );
- }
-
- ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
-
- if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
- ret = ret.reverse();
- }
-
- return this.pushStack( ret, name, slice.call( arguments ).join(",") );
- };
-});
-
-jQuery.extend({
- filter: function( expr, elems, not ) {
- if ( not ) {
- expr = ":not(" + expr + ")";
- }
-
- return elems.length === 1 ?
- jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
- jQuery.find.matches(expr, elems);
- },
-
- dir: function( elem, dir, until ) {
- var matched = [],
- cur = elem[ dir ];
-
- while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
- if ( cur.nodeType === 1 ) {
- matched.push( cur );
- }
- cur = cur[dir];
- }
- return matched;
- },
-
- nth: function( cur, result, dir, elem ) {
- result = result || 1;
- var num = 0;
-
- for ( ; cur; cur = cur[dir] ) {
- if ( cur.nodeType === 1 && ++num === result ) {
- break;
- }
- }
-
- return cur;
- },
-
- sibling: function( n, elem ) {
- var r = [];
-
- for ( ; n; n = n.nextSibling ) {
- if ( n.nodeType === 1 && n !== elem ) {
- r.push( n );
- }
- }
-
- return r;
- }
-});
-
-// Implement the identical functionality for filter and not
-function winnow( elements, qualifier, keep ) {
-
- // Can't pass null or undefined to indexOf in Firefox 4
- // Set to 0 to skip string check
- qualifier = qualifier || 0;
-
- if ( jQuery.isFunction( qualifier ) ) {
- return jQuery.grep(elements, function( elem, i ) {
- var retVal = !!qualifier.call( elem, i, elem );
- return retVal === keep;
- });
-
- } else if ( qualifier.nodeType ) {
- return jQuery.grep(elements, function( elem, i ) {
- return ( elem === qualifier ) === keep;
- });
-
- } else if ( typeof qualifier === "string" ) {
- var filtered = jQuery.grep(elements, function( elem ) {
- return elem.nodeType === 1;
- });
-
- if ( isSimple.test( qualifier ) ) {
- return jQuery.filter(qualifier, filtered, !keep);
- } else {
- qualifier = jQuery.filter( qualifier, filtered );
- }
- }
-
- return jQuery.grep(elements, function( elem, i ) {
- return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
- });
-}
-
-
-
-
-function createSafeFragment( document ) {
- var list = nodeNames.split( "|" ),
- safeFrag = document.createDocumentFragment();
-
- if ( safeFrag.createElement ) {
- while ( list.length ) {
- safeFrag.createElement(
- list.pop()
- );
- }
- }
- return safeFrag;
-}
-
-var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
- "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
- rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
- rleadingWhitespace = /^\s+/,
- rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
- rtagName = /<([\w:]+)/,
- rtbody = /]", "i"),
- // checked="checked" or checked
- rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
- rscriptType = /\/(java|ecma)script/i,
- rcleanScript = /^\s*", "" ],
- legend: [ 1, "" ],
- thead: [ 1, "