server/src/metaeducation/mtdc_oauth_provider/views.py
author durandn
Mon, 14 Mar 2016 15:08:25 +0100
changeset 35 e82a0ac6cc2c
parent 32 eb9e83610c99
child 63 6bfac7c633a0
permissions -rw-r--r--
used '%r' and removed '+str()' in logger.debug() calls
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
     1
import requests, logging
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
     2
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
     3
from datetime import timedelta
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
     4
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
     5
from django.core.exceptions import PermissionDenied
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
     6
from django.core.urlresolvers import reverse
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
     7
from django.contrib.auth.models import Permission
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
     8
from django.contrib.auth import get_user_model
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
     9
from django.http import HttpResponseRedirect
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    10
from django.utils import timezone
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    11
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    12
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    13
                                                          OAuth2View,
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    14
                                                          OAuth2LoginView,
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    15
                                                          OAuth2CallbackView)
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    16
from allauth.socialaccount.providers.oauth2.client import (OAuth2Client,
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    17
                                                           OAuth2Error)
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    18
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    19
from allauth.socialaccount.helpers import complete_social_login, render_authentication_error
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    20
from allauth.socialaccount.models import SocialToken, SocialLogin
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    21
from allauth.account import app_settings
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    22
from allauth.account.utils import perform_login
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    23
from allauth.utils import build_absolute_uri, get_request_param
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    24
from allauth.socialaccount.providers.base import AuthAction, AuthError
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    25
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    26
from django.conf import settings
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    27
from urllib.parse import urlparse
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    28
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    29
from .provider import MtdcProvider
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    30
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
    31
logger = logging.getLogger(__name__)
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
    32
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    33
class MtdcOAuth2Adapter(OAuth2Adapter, DefaultSocialAccountAdapter):
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    34
    provider_id = MtdcProvider.id
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    35
    supports_state = False
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    36
    
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    37
    oauth_base_url = ""
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    38
    access_token_url = ""
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    39
    authorize_url = ""
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    40
    profile_url = ""
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    41
    
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    42
    def __init__(self, request=None):
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    43
        if request:
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
    44
            logger.debug("AUTHORIZATION CODE AUTH: init adapter")
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    45
            if request.session.get("OAUTH_CONTEXT_BASE_URL", None) is None:
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
    46
                logger.debug("AUTHORIZATION CODE AUTH: no context in session, storing context")
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    47
                request.session["OAUTH_CONTEXT_BASE_URL"] = request.GET.get("context", None)
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    48
                logger.debug("AUTHORIZATION CODE AUTH: context queryarg is %r", request.GET.get("context", None))
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    49
            self.oauth_base_url = request.session.get("OAUTH_CONTEXT_BASE_URL", None)
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    50
            logger.debug("AUTHORIZATION CODE AUTH: context is %r", self.oauth_base_url)
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    51
            self.access_token_url = self.oauth_base_url + settings.MTDC_ACCESS_TOKEN_URL
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    52
            self.authorize_url = self.oauth_base_url + settings.MTDC_AUTHORIZE_URL
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    53
            self.profile_url = self.oauth_base_url + settings.MTDC_PROFILE_URL
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    54
    
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    55
    def pre_social_login(self, request, sociallogin):
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    56
        try:
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    57
            logger.debug("AUTHORIZATION CODE AUTH: login almost complete, checking if user %r exists", sociallogin.account.extra_data.get('external_id', 'NO_ID'))
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
    58
            user = get_user_model().objects.get(external_id=sociallogin.account.extra_data.get('external_id', ''))  # if user exists, connect the account to the existing account and login
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    59
            logger.debug("AUTHORIZATION CODE AUTH: user %r exists, connecting to existing account", sociallogin.account.extra_data.get('external_id', 'NO_ID'))
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
    60
            sociallogin.state['process'] = 'connect'             
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    61
            perform_login(request, user, 'none')
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    62
        except get_user_model().DoesNotExist:
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    63
            logger.debug("AUTHORIZATION CODE AUTH: user %r does not exist", sociallogin.account.extra_data.get('external_id', 'NO_ID'))
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    64
    
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    65
    def get_login_redirect_url(self, request):
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    66
        return super(MtdcOAuth2Adapter, self).get_login_redirect_url(self, request)
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    67
    
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    68
    def new_user(self, request, sociallogin):
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    69
        if 'username' in sociallogin.account.extra_data:
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    70
            logger.debug("AUTHORIZATION CODE AUTH: checking if user %r exists to populate sociallogin", sociallogin.account.extra_data.get('external_id', 'NO_ID'))
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    71
            user_queryset = get_user_model().objects.filter(external_id=sociallogin.account.extra_data.get('external_id', ''), username=sociallogin.account.extra_data['username'])
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    72
            if user_queryset.exists():
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    73
                logger.debug("AUTHORIZATION CODE AUTH: user %r exists", sociallogin.account.extra_data.get('external_id', 'NO_ID'))
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    74
                user = user_queryset.first()
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    75
            else:
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
    76
                logger.debug("AUTHORIZATION CODE AUTH: user %r does not exist, creating new user and populating", sociallogin.account.extra_data.get('external_id', 'NO_ID'))
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    77
                user = get_user_model()()
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    78
                user.username = sociallogin.account.extra_data.get('username', '')
