2015-05-16 21:43:46 +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.
|
|
|
|
#
|
|
|
|
# (c) 2015 Valentin Samir
|
2015-05-27 19:56:39 +00:00
|
|
|
"""views for the app"""
|
2015-05-30 17:45:59 +00:00
|
|
|
from .default_settings import settings
|
2015-05-29 17:27:54 +00:00
|
|
|
|
2015-05-16 21:43:46 +00:00
|
|
|
from django.shortcuts import render, redirect
|
2015-11-17 13:50:16 +00:00
|
|
|
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
|
2015-05-29 17:27:54 +00:00
|
|
|
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
|
2015-05-29 17:27:54 +00:00
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
|
2015-05-29 14:11:10 +00:00
|
|
|
from django.views.generic import View
|
2015-05-16 21:43:46 +00:00
|
|
|
|
2016-06-24 19:05:43 +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-12-12 11:02:26 +00:00
|
|
|
from importlib import import_module
|
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
|
2015-06-08 00:51:22 +00:00
|
|
|
from .models import ServiceTicket, ProxyTicket, ProxyGrantingTicket
|
|
|
|
from .models import ServicePattern
|
|
|
|
|
2015-12-12 11:02:26 +00:00
|
|
|
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
|
|
|
|
|
2015-12-13 12:50:29 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-29 17:27:54 +00:00
|
|
|
class AttributesMixin(object):
|
|
|
|
"""mixin for the attributs methode"""
|
|
|
|
|
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
|
|
|
|
def attributes(self):
|
|
|
|
"""regerate attributes list for template rendering"""
|
|
|
|
attributes = []
|
|
|
|
for key, value in self.ticket.attributs.items():
|
|
|
|
if isinstance(value, list):
|
|
|
|
for elt in value:
|
|
|
|
attributes.append((key, elt))
|
|
|
|
else:
|
|
|
|
attributes.append((key, value))
|
|
|
|
return attributes
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-29 14:14:27 +00:00
|
|
|
class LogoutMixin(object):
|
2015-05-29 17:27:54 +00:00
|
|
|
"""destroy CAS session utils"""
|
2016-06-26 09:16:41 +00:00
|
|
|
def logout(self, all_session=False):
|
2015-05-29 14:11:10 +00:00
|
|
|
"""effectively destroy CAS session"""
|
2015-12-26 14:37:46 +00:00
|
|
|
session_nb = 0
|
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)
|
2015-12-12 11:02:26 +00:00
|
|
|
# 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(
|
2015-12-12 11:02:26 +00:00
|
|
|
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
|
|
|
)
|
2015-11-14 00:05:53 +00:00
|
|
|
self.request.session.flush()
|
2015-05-29 14:11:10 +00:00
|
|
|
user.logout(self.request)
|
|
|
|
user.delete()
|
2015-12-26 14:37:46 +00:00
|
|
|
session_nb += 1
|
2015-05-29 14:11:10 +00:00
|
|
|
except models.User.DoesNotExist:
|
2015-12-12 11:02:26 +00:00
|
|
|
# if user not found in database, flush the session anyway
|
2015-12-11 12:29:04 +00:00
|
|
|
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:
|
2015-12-12 11:02:26 +00:00
|
|
|
for user in models.User.objects.filter(username=username):
|
|
|
|
session = SessionStore(session_key=user.session_key)
|
|
|
|
session.flush()
|
|
|
|
user.logout(self.request)
|
|
|
|
user.delete()
|
2015-12-26 14:37:46 +00:00
|
|
|
session_nb += 1
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.info("User %s logged out" % username)
|
2015-12-26 14:37:46 +00:00
|
|
|
return session_nb
|
2015-12-12 11:02:26 +00:00
|
|
|
|
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"""
|
|
|
|
|
|
|
|
request = None
|
|
|
|
service = None
|
|
|
|
|
2015-06-12 21:57:11 +00:00
|
|
|
def init_get(self, request):
|
2016-06-27 21:55:17 +00:00
|
|
|
"""Initialize GET received parameters"""
|
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):
|
|
|
|
"""methode called on GET request on this view"""
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.info("logout requested")
|
2015-06-12 21:57:11 +00:00
|
|
|
self.init_get(request)
|
2015-12-26 14:37:46 +00:00
|
|
|
session_nb = self.logout(self.request.GET.get("all"))
|
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)
|
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 redirect to login page
|
|
|
|
else:
|
2015-12-26 14:37:46 +00:00
|
|
|
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."
|
|
|
|
)
|
|
|
|
|
2015-06-02 19:06:32 +00:00
|
|
|
if settings.CAS_REDIRECT_TO_LOGIN_AFTER_LOGOUT:
|
2015-12-26 14:37:46 +00:00
|
|
|
messages.add_message(request, messages.SUCCESS, logout_msg)
|
2015-11-17 13:50:16 +00:00
|
|
|
if self.ajax:
|
|
|
|
url = reverse("cas_server:login")
|
2015-12-26 14:37:46 +00:00
|
|
|
data = {
|
|
|
|
'status': 'success',
|
|
|
|
'detail': 'logout',
|
|
|
|
'url': url,
|
|
|
|
'session_nb': session_nb
|
|
|
|
}
|
2016-06-26 14:02:25 +00:00
|
|
|
return json_response(request, data)
|
2015-11-17 13:50:16 +00:00
|
|
|
else:
|
|
|
|
return redirect("cas_server:login")
|
2015-06-02 19:06:32 +00:00
|
|
|
else:
|
2015-11-17 13:50:16 +00:00
|
|
|
if self.ajax:
|
2015-12-26 14:37:46 +00:00
|
|
|
data = {'status': 'success', 'detail': 'logout', 'session_nb': session_nb}
|
2016-06-26 14:02:25 +00:00
|
|
|
return json_response(request, data)
|
2015-11-17 13:50:16 +00:00
|
|
|
else:
|
2015-12-26 14:37:46 +00:00
|
|
|
return render(
|
|
|
|
request,
|
|
|
|
settings.CAS_LOGOUT_TEMPLATE,
|
2016-06-20 11:31:59 +00:00
|
|
|
utils.context({'logout_msg': logout_msg})
|
2015-12-26 14:37:46 +00:00
|
|
|
)
|
2015-05-29 14:11:10 +00:00
|
|
|
|
2015-06-12 16:10:52 +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.
|
|
|
|
|
2015-05-16 21:43:46 +00:00
|
|
|
user = None
|
|
|
|
form = None
|
2015-05-29 14:11:10 +00:00
|
|
|
|
|
|
|
request = None
|
|
|
|
service = None
|
|
|
|
renew = None
|
|
|
|
gateway = None
|
|
|
|
method = None
|
2015-11-17 13:50:16 +00:00
|
|
|
ajax = None
|
2015-05-29 14:11:10 +00:00
|
|
|
|
2015-05-16 21:43:46 +00:00
|
|
|
renewed = False
|
2015-05-16 21:50:25 +00:00
|
|
|
warned = False
|
2015-05-29 14:11:10 +00:00
|
|
|
|
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-06-27 21:55:17 +00:00
|
|
|
"""Initialize POST received parameters"""
|
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
|
2016-06-03 12:11:07 +00:00
|
|
|
if request.POST.get('warned') and request.POST['warned'] != "False":
|
|
|
|
self.warned = True
|
2016-06-28 13:24:50 +00:00
|
|
|
self.warn = request.POST.get('warn')
|
2015-05-29 14:11:10 +00:00
|
|
|
|
2016-06-27 21:55:17 +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-06-27 21:55:17 +00:00
|
|
|
"""Check is the POSTed LoginTicket is valid, if yes invalide it"""
|
2015-06-05 13:44:17 +00:00
|
|
|
# save LT for later check
|
2015-11-14 00:05:53 +00:00
|
|
|
lt_valid = self.request.session.get('lt', [])
|
2015-06-12 21:57:11 +00:00
|
|
|
lt_send = self.request.POST.get('lt')
|
2015-06-07 21:46:32 +00:00
|
|
|
# generate a new LT (by posting the LT has been consumed)
|
2016-06-27 21:55:17 +00:00
|
|
|
self.gen_lt()
|
2015-06-05 13:44:17 +00:00
|
|
|
# check if send LT is valid
|
2015-11-14 00:05:53 +00:00
|
|
|
if lt_valid is None or lt_send not in lt_valid:
|
2015-06-12 21:57:11 +00:00
|
|
|
return False
|
|
|
|
else:
|
2015-11-14 00:05:53 +00:00
|
|
|
self.request.session['lt'].remove(lt_send)
|
|
|
|
self.request.session['lt'] = self.request.session['lt']
|
2015-06-12 21:57:11 +00:00
|
|
|
return True
|
|
|
|
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
|
|
"""methode called on POST request on this view"""
|
|
|
|
self.init_post(request)
|
|
|
|
ret = self.process_post()
|
|
|
|
if ret == self.INVALID_LOGIN_TICKET:
|
2015-06-05 13:44:17 +00:00
|
|
|
messages.add_message(
|
|
|
|
self.request,
|
|
|
|
messages.ERROR,
|
|
|
|
_(u"Invalid login ticket")
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2015-06-12 21:57:11 +00:00
|
|
|
elif ret == self.USER_LOGIN_OK:
|
|
|
|
try:
|
2015-06-09 20:04:05 +00:00
|
|
|
self.user = models.User.objects.get(
|
2015-06-12 21:57:11 +00:00
|
|
|
username=self.request.session['username'],
|
|
|
|
session_key=self.request.session.session_key
|
|
|
|
)
|
2016-06-27 21:55:17 +00:00
|
|
|
self.user.save() # pragma: no cover (should not happend)
|
2015-06-12 21:57:11 +00:00
|
|
|
except models.User.DoesNotExist:
|
|
|
|
self.user = models.User.objects.create(
|
|
|
|
username=self.request.session['username'],
|
2015-06-11 21:34:25 +00:00
|
|
|
session_key=self.request.session.session_key
|
2015-06-09 20:04:05 +00:00
|
|
|
)
|
2015-06-12 21:57:11 +00:00
|
|
|
self.user.save()
|
|
|
|
elif ret == self.USER_LOGIN_FAILURE: # bad user login
|
|
|
|
self.logout()
|
|
|
|
elif ret == self.USER_ALREADY_LOGGED:
|
|
|
|
pass
|
|
|
|
else:
|
2016-06-27 21:55:17 +00:00
|
|
|
raise EnvironmentError("invalid output for LoginView.process_post") # pragma: no cover
|
2015-06-12 21:57:11 +00:00
|
|
|
return self.common()
|
|
|
|
|
2016-06-26 14:02:25 +00:00
|
|
|
def process_post(self):
|
2016-06-27 21:55:17 +00:00
|
|
|
"""
|
|
|
|
Analyse the POST request:
|
|
|
|
* check that the LoginTicket is valid
|
|
|
|
* check that the user sumited credentials are valid
|
|
|
|
"""
|
2015-06-12 21:57:11 +00:00
|
|
|
if not self.check_lt():
|
|
|
|
values = self.request.POST.copy()
|
|
|
|
# if not set a new LT and fail
|
2015-11-14 00:05:53 +00:00
|
|
|
values['lt'] = self.request.session['lt'][-1]
|
2015-06-12 21:57:11 +00:00
|
|
|
self.init_form(values)
|
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:
|
|
|
|
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-06-27 21:55:17 +00:00
|
|
|
"""Initialize GET received parameters"""
|
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-28 13:24:50 +00:00
|
|
|
self.warn = request.GET.get('warn')
|
2015-05-29 14:11:10 +00:00
|
|
|
|
2015-06-12 21:57:11 +00:00
|
|
|
def get(self, request, *args, **kwargs):
|
|
|
|
"""methode called on GET request on this view"""
|
|
|
|
self.init_get(request)
|
|
|
|
self.process_get()
|
|
|
|
return self.common()
|
|
|
|
|
|
|
|
def process_get(self):
|
2016-06-27 21:55:17 +00:00
|
|
|
"""Analyse the GET request"""
|
|
|
|
# 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:
|
2015-06-05 13:44:17 +00:00
|
|
|
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
|
|
|
|
2015-06-05 13:44:17 +00:00
|
|
|
def init_form(self, values=None):
|
2016-06-27 21:55:17 +00:00
|
|
|
"""Initialization of the good form depending of POST and GET parameters"""
|
2015-06-05 13:44:17 +00:00
|
|
|
self.form = forms.UserCredential(
|
|
|
|
values,
|
|
|
|
initial={
|
2015-06-12 16:10:52 +00:00
|
|
|
'service': self.service,
|
|
|
|
'method': self.method,
|
|
|
|
'warn': self.request.session.get("warn"),
|
2016-06-28 13:24:50 +00:00
|
|
|
'lt': self.request.session['lt'][-1],
|
|
|
|
'renew': self.renew
|
2015-06-05 13:44:17 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2015-05-29 14:11:10 +00:00
|
|
|
def service_login(self):
|
|
|
|
"""Perform login agains a service"""
|
|
|
|
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
|
|
|
)
|
2015-11-17 13:50:16 +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)
|
2015-11-17 13:50:16 +00:00
|
|
|
else:
|
2016-06-03 12:11:07 +00:00
|
|
|
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]
|
|
|
|
})
|
2015-11-17 13:50:16 +00:00
|
|
|
return render(
|
|
|
|
self.request,
|
|
|
|
settings.CAS_WARN_TEMPLATE,
|
2016-06-20 11:31:59 +00:00
|
|
|
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
|
2015-11-17 13:50:16 +00:00
|
|
|
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
|
|
|
)
|
2015-11-17 13:50:16 +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:
|
2015-11-17 13:50:16 +00:00
|
|
|
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:
|
2015-11-17 13:50:16 +00:00
|
|
|
error = 2
|
2015-05-29 14:11:10 +00:00
|
|
|
messages.add_message(
|
|
|
|
self.request,
|
|
|
|
messages.ERROR,
|
|
|
|
_(u"Username non allowed")
|
|
|
|
)
|
|
|
|
except models.BadFilter:
|
2015-11-17 13:50:16 +00:00
|
|
|
error = 3
|
2015-05-29 14:11:10 +00:00
|
|
|
messages.add_message(
|
|
|
|
self.request,
|
|
|
|
messages.ERROR,
|
|
|
|
_(u"User charateristics non allowed")
|
|
|
|
)
|
|
|
|
except models.UserFieldNotDefined:
|
2015-11-17 13:50:16 +00:00
|
|
|
error = 4
|
2015-05-29 14:11:10 +00:00
|
|
|
messages.add_message(
|
|
|
|
self.request,
|
|
|
|
messages.ERROR,
|
2015-06-12 16:10:52 +00:00
|
|
|
_(u"The attribut %(field)s is needed to use"
|
|
|
|
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
|
2015-11-17 13:50:16 +00:00
|
|
|
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
|
|
|
|
2015-11-17 13:50:16 +00:00
|
|
|
if not self.ajax:
|
|
|
|
return render(
|
|
|
|
self.request,
|
|
|
|
settings.CAS_LOGGED_TEMPLATE,
|
2016-06-20 11:31:59 +00:00
|
|
|
utils.context({'session': self.request.session})
|
2015-11-17 13:50:16 +00:00
|
|
|
)
|
|
|
|
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):
|
|
|
|
"""Processing authenticated users"""
|
|
|
|
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
|
|
|
)
|
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()
|
2015-11-17 13:50:16 +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)
|
2015-11-17 13:50:16 +00:00
|
|
|
else:
|
|
|
|
return utils.redirect_params("cas_server:login", params=self.request.GET)
|
2015-05-29 14:11:10 +00:00
|
|
|
|
|
|
|
# if login agains a service is self.requestest
|
|
|
|
if self.service:
|
|
|
|
return self.service_login()
|
|
|
|
else:
|
2015-11-17 13:50:16 +00:00
|
|
|
if self.ajax:
|
|
|
|
data = {"status": "success", "detail": "logged"}
|
2016-06-26 14:02:25 +00:00
|
|
|
return json_response(self.request, data)
|
2015-11-17 13:50:16 +00:00
|
|
|
else:
|
|
|
|
return render(
|
|
|
|
self.request,
|
|
|
|
settings.CAS_LOGGED_TEMPLATE,
|
2016-06-20 11:31:59 +00:00
|
|
|
utils.context({'session': self.request.session})
|
2015-11-17 13:50:16 +00:00
|
|
|
)
|
2015-05-29 14:11:10 +00:00
|
|
|
|
|
|
|
def not_authenticated(self):
|
|
|
|
"""Processing non authenticated users"""
|
|
|
|
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)
|
2015-11-17 13:50:16 +00:00
|
|
|
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
|
|
|
)
|
2015-11-17 13:50:16 +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)
|
2015-11-17 13:50:16 +00:00
|
|
|
else:
|
2016-06-20 11:31:59 +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):
|
|
|
|
"""Part execute uppon GET and POST request"""
|
|
|
|
# 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
|
|
|
|
2015-06-03 16:15:37 +00:00
|
|
|
class Auth(View):
|
|
|
|
"""A simple view to validate username/password/service tuple"""
|
|
|
|
@method_decorator(csrf_exempt)
|
|
|
|
def dispatch(self, request, *args, **kwargs):
|
|
|
|
"""dispatch requests based on method GET, POST, ..."""
|
|
|
|
return super(Auth, self).dispatch(request, *args, **kwargs)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def post(request):
|
|
|
|
"""methode called on GET request on this view"""
|
|
|
|
username = request.POST.get('username')
|
|
|
|
password = request.POST.get('password')
|
|
|
|
service = request.POST.get('service')
|
2015-06-03 16:32:15 +00:00
|
|
|
secret = request.POST.get('secret')
|
2015-06-03 16:15:37 +00:00
|
|
|
|
2015-06-03 16:32:15 +00:00
|
|
|
if not settings.CAS_AUTH_SHARED_SECRET:
|
|
|
|
return HttpResponse("no\nplease set CAS_AUTH_SHARED_SECRET", content_type="text/plain")
|
|
|
|
if secret != settings.CAS_AUTH_SHARED_SECRET:
|
|
|
|
return HttpResponse("no\n", content_type="text/plain")
|
2015-06-03 16:15:37 +00:00
|
|
|
if not username or not password or not service:
|
|
|
|
return HttpResponse("no\n", content_type="text/plain")
|
|
|
|
form = forms.UserCredential(
|
|
|
|
request.POST,
|
|
|
|
initial={
|
2015-06-12 16:10:52 +00:00
|
|
|
'service': service,
|
|
|
|
'method': 'POST',
|
|
|
|
'warn': False
|
2015-06-03 16:15:37 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
if form.is_valid():
|
|
|
|
try:
|
2015-06-12 21:57:11 +00:00
|
|
|
try:
|
|
|
|
user = models.User.objects.get(
|
|
|
|
username=form.cleaned_data['username'],
|
|
|
|
session_key=request.session.session_key
|
|
|
|
)
|
|
|
|
except models.User.DoesNotExist:
|
|
|
|
user = models.User.objects.create(
|
|
|
|
username=form.cleaned_data['username'],
|
|
|
|
session_key=request.session.session_key
|
|
|
|
)
|
|
|
|
user.save()
|
2015-06-03 16:15:37 +00:00
|
|
|
# is the service allowed
|
2015-06-08 00:51:22 +00:00
|
|
|
service_pattern = ServicePattern.validate(service)
|
2015-06-03 16:15:37 +00:00
|
|
|
# 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()
|
2015-06-03 16:15:37 +00:00
|
|
|
return HttpResponse("yes\n", content_type="text/plain")
|
2015-06-12 16:10:52 +00:00
|
|
|
except (ServicePattern.DoesNotExist, models.ServicePatternException):
|
2015-06-03 16:15:37 +00:00
|
|
|
return HttpResponse("no\n", content_type="text/plain")
|
|
|
|
else:
|
|
|
|
return HttpResponse("no\n", content_type="text/plain")
|
|
|
|
|
2015-06-12 16:10:52 +00:00
|
|
|
|
2015-05-29 17:27:54 +00:00
|
|
|
class Validate(View):
|
2015-05-27 19:56:39 +00:00
|
|
|
"""service ticket validation"""
|
2015-05-29 17:27:54 +00:00
|
|
|
@staticmethod
|
|
|
|
def get(request):
|
|
|
|
"""methode called on GET request on this view"""
|
|
|
|
service = request.GET.get('service')
|
|
|
|
ticket = request.GET.get('ticket')
|
|
|
|
renew = True if request.GET.get('renew') else False
|
|
|
|
if service and ticket:
|
|
|
|
try:
|
2015-06-08 00:51:22 +00:00
|
|
|
ticket = ServiceTicket.objects.get(
|
2015-05-29 17:27:54 +00:00
|
|
|
value=ticket,
|
|
|
|
service=service,
|
|
|
|
validate=False,
|
|
|
|
renew=renew,
|
2015-06-08 00:51:22 +00:00
|
|
|
creation__gt=(timezone.now() - timedelta(seconds=ServiceTicket.VALIDITY))
|
2015-05-29 17:27:54 +00:00
|
|
|
)
|
|
|
|
ticket.validate = True
|
|
|
|
ticket.save()
|
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
|
|
|
|
)
|
|
|
|
)
|
2016-04-29 17:57:12 +00:00
|
|
|
if (ticket.service_pattern.user_field and
|
|
|
|
ticket.user.attributs.get(ticket.service_pattern.user_field)):
|
|
|
|
username = ticket.user.attributs.get(
|
|
|
|
ticket.service_pattern.user_field
|
|
|
|
)
|
|
|
|
if isinstance(username, list):
|
2016-06-28 16:57:56 +00:00
|
|
|
# the list is not empty because we wont generate a ticket with a user_field
|
2016-06-28 15:46:59 +00:00
|
|
|
# that evaluate to False
|
|
|
|
username = username[0]
|
2016-04-29 17:57:12 +00:00
|
|
|
else:
|
|
|
|
username = ticket.user.username
|
|
|
|
return HttpResponse("yes\n%s\n" % username, content_type="text/plain")
|
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
|
|
|
|
)
|
|
|
|
)
|
2015-05-29 17:27:54 +00:00
|
|
|
return HttpResponse("no\n", content_type="text/plain")
|
|
|
|
else:
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.warning("Validate: service or ticket missing")
|
2015-05-16 21:43:46 +00:00
|
|
|
return HttpResponse("no\n", content_type="text/plain")
|
|
|
|
|
2015-05-27 19:56:39 +00:00
|
|
|
|
2015-05-29 17:27:54 +00:00
|
|
|
class ValidateError(Exception):
|
|
|
|
"""handle service validation error"""
|
|
|
|
def __init__(self, code, msg=""):
|
|
|
|
self.code = code
|
|
|
|
self.msg = msg
|
2015-05-29 17:31:04 +00:00
|
|
|
super(ValidateError, self).__init__(code)
|
2015-05-29 17:27:54 +00:00
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
return u"%s" % self.msg
|
|
|
|
|
|
|
|
def render(self, request):
|
|
|
|
"""render the error template for the exception"""
|
|
|
|
return render(
|
|
|
|
request,
|
|
|
|
"cas_server/serviceValidateError.xml",
|
2015-06-12 16:10:52 +00:00
|
|
|
{'code': self.code, 'msg': self.msg},
|
2015-05-29 17:27:54 +00:00
|
|
|
content_type="text/xml; charset=utf-8"
|
|
|
|
)
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-05-29 17:27:54 +00:00
|
|
|
|
|
|
|
class ValidateService(View, AttributesMixin):
|
|
|
|
"""service ticket validation [CAS 2.0] and [CAS 3.0]"""
|
|
|
|
request = None
|
|
|
|
service = None
|
|
|
|
ticket = None
|
|
|
|
pgt_url = None
|
|
|
|
renew = None
|
2015-05-29 17:33:42 +00:00
|
|
|
allow_proxy_ticket = False
|
2015-05-29 17:27:54 +00:00
|
|
|
|
2015-05-29 17:33:42 +00:00
|
|
|
def get(self, request):
|
2015-05-29 17:27:54 +00:00
|
|
|
"""methode called on GET request on this view"""
|
|
|
|
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
|
|
|
|
|
|
|
|
if not self.service or not self.ticket:
|
2015-12-13 12:50:29 +00:00
|
|
|
logger.warning("ValidateService: missing ticket or service")
|
2015-05-29 17:27:54 +00:00
|
|
|
return ValidateError(
|
|
|
|
'INVALID_REQUEST',
|
|
|
|
"you must specify a service and a ticket"
|
|
|
|
).render(request)
|
2015-05-16 21:43:46 +00:00
|
|
|
else:
|
2015-05-29 17:27:54 +00:00
|
|
|
try:
|
|
|
|
self.ticket, proxies = self.process_ticket()
|
|
|
|
params = {
|
2015-06-12 16:10:52 +00:00
|
|
|
'username': self.ticket.user.username,
|
|
|
|
'attributes': self.attributes(),
|
|
|
|
'proxies': proxies
|
2015-05-29 17:27:54 +00:00
|
|
|
}
|
2015-06-12 16:10:52 +00:00
|
|
|
if (self.ticket.service_pattern.user_field and
|
|
|
|
self.ticket.user.attributs.get(self.ticket.service_pattern.user_field)):
|
2015-05-29 17:27:54 +00:00
|
|
|
params['username'] = self.ticket.user.attributs.get(
|
|
|
|
self.ticket.service_pattern.user_field
|
|
|
|
)
|
2016-06-28 16:57:56 +00:00
|
|
|
if isinstance(params['username'], list):
|
|
|
|
# the list is not empty because we wont generate a ticket with a user_field
|
|
|
|
# that evaluate to False
|
|
|
|
params['username'] = params['username'][0]
|
2016-06-24 19:05:43 +00:00
|
|
|
if self.pgt_url and (
|
|
|
|
self.pgt_url.startswith("https://") or
|
|
|
|
re.match("^http://(127\.0\.0\.1|localhost)(:[0-9]+)?(/.*)?$", self.pgt_url)
|
|
|
|
):
|
2015-05-29 17:27:54 +00:00
|
|
|
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),
|
|
|
|
)
|
|
|
|
)
|
2015-05-29 17:27:54 +00:00
|
|
|
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)
|
|
|
|
)
|
2015-05-29 17:27:54 +00:00
|
|
|
return error.render(request)
|
|
|
|
|
|
|
|
def process_ticket(self):
|
|
|
|
"""fetch the ticket angains the database and check its validity"""
|
2015-05-16 21:43:46 +00:00
|
|
|
try:
|
|
|
|
proxies = []
|
2015-06-08 00:51:22 +00:00
|
|
|
if self.ticket.startswith(ServiceTicket.PREFIX):
|
|
|
|
ticket = ServiceTicket.objects.get(
|
2015-05-29 17:27:54 +00:00
|
|
|
value=self.ticket,
|
2015-05-27 19:56:39 +00:00
|
|
|
validate=False,
|
2015-05-29 17:27:54 +00:00
|
|
|
renew=self.renew,
|
2015-06-08 00:51:22 +00:00
|
|
|
creation__gt=(timezone.now() - timedelta(seconds=ServiceTicket.VALIDITY))
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
2015-06-08 00:51:22 +00:00
|
|
|
elif self.allow_proxy_ticket and self.ticket.startswith(ProxyTicket.PREFIX):
|
|
|
|
ticket = ProxyTicket.objects.get(
|
2015-05-29 17:27:54 +00:00
|
|
|
value=self.ticket,
|
2015-05-27 19:56:39 +00:00
|
|
|
validate=False,
|
2015-05-29 17:27:54 +00:00
|
|
|
renew=self.renew,
|
2015-06-08 00:51:22 +00:00
|
|
|
creation__gt=(timezone.now() - timedelta(seconds=ProxyTicket.VALIDITY))
|
2015-05-27 19:56:39 +00:00
|
|
|
)
|
|
|
|
for prox in ticket.proxies.all():
|
|
|
|
proxies.append(prox.url)
|
2015-05-29 17:27:54 +00:00
|
|
|
else:
|
2015-12-13 12:50:29 +00:00
|
|
|
raise ValidateError('INVALID_TICKET', self.ticket)
|
2015-05-16 21:43:46 +00:00
|
|
|
ticket.validate = True
|
|
|
|
ticket.save()
|
2015-05-29 17:27:54 +00:00
|
|
|
if ticket.service != self.service:
|
2015-12-13 12:50:29 +00:00
|
|
|
raise ValidateError('INVALID_SERVICE', self.service)
|
2015-05-29 17:27:54 +00:00
|
|
|
return ticket, proxies
|
2015-06-08 00:51:22 +00:00
|
|
|
except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist):
|
2015-05-29 17:27:54 +00:00
|
|
|
raise ValidateError('INVALID_TICKET', 'ticket not found')
|
|
|
|
|
|
|
|
def process_pgturl(self, params):
|
|
|
|
"""Handle PGT request"""
|
|
|
|
try:
|
2015-06-08 00:51:22 +00:00
|
|
|
pattern = ServicePattern.validate(self.pgt_url)
|
2015-05-29 17:27:54 +00:00
|
|
|
if pattern.proxy_callback:
|
|
|
|
proxyid = utils.gen_pgtiou()
|
2015-06-08 00:51:22 +00:00
|
|
|
pticket = ProxyGrantingTicket.objects.create(
|
2015-05-29 17:27:54 +00:00
|
|
|
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})
|
2015-05-29 17:27:54 +00:00
|
|
|
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),
|
|
|
|
)
|
|
|
|
)
|
2015-05-29 17:27:54 +00:00
|
|
|
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:
|
2015-05-29 17:27:54 +00:00
|
|
|
error = utils.unpack_nested_exception(error)
|
2016-06-28 16:57:56 +00:00
|
|
|
raise ValidateError(
|
|
|
|
'INVALID_PROXY_CALLBACK',
|
|
|
|
"%s: %s" % (type(error), str(error))
|
|
|
|
)
|
2015-05-16 21:43:46 +00:00
|
|
|
else:
|
2015-05-29 17:27:54 +00:00
|
|
|
raise ValidateError(
|
|
|
|
'INVALID_PROXY_CALLBACK',
|
|
|
|
"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:
|
2015-05-29 17:27:54 +00:00
|
|
|
raise ValidateError(
|
2015-05-28 13:08:57 +00:00
|
|
|
'INVALID_PROXY_CALLBACK',
|
|
|
|
'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
|
|
|
|
2015-05-29 17:27:54 +00:00
|
|
|
class Proxy(View):
|
2015-05-27 19:56:39 +00:00
|
|
|
"""proxy ticket service"""
|
2015-05-29 17:27:54 +00:00
|
|
|
|
|
|
|
request = None
|
|
|
|
pgt = None
|
|
|
|
target_service = None
|
|
|
|
|
|
|
|
def get(self, request):
|
|
|
|
"""methode called on GET request on this view"""
|
|
|
|
self.request = request
|
|
|
|
self.pgt = request.GET.get('pgt')
|
|
|
|
self.target_service = request.GET.get('targetService')
|
|
|
|
try:
|
|
|
|
if self.pgt and self.target_service:
|
|
|
|
return self.process_proxy()
|
|
|
|
else:
|
|
|
|
raise ValidateError(
|
|
|
|
'INVALID_REQUEST',
|
|
|
|
"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))
|
2015-05-29 17:27:54 +00:00
|
|
|
return error.render(request)
|
|
|
|
|
|
|
|
def process_proxy(self):
|
|
|
|
"""handle PT request"""
|
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)
|
2015-05-28 13:26:46 +00:00
|
|
|
if not pattern.proxy:
|
2015-05-29 17:27:54 +00:00
|
|
|
raise ValidateError(
|
2015-05-28 13:26:46 +00:00
|
|
|
'UNAUTHORIZED_SERVICE',
|
2015-12-13 12:50:29 +00:00
|
|
|
'the service %s do not allow proxy ticket' % self.target_service
|
2015-05-28 13:26:46 +00:00
|
|
|
)
|
2015-05-27 19:56:39 +00:00
|
|
|
# is the proxy granting ticket valid
|
2015-06-08 00:51:22 +00:00
|
|
|
ticket = ProxyGrantingTicket.objects.get(
|
2015-05-29 17:27:54 +00:00
|
|
|
value=self.pgt,
|
2015-11-13 23:17:31 +00:00
|
|
|
creation__gt=(timezone.now() - timedelta(seconds=ProxyGrantingTicket.VALIDITY)),
|
|
|
|
validate=False
|
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)
|
2015-05-29 17:27:54 +00:00
|
|
|
pticket = ticket.user.get_ticket(
|
2015-06-08 00:51:22 +00:00
|
|
|
ProxyTicket,
|
2015-05-29 17:27:54 +00:00
|
|
|
self.target_service,
|
|
|
|
pattern,
|
|
|
|
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(
|
2015-05-29 17:27:54 +00:00
|
|
|
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"
|
|
|
|
)
|
2015-06-08 00:51:22 +00:00
|
|
|
except ProxyGrantingTicket.DoesNotExist:
|
2015-12-13 12:50:29 +00:00
|
|
|
raise ValidateError('INVALID_TICKET', 'PGT %s not found' % self.pgt)
|
2015-06-08 00:51:22 +00:00
|
|
|
except ServicePattern.DoesNotExist:
|
2015-12-13 12:50:29 +00:00
|
|
|
raise ValidateError('UNAUTHORIZED_SERVICE', self.target_service)
|
2015-05-28 13:08:57 +00:00
|
|
|
except (models.BadUsername, models.BadFilter, models.UserFieldNotDefined):
|
2015-05-29 17:27:54 +00:00
|
|
|
raise ValidateError(
|
2015-05-28 13:08:57 +00:00
|
|
|
'UNAUTHORIZED_USER',
|
2016-06-28 22:01:51 +00:00
|
|
|
'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
|
|
|
|
|
|
|
|
2015-05-29 17:27:54 +00:00
|
|
|
class SamlValidateError(Exception):
|
|
|
|
"""handle saml validation error"""
|
|
|
|
def __init__(self, code, msg=""):
|
|
|
|
self.code = code
|
|
|
|
self.msg = msg
|
2015-05-29 17:31:04 +00:00
|
|
|
super(SamlValidateError, self).__init__(code)
|
2015-05-29 17:27:54 +00:00
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
return u"%s" % self.msg
|
|
|
|
|
|
|
|
def render(self, request):
|
|
|
|
"""render the error template for the exception"""
|
|
|
|
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()
|
2015-05-29 17:27:54 +00:00
|
|
|
},
|
|
|
|
content_type="text/xml; charset=utf-8"
|
|
|
|
)
|
2015-05-22 17:31:50 +00:00
|
|
|
|
2015-05-28 13:08:57 +00:00
|
|
|
|
2015-05-29 17:27:54 +00:00
|
|
|
class SamlValidate(View, AttributesMixin):
|
|
|
|
"""SAML ticket validation"""
|
|
|
|
request = None
|
|
|
|
target = None
|
|
|
|
ticket = None
|
|
|
|
root = None
|
|
|
|
|
|
|
|
@method_decorator(csrf_exempt)
|
|
|
|
def dispatch(self, request, *args, **kwargs):
|
|
|
|
"""dispatch requests based on method GET, POST, ..."""
|
2015-05-29 18:07:53 +00:00
|
|
|
return super(SamlValidate, self).dispatch(request, *args, **kwargs)
|
2015-05-29 17:27:54 +00:00
|
|
|
|
|
|
|
def post(self, request):
|
|
|
|
"""methode called on POST request on this view"""
|
|
|
|
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()
|
2015-05-29 17:27:54 +00:00
|
|
|
attributes = self.attributes()
|
|
|
|
params = {
|
2015-06-12 16:10:52 +00:00
|
|
|
'IssueInstant': timezone.now().isoformat(),
|
|
|
|
'expireInstant': expire_instant,
|
|
|
|
'Recipient': self.target,
|
|
|
|
'ResponseID': utils.gen_saml_id(),
|
|
|
|
'username': self.ticket.user.username,
|
|
|
|
'attributes': attributes
|
2015-05-29 17:27:54 +00:00
|
|
|
}
|
2016-06-29 15:07:49 +00:00
|
|
|
if (self.ticket.service_pattern.user_field and
|
|
|
|
self.ticket.user.attributs.get(self.ticket.service_pattern.user_field)):
|
2015-05-29 17:27:54 +00:00
|
|
|
params['username'] = self.ticket.user.attributs.get(
|
|
|
|
self.ticket.service_pattern.user_field
|
|
|
|
)
|
2016-06-29 15:07:49 +00:00
|
|
|
if isinstance(params['username'], list):
|
|
|
|
# the list is not empty because we wont generate a ticket with a user_field
|
|
|
|
# that evaluate to False
|
|
|
|
params['username'] = params['username'][0]
|
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)
|
|
|
|
)
|
|
|
|
|
2015-05-29 17:27:54 +00:00
|
|
|
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))
|
2015-05-29 17:27:54 +00:00
|
|
|
return error.render(request)
|
|
|
|
|
|
|
|
def process_ticket(self):
|
|
|
|
"""validate ticket from SAML XML body"""
|
2015-05-22 17:31:50 +00:00
|
|
|
try:
|
2015-05-29 17:27:54 +00:00
|
|
|
auth_req = self.root.getchildren()[1].getchildren()[0]
|
2015-05-22 17:31:50 +00:00
|
|
|
ticket = auth_req.getchildren()[0].text
|
2015-06-08 00:51:22 +00:00
|
|
|
if ticket.startswith(ServiceTicket.PREFIX):
|
|
|
|
ticket = ServiceTicket.objects.get(
|
2015-05-28 13:08:57 +00:00
|
|
|
value=ticket,
|
|
|
|
validate=False,
|
2015-06-08 00:51:22 +00:00
|
|
|
creation__gt=(timezone.now() - timedelta(seconds=ServiceTicket.VALIDITY))
|
2015-05-28 13:08:57 +00:00
|
|
|
)
|
2015-06-08 00:51:22 +00:00
|
|
|
elif ticket.startswith(ProxyTicket.PREFIX):
|
|
|
|
ticket = ProxyTicket.objects.get(
|
2015-05-28 13:08:57 +00:00
|
|
|
value=ticket,
|
|
|
|
validate=False,
|
2015-06-08 00:51:22 +00:00
|
|
|
creation__gt=(timezone.now() - timedelta(seconds=ProxyTicket.VALIDITY))
|
2015-05-28 13:08:57 +00:00
|
|
|
)
|
|
|
|
else:
|
2015-05-29 17:27:54 +00:00
|
|
|
raise SamlValidateError(
|
2015-05-28 13:08:57 +00:00
|
|
|
'AuthnFailed',
|
2015-12-13 12:50:29 +00:00
|
|
|
'ticket %s should begin with PT- or ST-' % ticket
|
2015-05-28 13:08:57 +00:00
|
|
|
)
|
2015-05-22 17:31:50 +00:00
|
|
|
ticket.validate = True
|
|
|
|
ticket.save()
|
2015-05-29 17:27:54 +00:00
|
|
|
if ticket.service != self.target:
|
|
|
|
raise SamlValidateError(
|
2015-05-28 13:08:57 +00:00
|
|
|
'AuthnFailed',
|
2015-12-13 12:50:29 +00:00
|
|
|
'TARGET %s do not match ticket service' % self.target
|
2015-05-28 13:08:57 +00:00
|
|
|
)
|
2015-05-29 17:27:54 +00:00
|
|
|
return ticket
|
2015-05-28 13:08:57 +00:00
|
|
|
except (IndexError, KeyError):
|
2015-05-29 17:27:54 +00:00
|
|
|
raise SamlValidateError('VersionMismatch')
|
2015-06-08 00:51:22 +00:00
|
|
|
except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist):
|
2015-12-13 12:50:29 +00:00
|
|
|
raise SamlValidateError('AuthnFailed', 'ticket %s not found' % ticket)
|