django-cas-server/cas_server/views.py

1419 lines
58 KiB
Python
Raw Normal View History

2016-07-03 16:11:48 +00:00
# -*- coding: utf-8 -*-
2015-05-27 20:10:06 +00:00
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License version 3 for
# more details.
#
# You should have received a copy of the GNU General Public License version 3
# along with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
2016-06-30 22:00:53 +00:00
# (c) 2015-2016 Valentin Samir
2015-05-27 19:56:39 +00:00
"""views for the app"""
2016-07-20 16:28:23 +00:00
from .default_settings import settings, SessionStore
2015-05-16 21:43:46 +00:00
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
2015-05-27 19:56:39 +00:00
from django.http import HttpResponse, HttpResponseRedirect
2015-05-16 21:43:46 +00:00
from django.contrib import messages
from django.utils.decorators import method_decorator
2015-05-22 15:55:00 +00:00
from django.utils.translation import ugettext as _
2015-05-27 19:56:39 +00:00
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
2016-06-23 15:18:53 +00:00
from django.middleware.csrf import CsrfViewMiddleware
2015-05-29 14:11:10 +00:00
from django.views.generic import View
from django.utils.encoding import python_2_unicode_compatible
2015-05-16 21:43:46 +00:00
import re
2015-12-13 12:50:29 +00:00
import logging
import pprint
2015-05-16 21:43:46 +00:00
import requests
2015-05-22 17:31:50 +00:00
from lxml import etree
2015-05-27 19:56:39 +00:00
from datetime import timedelta
2015-05-16 21:43:46 +00:00
2015-06-21 16:56:16 +00:00
import cas_server.utils as utils
import cas_server.forms as forms
import cas_server.models as models
2015-05-16 21:43:46 +00:00
2016-06-26 14:02:25 +00:00
from .utils import json_response
2016-07-23 16:43:27 +00:00
from .models import Ticket, ServiceTicket, ProxyTicket, ProxyGrantingTicket
from .models import ServicePattern, FederatedIendityProvider, FederatedUser
2016-06-17 17:28:49 +00:00
from .federate import CASFederateValidateUser
2015-06-08 00:51:22 +00:00
2015-12-13 12:50:29 +00:00
logger = logging.getLogger(__name__)
2015-06-12 16:10:52 +00:00
2015-05-29 14:14:27 +00:00
class LogoutMixin(object):
"""destroy CAS session utils"""
2016-06-26 09:16:41 +00:00
def logout(self, all_session=False):
2016-07-23 16:41:46 +00:00
"""
effectively destroy a CAS session
:param boolean all_session: If ``True`` destroy all the user sessions, otherwise
destroy the current user session.
:return: The number of destroyed sessions
:rtype: int
"""
# initialize the counter of the number of destroyed sesisons
session_nb = 0
2016-07-23 16:41:46 +00:00
# save the current user username before flushing the session
2015-12-13 12:50:29 +00:00
username = self.request.session.get("username")
if username:
2016-06-26 09:16:41 +00:00
if all_session:
2015-12-13 12:50:29 +00:00
logger.info("Logging out user %s from all of they sessions." % username)
else:
logger.info("Logging out user %s." % username)
# logout the user from the current session
2015-05-29 14:11:10 +00:00
try:
2015-06-09 20:04:05 +00:00
user = models.User.objects.get(
username=username,
2015-06-11 21:34:25 +00:00
session_key=self.request.session.session_key
2015-06-09 20:04:05 +00:00
)
2016-07-23 16:41:46 +00:00
# flush the session
self.request.session.flush()
2016-07-23 16:41:46 +00:00
# send SLO requests
2015-05-29 14:11:10 +00:00
user.logout(self.request)
2016-07-23 16:41:46 +00:00
# delete the user
2015-05-29 14:11:10 +00:00
user.delete()
2016-07-23 16:41:46 +00:00
# increment the destroyed session counter
session_nb += 1
2015-05-29 14:11:10 +00:00
except models.User.DoesNotExist:
# if user not found in database, flush the session anyway
self.request.session.flush()
2015-05-29 14:11:10 +00:00
2016-06-26 09:16:41 +00:00
# If all_session is set logout user from alternative sessions
if all_session:
2016-07-23 16:41:46 +00:00
# Iterate over all user sessions
for user in models.User.objects.filter(username=username):
2016-07-23 16:41:46 +00:00
# get the user session
session = SessionStore(session_key=user.session_key)
2016-07-23 16:41:46 +00:00
# flush the session
session.flush()
2016-07-23 16:41:46 +00:00
# send SLO requests
user.logout(self.request)
2016-07-23 16:41:46 +00:00
# delete the user
user.delete()
2016-07-23 16:41:46 +00:00
# increment the destroyed session counter
session_nb += 1
2016-07-23 16:41:46 +00:00
if username:
logger.info("User %s logged out" % username)
return session_nb
2015-06-12 16:10:52 +00:00
2015-05-29 14:14:27 +00:00
class LogoutView(View, LogoutMixin):
"""destroy CAS session (logout) view"""
2016-07-23 16:41:46 +00:00
#: current :class:`django.http.HttpRequest` object
2015-05-29 14:14:27 +00:00
request = None
2016-07-23 16:41:46 +00:00
#: service GET parameter
2015-05-29 14:14:27 +00:00
service = None
2016-07-23 16:41:46 +00:00
#: url GET paramet
url = None
#: ``True`` if the HTTP_X_AJAX http header is sent and ``settings.CAS_ENABLE_AJAX_AUTH``
#: is ``True``, ``False`` otherwise.
ajax = None
2015-05-29 14:14:27 +00:00
2015-06-12 21:57:11 +00:00
def init_get(self, request):
2016-07-23 16:41:46 +00:00
"""
Initialize the :class:`LogoutView` attributes on GET request
:param django.http.HttpRequest request: The current request object
"""
2015-05-29 14:11:10 +00:00
self.request = request
self.service = request.GET.get('service')
2015-06-07 14:53:27 +00:00
self.url = request.GET.get('url')
2016-06-30 16:57:11 +00:00
self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
2015-06-12 21:57:11 +00:00
def get(self, request, *args, **kwargs):
2016-07-23 16:41:46 +00:00
"""
methode called on GET request on this view
:param django.http.HttpRequest request: The current request object
"""
2015-12-13 12:50:29 +00:00
logger.info("logout requested")
2016-07-23 16:41:46 +00:00
# initialize the class attributes
2015-06-12 21:57:11 +00:00
self.init_get(request)
2016-06-17 17:28:49 +00:00
# if CAS federation mode is enable, bakup the provider before flushing the sessions
if settings.CAS_FEDERATE:
try:
user = FederatedUser.get_from_federated_username(
self.request.session.get("username")
)
auth = CASFederateValidateUser(user.provider, service_url="")
except FederatedUser.DoesNotExist:
auth = None
session_nb = self.logout(self.request.GET.get("all"))
2016-07-23 16:41:46 +00:00
# if CAS federation mode is enable, redirect to user CAS logout page, appending the
# current querystring
2016-06-17 17:28:49 +00:00
if settings.CAS_FEDERATE:
if auth is not None:
params = utils.copy_params(request.GET)
url = auth.get_logout_url()
return HttpResponseRedirect(utils.update_url(url, params))
2015-05-29 14:11:10 +00:00
# if service is set, redirect to service after logout
if self.service:
2015-06-12 16:10:52 +00:00
list(messages.get_messages(request)) # clean messages before leaving the django app
2015-05-29 14:11:10 +00:00
return HttpResponseRedirect(self.service)
2016-07-23 16:41:46 +00:00
# if service is not set but url is set, redirect to url after logout
2015-06-07 14:53:27 +00:00
elif self.url:
2015-06-12 16:10:52 +00:00
list(messages.get_messages(request)) # clean messages before leaving the django app
2015-06-07 14:53:27 +00:00
return HttpResponseRedirect(self.url)
2015-05-29 14:11:10 +00:00
else:
2016-07-23 16:41:46 +00:00
# build logout message depending of the number of sessions the user logs out
if session_nb == 1:
logout_msg = _(
"<h3>Logout successful</h3>"
"You have successfully logged out from the Central Authentication Service. "
"For security reasons, exit your web browser."
)
elif session_nb > 1:
logout_msg = _(
"<h3>Logout successful</h3>"
"You have successfully logged out from %s sessions of the Central "
"Authentication Service. "
"For security reasons, exit your web browser."
) % session_nb
else:
logout_msg = _(
"<h3>Logout successful</h3>"
"You were already logged out from the Central Authentication Service. "
"For security reasons, exit your web browser."
)
2016-07-23 16:41:46 +00:00
# depending of settings, redirect to the login page with a logout message or display
# the logout page. The default is to display tge logout page.
if settings.CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT:
messages.add_message(request, messages.SUCCESS, logout_msg)
if self.ajax:
url = reverse("cas_server:login")
data = {
'status': 'success',
'detail': 'logout',
'url': url,
'session_nb': session_nb
}
2016-06-26 14:02:25 +00:00
return json_response(request, data)
else:
return redirect("cas_server:login")
else:
if self.ajax:
data = {'status': 'success', 'detail': 'logout', 'session_nb': session_nb}
2016-06-26 14:02:25 +00:00
return json_response(request, data)
else:
return render(
request,
settings.CAS_LOGOUT_TEMPLATE,
utils.context({'logout_msg': logout_msg})
)
2015-05-29 14:11:10 +00:00
2015-06-12 16:10:52 +00:00
2016-06-17 17:28:49 +00:00
class FederateAuth(View):
2016-07-03 15:54:11 +00:00
"""view to authenticated user agains a backend CAS then CAS_FEDERATE is True"""
2016-07-23 16:41:46 +00:00
@method_decorator(csrf_exempt) # csrf is disabled for allowing SLO requests reception
2016-06-23 15:18:53 +00:00
def dispatch(self, request, *args, **kwargs):
2016-07-23 16:41:46 +00:00
"""
dispatch different http request to the methods of the same name
:param django.http.HttpRequest request: The current request object
"""
2016-06-23 15:18:53 +00:00
return super(FederateAuth, self).dispatch(request, *args, **kwargs)
2016-06-27 22:48:48 +00:00
@staticmethod
def get_cas_client(request, provider):
2016-07-23 16:41:46 +00:00
"""
return a CAS client object matching provider
:param django.http.HttpRequest request: The current request object
:param cas_server.models.FederatedIendityProvider provider: the user identity provider
:return: The user CAS client object
2016-07-23 16:43:27 +00:00
:rtype: :class:`federate.CASFederateValidateUser
<cas_server.federate.CASFederateValidateUser>`
2016-07-23 16:41:46 +00:00
"""
# compute the current url, ignoring ticket dans provider GET parameters
service_url = utils.get_current_url(request, {"ticket", "provider"})
return CASFederateValidateUser(provider, service_url)
2016-06-23 15:18:53 +00:00
2016-06-17 17:28:49 +00:00
def post(self, request, provider=None):
2016-07-23 16:41:46 +00:00
"""
method called on POST request
:param django.http.HttpRequest request: The current request object
:param unicode provider: Optional parameter. The user provider suffix.
"""
# if settings.CAS_FEDERATE is not True redirect to the login page
if not settings.CAS_FEDERATE:
logger.warning("CAS_FEDERATE is False, set it to True to use the federated mode")
return redirect("cas_server:login")
2016-07-23 16:41:46 +00:00
# POST with a provider suffix, this is probably an SLO request. csrf is disabled for
# allowing SLO requests reception
try:
provider = FederatedIendityProvider.objects.get(suffix=provider)
2016-06-23 15:18:53 +00:00
auth = self.get_cas_client(request, provider)
try:
auth.clean_sessions(request.POST['logoutRequest'])
except (KeyError, AttributeError):
2016-06-23 15:18:53 +00:00
pass
return HttpResponse("ok")
# else, a User is trying to log in using an identity provider
except FederatedIendityProvider.DoesNotExist:
2016-06-23 15:18:53 +00:00
# Manually checking for csrf to protect the code below
reason = CsrfViewMiddleware().process_view(request, None, (), {})
if reason is not None: # pragma: no cover (csrf checks are disabled during tests)
2016-06-23 15:18:53 +00:00
return reason # Failed the test, stop here.
form = forms.FederateSelect(request.POST)
if form.is_valid():
params = utils.copy_params(
request.POST,
ignore={"provider", "csrfmiddlewaretoken", "ticket"}
)
url = utils.reverse_params(
"cas_server:federateAuth",
kwargs=dict(provider=form.cleaned_data["provider"].suffix),
2016-06-23 15:18:53 +00:00
params=params
)
response = HttpResponseRedirect(url)
2016-07-23 16:41:46 +00:00
# If the user has checked "remember my identity provider" store it in a cookie
2016-06-23 15:18:53 +00:00
if form.cleaned_data["remember"]:
max_age = settings.CAS_FEDERATE_REMEMBER_TIMEOUT
utils.set_cookie(
response,
"_remember_provider",
form.cleaned_data["provider"].suffix,
2016-06-23 15:18:53 +00:00
max_age
)
return response
else:
return redirect("cas_server:login")
2016-06-17 17:28:49 +00:00
def get(self, request, provider=None):
2016-07-23 16:41:46 +00:00
"""
method called on GET request
:param django.http.HttpRequest request: The current request object
:param unicode provider: Optional parameter. The user provider suffix.
"""
# if settings.CAS_FEDERATE is not True redirect to the login page
if not settings.CAS_FEDERATE:
logger.warning("CAS_FEDERATE is False, set it to True to use the federated mode")
return redirect("cas_server:login")
2016-07-23 16:41:46 +00:00
# Is the user is already authenticated, no need to request authentication to the user
# identity provider.
if self.request.session.get("authenticated"):
logger.warning("User already authenticated, dropping federate authentication request")
return redirect("cas_server:login")
try:
2016-07-23 16:41:46 +00:00
# get the identity provider from its suffix
provider = FederatedIendityProvider.objects.get(suffix=provider)
2016-07-23 16:41:46 +00:00
# get a CAS client for the user identity provider
auth = self.get_cas_client(request, provider)
2016-07-23 16:41:46 +00:00
# if no ticket submited, redirect to the identity provider CAS login page
if 'ticket' not in request.GET:
logger.info("Trying to authenticate again %s" % auth.provider.server_url)
2016-06-17 17:28:49 +00:00
return HttpResponseRedirect(auth.get_login_url())
else:
ticket = request.GET['ticket']
try:
# if the ticket validation succeed
if auth.verify_ticket(ticket):
logger.info(
"Got a valid ticket for %s from %s" % (
auth.username,
auth.provider.server_url
)
)
params = utils.copy_params(request.GET, ignore={"ticket"})
request.session["federate_username"] = auth.federated_username
request.session["federate_ticket"] = ticket
auth.register_slo(
auth.federated_username,
request.session.session_key,
ticket
)
# redirect to the the login page for the user to become authenticated
# thanks to the `federate_username` and `federate_ticket` session parameters
url = utils.reverse_params("cas_server:login", params)
return HttpResponseRedirect(url)
# else redirect to the identity provider CAS login page
else:
logger.info(
"Got a invalid ticket for %s from %s. Retrying to authenticate" % (
auth.username,
auth.provider.server_url
)
)
return HttpResponseRedirect(auth.get_login_url())
# both xml.etree.ElementTree and lxml.etree exceptions inherit from SyntaxError
except SyntaxError as error:
messages.add_message(
request,
messages.ERROR,
_(
u"Invalid response from your identity provider CAS upon "
u"ticket %(ticket)s validation: %(error)r"
) % {'ticket': ticket, 'error': error}
)
response = redirect("cas_server:login")
response.delete_cookie("_remember_provider")
return response
except FederatedIendityProvider.DoesNotExist:
logger.warning("Identity provider suffix %s not found" % provider)
2016-07-23 16:41:46 +00:00
# if the identity provider is not found, redirect to the login page
return redirect("cas_server:login")
2016-06-17 17:28:49 +00:00
2015-05-29 14:14:27 +00:00
class LoginView(View, LogoutMixin):
2015-05-27 19:56:39 +00:00
"""credential requestor / acceptor"""
2015-05-29 14:11:10 +00:00
# pylint: disable=too-many-instance-attributes
# Nine is reasonable in this case.
2016-07-23 16:41:46 +00:00
#: The current :class:`models.User<cas_server.models.User>` object
2015-05-16 21:43:46 +00:00
user = None
2016-07-23 16:41:46 +00:00
#: The form to display to the user
2015-05-16 21:43:46 +00:00
form = None
2015-05-29 14:11:10 +00:00
2016-07-23 16:41:46 +00:00
#: current :class:`django.http.HttpRequest` object
2015-05-29 14:11:10 +00:00
request = None
2016-07-23 16:41:46 +00:00
#: service GET/POST parameter
2015-05-29 14:11:10 +00:00
service = None
2016-07-23 16:41:46 +00:00
#: ``True`` if renew GET/POST parameter is present and not "False"
2015-05-29 14:11:10 +00:00
renew = None
2016-07-23 16:41:46 +00:00
#: the warn GET/POST parameter
warn = None
#: the gateway GET/POST parameter
2015-05-29 14:11:10 +00:00
gateway = None
2016-07-23 16:41:46 +00:00
#: the method GET/POST parameter
2015-05-29 14:11:10 +00:00
method = None
2016-07-23 16:41:46 +00:00
#: ``True`` if the HTTP_X_AJAX http header is sent and ``settings.CAS_ENABLE_AJAX_AUTH``
#: is ``True``, ``False`` otherwise.
ajax = None
2015-05-29 14:11:10 +00:00
2016-07-23 16:41:46 +00:00
#: ``True`` if the user has just authenticated
2015-05-16 21:43:46 +00:00
renewed = False
2016-07-23 16:41:46 +00:00
#: ``True`` if renew GET/POST parameter is present and not "False"
warned = False
2015-05-29 14:11:10 +00:00
2016-07-23 16:41:46 +00:00
#: The :class:`FederateAuth` transmited username (only used if ``settings.CAS_FEDERATE``
#: is ``True``)
username = None
2016-07-23 16:41:46 +00:00
#: The :class:`FederateAuth` transmited ticket (only used if ``settings.CAS_FEDERATE`` is
#: ``True``)
ticket = None
2015-06-12 21:57:11 +00:00
INVALID_LOGIN_TICKET = 1
USER_LOGIN_OK = 2
USER_LOGIN_FAILURE = 3
USER_ALREADY_LOGGED = 4
USER_AUTHENTICATED = 5
USER_NOT_AUTHENTICATED = 6
def init_post(self, request):
2016-07-23 16:41:46 +00:00
"""
Initialize POST received parameters
:param django.http.HttpRequest request: The current request object
"""
2015-05-29 14:11:10 +00:00
self.request = request
self.service = request.POST.get('service')
2016-06-26 09:16:41 +00:00
self.renew = bool(request.POST.get('renew') and request.POST['renew'] != "False")
2015-05-29 14:11:10 +00:00
self.gateway = request.POST.get('gateway')
self.method = request.POST.get('method')
2016-06-30 16:57:11 +00:00
self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
if request.POST.get('warned') and request.POST['warned'] != "False":
self.warned = True
2016-06-17 17:28:49 +00:00
self.warn = request.POST.get('warn')
if settings.CAS_FEDERATE:
self.username = request.POST.get('username')
self.ticket = request.POST.get('ticket')
2015-05-29 14:11:10 +00:00
def gen_lt(self):
"""Generate a new LoginTicket and add it to the list of valid LT for the user"""
self.request.session['lt'] = self.request.session.get('lt', []) + [utils.gen_lt()]
if len(self.request.session['lt']) > 100:
self.request.session['lt'] = self.request.session['lt'][-100:]
2015-06-12 21:57:11 +00:00
def check_lt(self):
2016-07-23 16:41:46 +00:00
"""
Check is the POSTed LoginTicket is valid, if yes invalide it
:return: ``True`` if the LoginTicket is valid, ``False`` otherwise
:rtype: bool
"""
# save LT for later check
lt_valid = self.request.session.get('lt', [])
2015-06-12 21:57:11 +00:00
lt_send = self.request.POST.get('lt')
# generate a new LT (by posting the LT has been consumed)
self.gen_lt()
# check if send LT is valid
if lt_send not in lt_valid:
2015-06-12 21:57:11 +00:00
return False
else:
self.request.session['lt'].remove(lt_send)
2016-07-23 16:41:46 +00:00
# we need to redo the affectation for django to detect that the list has changed
# and for its new value to be store in the session
self.request.session['lt'] = self.request.session['lt']
2015-06-12 21:57:11 +00:00
return True
def post(self, request, *args, **kwargs):
2016-07-23 16:41:46 +00:00
"""
methode called on POST request on this view
:param django.http.HttpRequest request: The current request object
"""
# initialize class parameters
2015-06-12 21:57:11 +00:00
self.init_post(request)
2016-07-23 16:41:46 +00:00
# process the POST request
2015-06-12 21:57:11 +00:00
ret = self.process_post()
if ret == self.INVALID_LOGIN_TICKET:
messages.add_message(
self.request,
messages.ERROR,
_(u"Invalid login ticket, please retry to login")
2015-05-27 19:56:39 +00:00
)
2015-06-12 21:57:11 +00:00
elif ret == self.USER_LOGIN_OK:
2016-07-23 16:41:46 +00:00
# On successful login, update the :class:`models.User<cas_server.models.User>` ``date``
# attribute by saving it. (``auto_now=True``)
self.user = models.User.objects.get_or_create(
username=self.request.session['username'],
session_key=self.request.session.session_key
)[0]
self.user.save()
2015-06-12 21:57:11 +00:00
elif ret == self.USER_LOGIN_FAILURE: # bad user login
if settings.CAS_FEDERATE:
self.ticket = None
self.username = None
self.init_form()
# preserve valid LoginTickets from session flush
lt = self.request.session.get('lt', [])
2016-07-23 16:41:46 +00:00
# On login failure, flush the session
2015-06-12 21:57:11 +00:00
self.logout()
# restore valid LoginTickets
self.request.session['lt'] = lt
2015-06-12 21:57:11 +00:00
elif ret == self.USER_ALREADY_LOGGED:
pass
2016-07-23 16:41:46 +00:00
else: # pragma: no cover (should no happen)
raise EnvironmentError("invalid output for LoginView.process_post")
# call the GET/POST common part
2015-06-12 21:57:11 +00:00
return self.common()
2016-06-26 14:02:25 +00:00
def process_post(self):
"""
Analyse the POST request:
2016-07-23 16:41:46 +00:00
* check that the LoginTicket is valid
* check that the user sumited credentials are valid
2016-07-23 16:41:46 +00:00
:return:
* :attr:`INVALID_LOGIN_TICKET` if the POSTed LoginTicket is not valid
* :attr:`USER_ALREADY_LOGGED` if the user is already logged and do no request
reauthentication.
* :attr:`USER_LOGIN_FAILURE` if the user is not logged or request for
reauthentication and his credentials are not valid
* :attr:`USER_LOGIN_OK` if the user is not logged or request for
reauthentication and his credentials are valid
:rtype: int
"""
2015-06-12 21:57:11 +00:00
if not self.check_lt():
self.init_form(self.request.POST)
2015-12-13 12:50:29 +00:00
logger.warning("Receive an invalid login ticket")
2015-06-12 21:57:11 +00:00
return self.INVALID_LOGIN_TICKET
elif not self.request.session.get("authenticated") or self.renew:
2016-07-23 16:41:46 +00:00
# authentication request receive, initialize the form to use
2015-06-12 21:57:11 +00:00
self.init_form(self.request.POST)
if self.form.is_valid():
self.request.session.set_expiry(0)
self.request.session["username"] = self.form.cleaned_data['username']
self.request.session["warn"] = True if self.form.cleaned_data.get("warn") else False
self.request.session["authenticated"] = True
2015-05-29 14:11:10 +00:00
self.renewed = True
self.warned = True
2015-12-13 12:50:29 +00:00
logger.info("User %s successfully authenticated" % self.request.session["username"])
2015-06-12 21:57:11 +00:00
return self.USER_LOGIN_OK
2015-05-16 21:43:46 +00:00
else:
2015-12-13 12:50:29 +00:00
logger.warning("A logging attemps failed")
2015-06-12 21:57:11 +00:00
return self.USER_LOGIN_FAILURE
else:
2015-12-13 12:50:29 +00:00
logger.warning("Receuve a logging attempt whereas the user is already logged")
2015-06-12 21:57:11 +00:00
return self.USER_ALREADY_LOGGED
2015-05-29 14:11:10 +00:00
2015-06-12 21:57:11 +00:00
def init_get(self, request):
2016-07-23 16:41:46 +00:00
"""
Initialize GET received parameters
:param django.http.HttpRequest request: The current request object
"""
2015-05-29 14:11:10 +00:00
self.request = request
self.service = request.GET.get('service')
2016-06-26 09:16:41 +00:00
self.renew = bool(request.GET.get('renew') and request.GET['renew'] != "False")
2015-05-29 14:11:10 +00:00
self.gateway = request.GET.get('gateway')
self.method = request.GET.get('method')
2016-06-30 16:57:11 +00:00
self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
2016-06-17 17:28:49 +00:00
self.warn = request.GET.get('warn')
if settings.CAS_FEDERATE:
2016-07-23 16:41:46 +00:00
# here username and ticket are fetch from the session after a redirection from
# FederateAuth.get
self.username = request.session.get("federate_username")
self.ticket = request.session.get("federate_ticket")
if self.username:
del request.session["federate_username"]
if self.ticket:
del request.session["federate_ticket"]
2015-05-29 14:11:10 +00:00
2015-06-12 21:57:11 +00:00
def get(self, request, *args, **kwargs):
2016-07-23 16:41:46 +00:00
"""
methode called on GET request on this view
:param django.http.HttpRequest request: The current request object
"""
# initialize class parameters
2015-06-12 21:57:11 +00:00
self.init_get(request)
2016-07-23 16:41:46 +00:00
# process the GET request
2015-06-12 21:57:11 +00:00
self.process_get()
2016-07-23 16:41:46 +00:00
# call the GET/POST common part
2015-06-12 21:57:11 +00:00
return self.common()
def process_get(self):
2016-07-23 16:41:46 +00:00
"""
Analyse the GET request
:return:
* :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting
for authentication renewal
* :attr:`USER_AUTHENTICATED` if the user is authenticated and is not requesting
for authentication renewal
:rtype: int
"""
# generate a new LT
self.gen_lt()
2015-06-12 21:57:11 +00:00
if not self.request.session.get("authenticated") or self.renew:
2016-07-23 16:41:46 +00:00
# authentication will be needed, initialize the form to use
self.init_form()
2015-06-12 21:57:11 +00:00
return self.USER_NOT_AUTHENTICATED
return self.USER_AUTHENTICATED
2015-05-16 21:43:46 +00:00
def init_form(self, values=None):
2016-07-23 16:41:46 +00:00
"""
Initialization of the good form depending of POST and GET parameters
:param django.http.QueryDict values: A POST or GET QueryDict
"""
if values:
values = values.copy()
values['lt'] = self.request.session['lt'][-1]
2016-06-17 17:28:49 +00:00
form_initial = {
'service': self.service,
'method': self.method,
'warn': self.warn or self.request.session.get("warn"),
2016-06-28 13:29:45 +00:00
'lt': self.request.session['lt'][-1],
'renew': self.renew
2016-06-17 17:28:49 +00:00
}
if settings.CAS_FEDERATE:
if self.username and self.ticket:
form_initial['username'] = self.username
form_initial['password'] = self.ticket
form_initial['ticket'] = self.ticket
self.form = forms.FederateUserCredential(
values,
initial=form_initial
)
else:
self.form = forms.FederateSelect(values, initial=form_initial)
else:
self.form = forms.UserCredential(
values,
initial=form_initial
)
2015-05-29 14:11:10 +00:00
def service_login(self):
2016-07-23 16:41:46 +00:00
"""
Perform login agains a service
:return:
* The rendering of the ``settings.CAS_WARN_TEMPLATE`` if the user asked to be
warned before ticket emission and has not yep been warned.
* The redirection to the service URL with a ticket GET parameter
* The redirection to the service URL without a ticket if ticket generation failed
and the :attr:`gateway` attribute is set
* The rendering of the ``settings.CAS_LOGGED_TEMPLATE`` template with some error
messages if the ticket generation failed (e.g: user not allowed).
:rtype: django.http.HttpResponse
"""
2015-05-29 14:11:10 +00:00
try:
# is the service allowed
2015-06-08 00:51:22 +00:00
service_pattern = ServicePattern.validate(self.service)
2015-05-29 14:11:10 +00:00
# is the current user allowed on this service
service_pattern.check_user(self.user)
# if the user has asked to be warned before any login to a service
if self.request.session.get("warn", True) and not self.warned:
2015-05-27 19:56:39 +00:00
messages.add_message(
2015-05-29 14:11:10 +00:00
self.request,
messages.WARNING,
2015-06-12 16:10:52 +00:00
_(u"Authentication has been required by service %(name)s (%(url)s)") %
{'name': service_pattern.name, 'url': self.service}
2015-05-27 19:56:39 +00:00
)
if self.ajax:
data = {"status": "error", "detail": "confirmation needed"}
2016-06-26 14:02:25 +00:00
return json_response(self.request, data)
else:
warn_form = forms.WarnForm(initial={
'service': self.service,
'renew': self.renew,
'gateway': self.gateway,
'method': self.method,
'warned': True,
'lt': self.request.session['lt'][-1]
})
return render(
self.request,
settings.CAS_WARN_TEMPLATE,
utils.context({'form': warn_form})
2015-11-20 16:38:03 +00:00
)
2015-05-29 14:11:10 +00:00
else:
# redirect, using method ?
2015-06-12 16:10:52 +00:00
list(messages.get_messages(self.request)) # clean messages before leaving django
redirect_url = self.user.get_service_url(
self.service,
service_pattern,
2016-06-28 13:24:50 +00:00
renew=self.renewed
2015-05-27 19:56:39 +00:00
)
if not self.ajax:
return HttpResponseRedirect(redirect_url)
else:
data = {"status": "success", "detail": "auth", "url": redirect_url}
2016-06-26 14:02:25 +00:00
return json_response(self.request, data)
2015-06-08 00:51:22 +00:00
except ServicePattern.DoesNotExist:
error = 1
2015-05-29 14:11:10 +00:00
messages.add_message(
self.request,
messages.ERROR,
2015-06-12 16:10:52 +00:00
_(u'Service %(url)s non allowed.') % {'url': self.service}
2015-05-29 14:11:10 +00:00
)
except models.BadUsername:
error = 2
2015-05-29 14:11:10 +00:00
messages.add_message(
self.request,
messages.ERROR,
_(u"Username non allowed")
)
except models.BadFilter:
error = 3
2015-05-29 14:11:10 +00:00
messages.add_message(
self.request,
messages.ERROR,
_(u"User characteristics non allowed")
2015-05-29 14:11:10 +00:00
)
except models.UserFieldNotDefined:
error = 4
2015-05-29 14:11:10 +00:00
messages.add_message(
self.request,
messages.ERROR,
_(u"The attribute %(field)s is needed to use"
2015-06-12 16:10:52 +00:00
u" that service") % {'field': service_pattern.user_field}
2015-05-29 14:11:10 +00:00
)
# if gateway is set and auth failed redirect to the service without authentication
if self.gateway and not self.ajax:
2015-06-12 16:10:52 +00:00
list(messages.get_messages(self.request)) # clean messages before leaving django
2015-05-29 14:11:10 +00:00
return HttpResponseRedirect(self.service)
2015-05-16 21:43:46 +00:00
if not self.ajax:
return render(
self.request,
settings.CAS_LOGGED_TEMPLATE,
utils.context({'session': self.request.session})
)
else:
data = {"status": "error", "detail": "auth", "code": error}
2016-06-26 14:02:25 +00:00
return json_response(self.request, data)
2015-05-16 21:43:46 +00:00
2015-05-29 14:11:10 +00:00
def authenticated(self):
2016-07-23 16:41:46 +00:00
"""
Processing authenticated users
:return:
* The returned value of :meth:`service_login` if :attr:`service` is defined
* The rendering of ``settings.CAS_LOGGED_TEMPLATE`` otherwise
:rtype: django.http.HttpResponse
"""
# Try to get the current :class:`models.User<cas_server.models.User>` object for the current
# session
2015-05-29 14:11:10 +00:00
try:
2015-06-09 20:04:05 +00:00
self.user = models.User.objects.get(
username=self.request.session.get("username"),
2015-06-11 21:34:25 +00:00
session_key=self.request.session.session_key
2015-06-09 20:04:05 +00:00
)
2016-07-23 16:41:46 +00:00
# if not found, flush the session and redirect to the login page
2015-05-29 14:11:10 +00:00
except models.User.DoesNotExist:
2015-12-13 12:50:29 +00:00
logger.warning(
"User %s seems authenticated but is not found in the database." % (
self.request.session.get("username"),
)
)
2015-05-29 14:11:10 +00:00
self.logout()
if self.ajax:
data = {
"status": "error",
"detail": "login required",
"url": utils.reverse_params("cas_server:login", params=self.request.GET)
}
2016-06-26 14:02:25 +00:00
return json_response(self.request, data)
else:
return utils.redirect_params("cas_server:login", params=self.request.GET)
2015-05-29 14:11:10 +00:00
2016-07-23 16:41:46 +00:00
# if login agains a service
2015-05-29 14:11:10 +00:00
if self.service:
return self.service_login()
2016-07-23 16:41:46 +00:00
# else display the logged template
2015-05-29 14:11:10 +00:00
else:
if self.ajax:
data = {"status": "success", "detail": "logged"}
2016-06-26 14:02:25 +00:00
return json_response(self.request, data)
else:
return render(
self.request,
settings.CAS_LOGGED_TEMPLATE,
utils.context({'session': self.request.session})
)
2015-05-29 14:11:10 +00:00
def not_authenticated(self):
2016-07-23 16:41:46 +00:00
"""
Processing non authenticated users
:return:
* The rendering of ``settings.CAS_LOGIN_TEMPLATE`` with various messages
depending of GET/POST parameters
* The redirection to :class:`FederateAuth` if ``settings.CAS_FEDERATE`` is ``True``
and the "remember my identity provider" cookie is found
:rtype: django.http.HttpResponse
"""
2015-05-29 14:11:10 +00:00
if self.service:
2015-05-18 18:30:00 +00:00
try:
2015-06-08 00:51:22 +00:00
service_pattern = ServicePattern.validate(self.service)
if self.gateway and not self.ajax:
2015-06-12 16:10:52 +00:00
# clean messages before leaving django
list(messages.get_messages(self.request))
2015-05-29 14:11:10 +00:00
return HttpResponseRedirect(self.service)
if self.request.session.get("authenticated") and self.renew:
2015-05-27 19:56:39 +00:00
messages.add_message(
2015-05-29 14:11:10 +00:00
self.request,
2015-05-27 19:56:39 +00:00
messages.WARNING,
2015-05-29 14:11:10 +00:00
_(u"Authentication renewal required by service %(name)s (%(url)s).") %
2015-06-12 16:10:52 +00:00
{'name': service_pattern.name, 'url': self.service}
2015-05-27 19:56:39 +00:00
)
2015-05-18 18:30:00 +00:00
else:
2015-05-27 19:56:39 +00:00
messages.add_message(
2015-05-29 14:11:10 +00:00
self.request,
2015-05-27 19:56:39 +00:00
messages.WARNING,
2015-05-29 14:11:10 +00:00
_(u"Authentication required by service %(name)s (%(url)s).") %
2015-06-12 16:10:52 +00:00
{'name': service_pattern.name, 'url': self.service}
2015-05-27 19:56:39 +00:00
)
2015-06-08 00:51:22 +00:00
except ServicePattern.DoesNotExist:
2015-05-27 19:56:39 +00:00
messages.add_message(
2015-05-29 14:11:10 +00:00
self.request,
2015-05-27 19:56:39 +00:00
messages.ERROR,
2015-05-29 14:11:10 +00:00
_(u'Service %s non allowed') % self.service
2015-05-27 19:56:39 +00:00
)
if self.ajax:
data = {
"status": "error",
"detail": "login required",
"url": utils.reverse_params("cas_server:login", params=self.request.GET)
}
2016-06-26 14:02:25 +00:00
return json_response(self.request, data)
else:
2016-06-17 17:28:49 +00:00
if settings.CAS_FEDERATE:
if self.username and self.ticket:
return render(
self.request,
settings.CAS_LOGIN_TEMPLATE,
2016-06-20 11:35:48 +00:00
utils.context({
2016-06-17 17:28:49 +00:00
'form': self.form,
'auto_submit': True,
'post_url': reverse("cas_server:login")
2016-06-20 11:35:48 +00:00
})
2016-06-17 17:28:49 +00:00
)
else:
if (
self.request.COOKIES.get('_remember_provider') and
FederatedIendityProvider.objects.filter(
suffix=self.request.COOKIES['_remember_provider']
)
2016-06-17 17:28:49 +00:00
):
params = utils.copy_params(self.request.GET)
url = utils.reverse_params(
"cas_server:federateAuth",
params=params,
kwargs=dict(provider=self.request.COOKIES['_remember_provider'])
)
return HttpResponseRedirect(url)
else:
return render(
self.request,
settings.CAS_LOGIN_TEMPLATE,
utils.context({
'form': self.form,
'post_url': reverse("cas_server:federateAuth")
})
2016-06-17 17:28:49 +00:00
)
else:
2016-06-20 11:35:48 +00:00
return render(
self.request,
settings.CAS_LOGIN_TEMPLATE,
utils.context({'form': self.form})
)
2015-05-16 21:43:46 +00:00
2015-05-29 14:11:10 +00:00
def common(self):
2016-07-23 16:41:46 +00:00
"""
Common part execute uppon GET and POST request
:return:
* The returned value of :meth:`authenticated` if the user is authenticated and
not requesting for authentication or if the authentication has just been renewed
* The returned value of :meth:`not_authenticated` otherwise
:rtype: django.http.HttpResponse
"""
2015-05-29 14:11:10 +00:00
# if authenticated and successfully renewed authentication if needed
if self.request.session.get("authenticated") and (not self.renew or self.renewed):
return self.authenticated()
else:
return self.not_authenticated()
2015-05-16 21:43:46 +00:00
2015-06-12 16:10:52 +00:00
class Auth(View):
"""A simple view to validate username/password/service tuple"""
2016-07-23 16:41:46 +00:00
# csrf is disable as it is intended to be used by programs. Security is assured by a shared
# secret between the programs dans django-cas-server.
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
2016-07-23 16:41:46 +00:00
"""
dispatch requests based on method GET, POST, ...
:param django.http.HttpRequest request: The current request object
"""
return super(Auth, self).dispatch(request, *args, **kwargs)
@staticmethod
def post(request):
2016-07-23 16:41:46 +00:00
"""
methode called on POST request on this view
:param django.http.HttpRequest request: The current request object
:return: ``HttpResponse(u"yes\\n")`` if the POSTed tuple (username, password, service)
if valid (i.e. (username, password) is valid dans username is allowed on service).
``HttpResponse(u"no\\n…")`` otherwise, with possibly an error message on the second
line.
:rtype: django.http.HttpResponse
"""
username = request.POST.get('username')
password = request.POST.get('password')
service = request.POST.get('service')
secret = request.POST.get('secret')
if not settings.CAS_AUTH_SHARED_SECRET:
return HttpResponse(
"no\nplease set CAS_AUTH_SHARED_SECRET",
content_type="text/plain; charset=utf-8"
)
if secret != settings.CAS_AUTH_SHARED_SECRET:
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
if not username or not password or not service:
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
form = forms.UserCredential(
request.POST,
initial={
2015-06-12 16:10:52 +00:00
'service': service,
'method': 'POST',
'warn': False
}
)
if form.is_valid():
try:
user = models.User.objects.get_or_create(
username=form.cleaned_data['username'],
session_key=request.session.session_key
)[0]
2015-06-12 21:57:11 +00:00
user.save()
# is the service allowed
2015-06-08 00:51:22 +00:00
service_pattern = ServicePattern.validate(service)
# is the current user allowed on this service
service_pattern.check_user(user)
2015-06-09 20:04:05 +00:00
if not request.session.get("authenticated"):
user.delete()
return HttpResponse(u"yes\n", content_type="text/plain; charset=utf-8")
2015-06-12 16:10:52 +00:00
except (ServicePattern.DoesNotExist, models.ServicePatternException):
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
else:
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
2015-06-12 16:10:52 +00:00
class Validate(View):
2015-05-27 19:56:39 +00:00
"""service ticket validation"""
@staticmethod
def get(request):
2016-07-23 16:41:46 +00:00
"""
methode called on GET request on this view
:param django.http.HttpRequest request: The current request object
:return:
* ``HttpResponse("yes\\nusername")`` if submited (service, ticket) is valid
* else ``HttpResponse("no\\n")``
:rtype: django.http.HttpResponse
"""
# store wanted GET parameters
service = request.GET.get('service')
ticket = request.GET.get('ticket')
renew = True if request.GET.get('renew') else False
2016-07-23 16:41:46 +00:00
# service and ticket parameters are mandatory
if service and ticket:
try:
2016-07-23 16:43:27 +00:00
# search for the ticket, associated at service that is not yet validated but is
# still valid
ticket = ServiceTicket.get(ticket, renew, service)
2015-12-13 12:50:29 +00:00
logger.info(
"Validate: Service ticket %s validated, user %s authenticated on service %s" % (
ticket.value,
ticket.user.username,
ticket.service
)
)
return HttpResponse(
2016-07-23 16:43:27 +00:00
u"yes\n%s\n" % ticket.username(),
content_type="text/plain; charset=utf-8"
)
2015-06-08 00:51:22 +00:00
except ServiceTicket.DoesNotExist:
2015-12-13 12:50:29 +00:00
logger.warning(
(
"Validate: Service ticket %s not found or "
"already validated, auth to %s failed"
) % (
ticket,
service
)
)
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
else:
2015-12-13 12:50:29 +00:00
logger.warning("Validate: service or ticket missing")
return HttpResponse(u"no\n", content_type="text/plain; charset=utf-8")
2015-05-16 21:43:46 +00:00
2015-05-27 19:56:39 +00:00
@python_2_unicode_compatible
class ValidateError(Exception):
"""handle service validation error"""
2016-07-23 16:41:46 +00:00
#: The error code
code = None
#: The error message
msg = None
2016-07-23 16:43:27 +00:00
def __init__(self, code, msg=""):
self.code = code
self.msg = msg
2015-05-29 17:31:04 +00:00
super(ValidateError, self).__init__(code)
def __str__(self):
return u"%s" % self.msg
def render(self, request):
2016-07-23 16:41:46 +00:00
"""
render the error template for the exception
:param django.http.HttpRequest request: The current request object:
:return: the rendered ``cas_server/serviceValidateError.xml`` template
:rtype: django.http.HttpResponse
"""
return render(
request,
"cas_server/serviceValidateError.xml",
2015-06-12 16:10:52 +00:00
{'code': self.code, 'msg': self.msg},
content_type="text/xml; charset=utf-8"
)
2016-07-23 16:41:46 +00:00
class ValidateService(View):
"""service ticket validation [CAS 2.0] and [CAS 3.0]"""
2016-07-23 16:41:46 +00:00
#: Current :class:`django.http.HttpRequest` object
request = None
2016-07-23 16:41:46 +00:00
#: The service GET parameter
service = None
2016-07-23 16:41:46 +00:00
#: the ticket GET parameter
ticket = None
2016-07-23 16:41:46 +00:00
#: the pgtUrl GET parameter
pgt_url = None
2016-07-23 16:41:46 +00:00
#: the renew GET parameter
renew = None
2016-07-23 16:41:46 +00:00
#: specify if ProxyTicket are allowed by the view. Hence we user the same view for
#: ``/serviceValidate`` and ``/proxyValidate`` juste changing the parameter.
2015-05-29 17:33:42 +00:00
allow_proxy_ticket = False
2015-05-29 17:33:42 +00:00
def get(self, request):
2016-07-23 16:41:46 +00:00
"""
methode called on GET request on this view
:param django.http.HttpRequest request: The current request object:
:return: The rendering of ``cas_server/serviceValidate.xml`` if no errors is raised,
the rendering or ``cas_server/serviceValidateError.xml`` otherwise.
:rtype: django.http.HttpResponse
"""
# define the class parameters
self.request = request
self.service = request.GET.get('service')
self.ticket = request.GET.get('ticket')
self.pgt_url = request.GET.get('pgtUrl')
self.renew = True if request.GET.get('renew') else False
2016-07-23 16:41:46 +00:00
# service and ticket parameter are mandatory
if not self.service or not self.ticket:
2015-12-13 12:50:29 +00:00
logger.warning("ValidateService: missing ticket or service")
return ValidateError(
u'INVALID_REQUEST',
u"you must specify a service and a ticket"
).render(request)
2015-05-16 21:43:46 +00:00
else:
try:
2016-07-23 16:41:46 +00:00
# search the ticket in the database
self.ticket, proxies = self.process_ticket()
2016-07-23 16:41:46 +00:00
# prepare template rendering context
params = {
2016-07-23 16:43:27 +00:00
'username': self.ticket.username(),
'attributes': self.ticket.attributs_flat(),
2015-06-12 16:10:52 +00:00
'proxies': proxies
}
2016-07-23 16:43:27 +00:00
# if pgtUrl is set, require https or localhost
if self.pgt_url and (
self.pgt_url.startswith("https://") or
re.match("^http://(127\.0\.0\.1|localhost)(:[0-9]+)?(/.*)?$", self.pgt_url)
):
return self.process_pgturl(params)
else:
2015-12-13 12:50:29 +00:00
logger.info(
"ValidateService: ticket %s validated for user %s on service %s." % (
self.ticket.value,
self.ticket.user.username,
self.ticket.service
)
)
logger.debug(
"ValidateService: User attributs are:\n%s" % (
pprint.pformat(self.ticket.attributs),
)
)
return render(
request,
"cas_server/serviceValidate.xml",
params,
content_type="text/xml; charset=utf-8"
)
except ValidateError as error:
2015-12-13 12:50:29 +00:00
logger.warning(
"ValidateService: validation error: %s %s" % (error.code, error.msg)
)
return error.render(request)
def process_ticket(self):
2016-07-23 16:41:46 +00:00
"""
fetch the ticket against the database and check its validity
:raises ValidateError: if the ticket is not found or not valid, potentially for that
service
:returns: A couple (ticket, proxies list)
:rtype: :obj:`tuple`
"""
2015-05-16 21:43:46 +00:00
try:
proxies = []
2016-07-23 16:41:46 +00:00
if self.allow_proxy_ticket:
ticket = models.Ticket.get(self.ticket, self.renew)
else:
2016-07-23 16:41:46 +00:00
ticket = models.ServiceTicket.get(self.ticket, self.renew)
try:
for prox in ticket.proxies.all():
proxies.append(prox.url)
except AttributeError:
pass
if ticket.service != self.service:
raise ValidateError(u'INVALID_SERVICE', self.service)
return ticket, proxies
2016-07-23 16:41:46 +00:00
except Ticket.DoesNotExist:
raise ValidateError(u'INVALID_TICKET', self.ticket)
2015-06-08 00:51:22 +00:00
except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist):
raise ValidateError(u'INVALID_TICKET', 'ticket not found')
def process_pgturl(self, params):
2016-07-23 16:41:46 +00:00
"""
Handle PGT request
:param dict params: A template context dict
:raises ValidateError: if pgtUrl is invalid or if TLS validation of the pgtUrl fails
:return: The rendering of ``cas_server/serviceValidate.xml``, using ``params``
:rtype: django.http.HttpResponse
"""
try:
2015-06-08 00:51:22 +00:00
pattern = ServicePattern.validate(self.pgt_url)
if pattern.proxy_callback:
proxyid = utils.gen_pgtiou()
2015-06-08 00:51:22 +00:00
pticket = ProxyGrantingTicket.objects.create(
user=self.ticket.user,
service=self.pgt_url,
service_pattern=pattern,
single_log_out=pattern.single_log_out
)
2015-06-12 16:10:52 +00:00
url = utils.update_url(self.pgt_url, {'pgtIou': proxyid, 'pgtId': pticket.value})
try:
ret = requests.get(url, verify=settings.CAS_PROXY_CA_CERTIFICATE_PATH)
if ret.status_code == 200:
params['proxyGrantingTicket'] = proxyid
else:
pticket.delete()
2015-12-13 12:50:29 +00:00
logger.info(
(
"ValidateService: ticket %s validated for user %s on service %s. "
"Proxy Granting Ticket transmited to %s."
) % (
self.ticket.value,
self.ticket.user.username,
self.ticket.service,
self.pgt_url
)
)
logger.debug(
"ValidateService: User attributs are:\n%s" % (
pprint.pformat(self.ticket.attributs),
)
)
return render(
self.request,
"cas_server/serviceValidate.xml",
params,
content_type="text/xml; charset=utf-8"
2015-05-27 19:56:39 +00:00
)
2016-06-28 16:57:56 +00:00
except requests.exceptions.RequestException as error:
error = utils.unpack_nested_exception(error)
2016-06-28 16:57:56 +00:00
raise ValidateError(
u'INVALID_PROXY_CALLBACK',
u"%s: %s" % (type(error), str(error))
2016-06-28 16:57:56 +00:00
)
2015-05-16 21:43:46 +00:00
else:
raise ValidateError(
u'INVALID_PROXY_CALLBACK',
u"callback url not allowed by configuration"
2015-05-27 19:56:39 +00:00
)
2015-06-08 00:51:22 +00:00
except ServicePattern.DoesNotExist:
raise ValidateError(
u'INVALID_PROXY_CALLBACK',
u'callback url not allowed by configuration'
2015-05-27 19:56:39 +00:00
)
2015-05-16 21:43:46 +00:00
2015-06-12 16:10:52 +00:00
class Proxy(View):
2015-05-27 19:56:39 +00:00
"""proxy ticket service"""
2016-07-23 16:41:46 +00:00
#: Current :class:`django.http.HttpRequest` object
request = None
2016-07-23 16:41:46 +00:00
#: A ProxyGrantingTicket from the pgt GET parameter
pgt = None
2016-07-23 16:41:46 +00:00
#: the targetService GET parameter
target_service = None
def get(self, request):
2016-07-23 16:41:46 +00:00
"""
methode called on GET request on this view
:param django.http.HttpRequest request: The current request object:
:return: The returned value of :meth:`process_proxy` if no error is raised,
else the rendering of ``cas_server/serviceValidateError.xml``.
:rtype: django.http.HttpResponse
"""
self.request = request
self.pgt = request.GET.get('pgt')
self.target_service = request.GET.get('targetService')
try:
2016-07-23 16:41:46 +00:00
# pgt and targetService parameters are mandatory
if self.pgt and self.target_service:
return self.process_proxy()
else:
raise ValidateError(
u'INVALID_REQUEST',
u"you must specify and pgt and targetService"
)
except ValidateError as error:
2015-12-13 12:50:29 +00:00
logger.warning("Proxy: validation error: %s %s" % (error.code, error.msg))
return error.render(request)
def process_proxy(self):
2016-07-23 16:41:46 +00:00
"""
handle PT request
:raises ValidateError: if the PGT is not found, or the target service not allowed or
the user not allowed on the tardet service.
:return: The rendering of ``cas_server/proxy.xml``
:rtype: django.http.HttpResponse
"""
2015-05-16 21:43:46 +00:00
try:
2015-05-27 19:56:39 +00:00
# is the target service allowed
2015-06-08 00:51:22 +00:00
pattern = ServicePattern.validate(self.target_service)
2016-07-23 16:41:46 +00:00
# to get a proxy ticket require that the service allow it
if not pattern.proxy:
raise ValidateError(
u'UNAUTHORIZED_SERVICE',
u'the service %s do not allow proxy ticket' % self.target_service
)
2015-05-27 19:56:39 +00:00
# is the proxy granting ticket valid
2016-07-23 16:43:27 +00:00
ticket = ProxyGrantingTicket.get(self.pgt)
2015-05-27 19:56:39 +00:00
# is the pgt user allowed on the target service
2015-05-17 21:24:41 +00:00
pattern.check_user(ticket.user)
pticket = ticket.user.get_ticket(
2015-06-08 00:51:22 +00:00
ProxyTicket,
self.target_service,
pattern,
2016-07-23 16:41:46 +00:00
renew=False
)
2015-06-21 16:56:16 +00:00
models.Proxy.objects.create(proxy_ticket=pticket, url=ticket.service)
2015-12-13 12:50:29 +00:00
logger.info(
"Proxy ticket created for user %s on service %s." % (
ticket.user.username,
self.target_service
)
)
2015-05-27 19:56:39 +00:00
return render(
self.request,
2015-05-27 19:56:39 +00:00
"cas_server/proxy.xml",
2015-06-12 16:10:52 +00:00
{'ticket': pticket.value},
2015-05-27 19:56:39 +00:00
content_type="text/xml; charset=utf-8"
)
2016-07-23 16:43:27 +00:00
except (Ticket.DoesNotExist, ProxyGrantingTicket.DoesNotExist):
raise ValidateError(u'INVALID_TICKET', u'PGT %s not found' % self.pgt)
2015-06-08 00:51:22 +00:00
except ServicePattern.DoesNotExist:
raise ValidateError(u'UNAUTHORIZED_SERVICE', self.target_service)
except (models.BadUsername, models.BadFilter, models.UserFieldNotDefined):
raise ValidateError(
u'UNAUTHORIZED_USER',
u'User %s not allowed on %s' % (ticket.user.username, self.target_service)
2015-05-27 19:56:39 +00:00
)
2015-05-16 21:43:46 +00:00
@python_2_unicode_compatible
class SamlValidateError(Exception):
"""handle saml validation error"""
2016-07-23 16:41:46 +00:00
#: The error code
code = None
#: The error message
msg = None
2016-07-23 16:43:27 +00:00
def __init__(self, code, msg=""):
self.code = code
self.msg = msg
2015-05-29 17:31:04 +00:00
super(SamlValidateError, self).__init__(code)
def __str__(self):
return u"%s" % self.msg
def render(self, request):
2016-07-23 16:41:46 +00:00
"""
render the error template for the exception
:param django.http.HttpRequest request: The current request object:
:return: the rendered ``cas_server/samlValidateError.xml`` template
:rtype: django.http.HttpResponse
"""
return render(
request,
"cas_server/samlValidateError.xml",
{
2015-06-12 16:10:52 +00:00
'code': self.code,
'msg': self.msg,
'IssueInstant': timezone.now().isoformat(),
'ResponseID': utils.gen_saml_id()
},
content_type="text/xml; charset=utf-8"
)
2015-05-22 17:31:50 +00:00
2016-07-23 16:43:27 +00:00
class SamlValidate(View):
"""SAML ticket validation"""
request = None
target = None
ticket = None
root = None
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
2016-07-23 16:41:46 +00:00
"""
dispatch requests based on method GET, POST, ...
:param django.http.HttpRequest request: The current request object
"""
2015-05-29 18:07:53 +00:00
return super(SamlValidate, self).dispatch(request, *args, **kwargs)
def post(self, request):
2016-07-23 16:41:46 +00:00
"""
methode called on POST request on this view
:param django.http.HttpRequest request: The current request object
:return: the rendering of ``cas_server/samlValidate.xml`` if no error is raised,
else the rendering of ``cas_server/samlValidateError.xml``.
:rtype: django.http.HttpResponse
"""
self.request = request
self.target = request.GET.get('TARGET')
self.root = etree.fromstring(request.body)
try:
self.ticket = self.process_ticket()
2015-06-12 16:10:52 +00:00
expire_instant = (self.ticket.creation +
timedelta(seconds=self.ticket.VALIDITY)).isoformat()
params = {
2015-06-12 16:10:52 +00:00
'IssueInstant': timezone.now().isoformat(),
'expireInstant': expire_instant,
'Recipient': self.target,
'ResponseID': utils.gen_saml_id(),
2016-07-23 16:43:27 +00:00
'username': self.ticket.username(),
'attributes': self.ticket.attributs_flat()
}
2015-12-13 12:50:29 +00:00
logger.info(
"SamlValidate: ticket %s validated for user %s on service %s." % (
self.ticket.value,
self.ticket.user.username,
self.ticket.service
)
)
logger.debug(
"SamlValidate: User attributs are:\n%s" % pprint.pformat(self.ticket.attributs)
)
return render(
request,
"cas_server/samlValidate.xml",
params,
content_type="text/xml; charset=utf-8"
)
except SamlValidateError as error:
2015-12-13 12:50:29 +00:00
logger.warning("SamlValidate: validation error: %s %s" % (error.code, error.msg))
return error.render(request)
def process_ticket(self):
2016-07-23 16:41:46 +00:00
"""
validate ticket from SAML XML body
:raises: SamlValidateError: if the ticket is not found or not valid, or if we fail
to parse the posted XML.
:return: a ticket object
:rtype: :class:`models.Ticket<cas_server.models.Ticket>`
"""
2015-05-22 17:31:50 +00:00
try:
auth_req = self.root.getchildren()[1].getchildren()[0]
2015-05-22 17:31:50 +00:00
ticket = auth_req.getchildren()[0].text
2016-07-23 16:43:27 +00:00
ticket = models.Ticket.get(ticket)
if ticket.service != self.target:
raise SamlValidateError(
u'AuthnFailed',
u'TARGET %s do not match ticket service' % self.target
)
return ticket
except (IndexError, KeyError):
raise SamlValidateError(u'VersionMismatch')
2016-07-23 16:43:27 +00:00
except Ticket.DoesNotExist:
raise SamlValidateError(
u'AuthnFailed',
u'ticket %s should begin with PT- or ST-' % ticket
)
2015-06-08 00:51:22 +00:00
except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist):
raise SamlValidateError(u'AuthnFailed', u'ticket %s not found' % ticket)