9
fdbc47f06361 adding custom user model + corrected provider to correctly create user according to new model
durandn
parents: 7
diff changeset
    79
                user.external_id = sociallogin.account.extra_data.get('external_id', '')
29
23de98e32b3b added uai field to user model and corresponding migrations + edited test oauth server to serve uai info for testing
durandn
parents: 11
diff changeset
    80
                user.uai = sociallogin.account.extra_data.get('uai', '')
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    81
            return user
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    82
        else:
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
    83
            logger.debug("AUTHORIZATION CODE AUTH: no username in extra data")
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    84
            return get_user_model()()
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    85
        
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    86
    def populate_user(self,
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    87
                      request,
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    88
                      sociallogin,
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    89
                      data):
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    90
        username = data.get('username')
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    91
        user = sociallogin.user
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    92
        user.username = username
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    93
        user.save()
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    94
        add_permission = Permission.objects.get(codename="add_renkan")
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    95
        user.user_permissions.add(add_permission)
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    96
        return user
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
    97
    
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
    98
    def complete_login(self, request, app, token, **kwargs):
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
    99
        logger.debug("AUTHORIZATION CODE AUTH: complete_login: getting profile info")
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   100
        resp = requests.get(self.profile_url,
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   101
                            params={'access_token': token.token})
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   102
        extra_data = resp.json()
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
   103
        
35
e82a0ac6cc2c used '%r' and removed '+str()' in logger.debug() calls
durandn
parents: 32
diff changeset
   104
        logger.debug("AUTHORIZATION CODE AUTH: response extra_data: %r ", extra_data)
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
   105
        if request.session.get("OAUTH_CONTEXT_BASE_URL", None) is not None:
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
   106
            del request.session["OAUTH_CONTEXT_BASE_URL"]
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   107
        return self.get_provider().sociallogin_from_response(request,
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   108
                                                             extra_data)
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   109
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   110
class MtdcOAuth2View(OAuth2View):
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   111
    @classmethod
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   112
    def adapter_view(cls, adapter):
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   113
        def view(request, *args, **kwargs):
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   114
            self = cls()
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   115
            self.request = request
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   116
            self.adapter = adapter(request)
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   117
            return self.dispatch(request, *args, **kwargs)
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   118
        return view
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   119
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
   120
class MtdcOAuth2LoginView(MtdcOAuth2View, OAuth2LoginView):
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   121
    def dispatch(self, request):
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
   122
        logger.debug("AUTHORIZATION CODE AUTH: dispatching LoginView")
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
   123
        return super(MtdcOAuth2LoginView, self).dispatch(request)
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
   124
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
   125
class MtdcOAuth2CallbackView(MtdcOAuth2View, OAuth2CallbackView):
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
   126
    def dispatch(self, request):
32
eb9e83610c99 added logging and logs config
durandn
parents: 29
diff changeset
   127
        logger.debug("AUTHORIZATION CODE AUTH: dispatching CallbackView")
6
39cecdd5260e Added OAuth2 Client Credentials Authentication workflow for Mtdc Application + Corrected mistakes on Authorization Code flow
durandn
parents: 1
diff changeset
   128
        return super(MtdcOAuth2CallbackView, self).dispatch(request)
1
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   129
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   130
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   131
oauth2_login = MtdcOAuth2LoginView.adapter_view(MtdcOAuth2Adapter)
5f50937893ac Commit work on metaeducation
durandn
parents:
diff changeset
   132
oauth2_callback = MtdcOAuth2CallbackView.adapter_view(MtdcOAuth2Adapter)