server/src/metaeducation/auth.py
author durandn
Thu, 03 Mar 2016 17:06:20 +0100
changeset 11 cfc868991b82
parent 6 39cecdd5260e
child 32 eb9e83610c99
permissions -rw-r--r--
Added custom user model to store extra data from the GED + corrected signals and api auth class so they interface correctly with the ged

from rest_framework.authentication import BaseAuthentication
from django.contrib.auth import get_user_model, login
from django.contrib.auth.models import Permission
from django.conf import settings
from urllib import parse
import requests
import re
import json

class MtdcOAuth2ClientCredentialsAuthentication(BaseAuthentication):
    
    def authenticate(self, request):
        # get token, get username
        if ("act_as" not in request.GET) and ('HTTP_RENKAN_ACT_AS' not in request.META):
            return
        else:
            external_id = request.GET.get('act_as', request.META.get("HTTP_RENKAN_ACT_AS", ""))
        try: 
            user = get_user_model().objects.get(external_id=external_id)
        except get_user_model().DoesNotExist:
            return
        if 'HTTP_AUTHORIZATION' not in request.META:
            return
        else:
            token = re.search("(?<=\s).*", request.META["HTTP_AUTHORIZATION"]).group(0)
        print(token)
        # send token to Oauth server
        token_validate_response = requests.get(
            settings.MTDC_VALIDATE_TOKEN_BASE_URL+token+"?redirect_uri="+parse.quote_plus(settings.MTDC_GED_BASE_URL)
        )
        if token_validate_response.status_code != 200:
            return
        return (user, None)