Skip to content

Instantly share code, notes, and snippets.

@JordanReiter
Last active November 1, 2017 14:57
Show Gist options
  • Save JordanReiter/24edbcce8a1c74227f408fa30cfa873d to your computer and use it in GitHub Desktop.
Save JordanReiter/24edbcce8a1c74227f408fa30cfa873d to your computer and use it in GitHub Desktop.
Automatic sign-in for already-authenticated users for SSO based on django-cas-provider
window.CASLogin = window.CASLogin || (function () {
var action = "{{ action|safe }}",
ticket = {% if ticket %}"{{ ticket.ticket }}"{% else %}null{% endif %},
logged_in = {{ logged_in|lower|default:"false" }},
username = {% if request.user.is_authenticated %}"{{ request.user.username }}"{% else %}null{% endif %},
email = {% if email %}"{{ email }}"{% else %}null{% endif %};
function authenticate() {
if (!logged_in) {
window.location.href = action;
} else {
window.location.replace(action);
}
}
function identify(url) {
if (logged_in) {
window.location.replace(
(url ? add_ticket(url) : action)
);
}
}
function add_ticket(url) {
return url + (url.indexOf('?') === -1 ? '?' : '&') + 'ticket=' + ticket;
}
return {
'username': username,
'email': email,
'is_logged_in': logged_in,
'identify': identify,
'authenticate': authenticate
}
}());
<body>
<p>Content of page</p>
<script src="http://login.example.org/login.js?service={{ request.build_absolute_uri }}"></script>
<script>
CASLogin.identify();
</script>
</body>
from django.http import HttpResponseBadRequest
from django.utils.http import urlencode
from django.shortcuts import render
from django.core.urlresolvers import reverse
from cas_provider.models import ServiceTicket
def script_login(request, template_name="cas/login-template.js"):
service = request.GET.get("service")
if not service:
return HttpResponseBadRequest("No value given for service.")
if request.user.is_authenticated():
logged_in = True
email = request.user.email
ticket = ServiceTicket.objects.create(
service=service,
user=request.user
)
action = ticket.get_redirect_url()
else:
action = "%s://%s%s%s" % (
'https' if request.is_secure() else 'http',
request.get_host(),
reverse('cas_login'),
(
"?%s" % urlencode(
dict(
service=service
)
)
if service else ""
)
)
return render(
request,
template_name,
locals(),
content_type="application/javascript"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment