-
-
Save jlhawn/1f61751f2bd2a0a7df4d to your computer and use it in GitHub Desktop.
Discourse SSO in a Django View
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@login_required | |
def discourse_sso(request): | |
sso_secret = settings.DOCKER_DISCOURSE_SSO_SECRET | |
payload = request.GET.get('sso', '') | |
signature = request.GET.get('sig', '') | |
log.debug("Handling discourse SSO request with payload: " | |
"%s. Signature: %s.", payload, signature) | |
# Validate the Signature. | |
expected_signature = hmac.new(sso_secret, payload, sha256).hexdigest() | |
if signature != expected_signature: | |
log.info("Invalid signature for discourse SSO request. " | |
"Payload: %s. Signature: %s. Expected Signature: %s.", | |
payload, signature, expected_signature) | |
raise Http404() | |
# Extract nonce data from the payload. | |
try: | |
payload = base64.b64decode(payload) | |
payload_data = urlparse.parse_qs(payload) | |
except (TypeError, ValueError) as error: | |
log.info("Invalid discourse SSO payload: %s", error.message) | |
raise Http404() | |
# Create new payload data with original nonce. | |
payload_data.update({ | |
'external_id': request.user.id, | |
'username': request.user.username, | |
'email': request.user.email, | |
'name': request.user.full_name, | |
}) | |
# Base64 encode the payload query string. | |
payload = urlencode(payload_data) | |
payload = base64.b64encode(payload) | |
# Generate a Signature of the payload. | |
signature = hmac.new(sso_secret, payload, sha256).hexdigest() | |
# Create new query string for redirect. | |
redirect_data = { | |
'sso': payload, | |
'sig': signature, | |
} | |
redirect_query = urlencode(redirect_data) | |
# Generate redirect URL. | |
redirect_url_format = '{url_base}?{query_string}' | |
redirect_url = redirect_url_format.format( | |
url_base=settings.DOCKER_DISCOURSE_SSO_URL, | |
query_string=redirect_query, | |
) | |
return HttpResponseRedirect(redirect_url) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment